Problem Description
Problem Analysis
Enjoy the meaningless satisfaction of applying a template
Even though I solved this problem long ago
This time I used path compression plus union by rank
Oh man…
Using this template so much, I don’t even know whether to put the solution in the Union-Find notes or write it here…
For this problem specifically…
Good grief…
Nothing much to say
A standard Union-Find problem
Just read the Union-Find notes
Book Notes: Union-Find — Merge and Query
Then output the total number of components minus 1
and the graph becomes connected
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
| #include<stdio.h>
int par[1020];
int rank[1020];
int find(int m) {
if(par[m]==m) {
return m;
} else
return par[m]=find(par[m]);
}
void unite(int x,int y) {
x=find(x);
y=find(y);
if(x==y)
return;
else {
if(rank[x]<rank[y]) {
par[x]=y;
} else {
par[y]=x;
if(rank[x]==rank[y])
rank[x]++;
}
}
}
int main() {
int N,M;
while(scanf("%d", &N),N) {
scanf("%d", &M);
for(int i=1; i<=N; i++) {
par[i]=i;
rank[i]=0;
}
while(M--) {
int u,v;
scanf("%d %d",&u,&v);
unite(u,v);
}
int cnt=0;
for(int i=1; i<=N; i++) {
if(par[i]==i)
cnt++;
}
printf("%d\n",cnt-1);
}
return 0;
}
|
Problem link: HDU 1232 Smooth Traffic Project