-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUVa-11503.cpp
More file actions
98 lines (80 loc) · 1.94 KB
/
UVa-11503.cpp
File metadata and controls
98 lines (80 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h> // here we have all the STL we need, including istringstream and ostringstream
#define ALL(x) x.begin(), x.end()
#define FAST std::cin.tie(0); ios::sync_with_stdio(false); std::cout.tie(0);
using namespace std;
#define vi vector<int>
void solve();
class UnionFind
{ // OOP style
private:
vi p, rank;
vi size;
public:
UnionFind(int N)
{
rank.assign(N, 0);
p.assign(N, 0);
for (int i = 0; i < N; i++)
p[i] = i;
size.assign(N, 1);
}
int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }
bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }
void unionSet(int i, int j)
{
if (!isSameSet(i, j))
{
// if from different set
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
size[x] += size[y];
}
// rank keeps the tree short
else
{
p[x] = y;
if (rank[x] == rank[y])
rank[y]++;
size[y] += size[x];
}
}
}
int sizeOfSet(int i) {
return size[findSet(i)];
}
};
int main(void) {
FAST
int T;
cin >> T;
while (T--) {
solve();
}
// return 0; // it is not necessary to return 0 in C++ main function
}
void solve() {
// map <string, int> m;
unordered_map <string, int> m;
UnionFind UF(100000);
int F;
cin >> F;
int count = 0;
while (F--) {
string s1, s2;
cin >> s1 >> s2;
if (m.find(s1) == m.end()) {
m[s1] = count++;
}
if (m.find(s2) == m.end()) {
m[s2] = count++;
}
UF.unionSet(m[s1], m[s2]);
cout << UF.sizeOfSet(m[s1]) << "\n";
}
}