1
2
3
4
5
6
7
8
9
10 #include
11 using namespace std;
12 const int N=1010;
13 int p[N];
14 int n,m;
15 void Merge(int x,int y)
16 {
17 int rx=x;
18 int ry=y;
19 while(p[rx]!=-1)
20 rx=p[rx];
21 while(p[ry]!=-1)
22 ry=p[ry];
23 int i=x;
24 int t;
25 while(p[i]!=-1)
26 {
27 t=p[i];
28 p[i]=rx;
29 i=t;
30 }
31 i=y;
32 while(p[i]!=-1)
33 {
34 t=p[i];
35 p[i]=rx;
36 i=t;
37 }
38 if(ry!=rx)
39 p[ry]=rx;
40 return;
41 }
42 int main()
43 {
44 int x,y;
45 while(scanf("%d",&n)!=EOF)
46 {
47 if(n==0)
48 break;
49 scanf("%d",&m);
50 memset(p,-1,sizeof(p));
51 for(int i=0;i<m;i++)
52 {
53 scanf("%d %d",&x,&y);
54 Merge(x,y);
55 }
56 int ans=0;
57 for(int i=1;i<=n;i++)
58 if(p[i]==-1)
59 ans++;
60 printf("%d\n",ans-1);
61 }
62 }
hdu1232 参考答案 (2008-10-22 14:42:30由218编辑)