-
Notifications
You must be signed in to change notification settings - Fork 10
/
union_find.cpp
69 lines (66 loc) · 1.02 KB
/
union_find.cpp
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
#include<stdio.h>
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<string.h>
#include <tr1/unordered_map>
#define MAX 200001
using namespace std;
int size[MAX];
int parent[MAX];
int root(int i)
{
while(i!=parent[i]) i = parent[i];
return i;
}
void unite(int a,int b)
{
int ra = root(a);
int rb = root(b);
if(ra==rb) return;
if(size[ra]>size[rb])
{
parent[rb] = ra;
size[ra] += size[rb];
}
else { parent[ra] = rb;
size[rb] += size[ra];
}
return;
}
int main()
{
int test;
scanf("%d",&test);
while(test--)
{
tr1::unordered_map<string,int> table;
int n;
scanf("%d",&n);
int index = 1;
while(n--)
{
string a,b;
cin>>a>>b;
if(!table[a])
{
table[a] = index;
size[index] = 1;
parent[index] = index;
index++;
}
if(!table[b])
{
table[b] = index;
parent[index] = index;
size[index] = 1;
index++;
}
// union of two sets!
unite(table[a],table[b]);
printf("%d\n",size[root(table[a])]);
}
}
return 0;
}