-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomponents in graph(union datastructure)
57 lines (46 loc) · 1.12 KB
/
components in graph(union datastructure)
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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int findset(int x, vector <int> &r) {
// we compress path here too
if (r[x]!=x) r[x]=findset(r[x],r);
return(r[x]);
}
int main() {
int n,q,i;
cin >> q;
n=2*q;
// makeset
vector <int> root(n+1);
vector <int> count(n+1);
for (int i=1;i<=n;i++) {
root[i]=i;
count[i]=1;
}
while (q--) {
int x,y;
cin >> x >> y;
// find root of x & y
int rx=findset(x,root);
int ry=findset(y,root);
// skip, already in same community
if (rx==ry) continue;
// do a union not using ranking
root[rx]=ry;
count[ry]+=count[rx];
count[rx]=0;
}
sort(count.begin(),count.end());
for(i=0;i<=n;i++)
{
if(count[i]!=0 && count[i]!=1)
{
printf("%d %d",count[i],count[n]);
break;
}
}
return 0;
}