Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8129 Accepted Submission(s): 4052
本题非常简单就是锻炼学习并查集的,只要是能连在一起的就放在一个集合里面,最后看有多少个集合,然后用集合-1就是所要求得的结果;
代码:
1 #include<stdio.h>
2 int father[1005],rank[1005];
3 int find(int x)
4 {
5 if(x!=father[x])
6 father[x]=find(father[x]);
7 return father[x];
8 }
9 void Union(int x,int y)
10 {
11 if(x==y)
12 return ;
13 if(rank[x]>rank[y])
14 father[y]=x;
15 else
16 {
17 if(rank[x]==rank[y])
18 rank[y]++;
19 father[x]=y;
20 }
21 }
22 int main()
23 {
24 int n,m,i,k,f,ff,a,b,c[1005],j;
25 while(scanf("%d",&n)!=EOF)
26 {
27 if(n==0)
28 break;
29 scanf("%d",&m);
30 for(i=1;i<=n;i++)
31 {
32 father[i]=i;
33 rank[i]=0;
34 }
35 while(m--)
36 {
37 scanf("%d%d",&a,&b);
38 f=find(a);
39 ff=find(b);
40 Union(f,ff);
41 }
42 k=0;
43 for(i=1;i<=n;i++)
44 {
45 f=find(i);
46 for(j=1;j<=k;j++)
47 if(f==c[j])
48 break;
49 if(j>k)
50 c[++k]=f;
51 }
52 printf("%d\n",k-1);
53 }
54 return 0;
55 }
56
57
58