找同乡

题目链接: http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1683&konwledgeId=135

解题思路: 并查集。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int MAXN = 100005;
 5 
 6 int f[MAXN];
 7 int num[MAXN];
 8 int n,m;
 9 
10 int getFather(int x)
11 {
12     if (x==f[x]) return f[x];
13     return f[x]=getFather(f[x]);
14 }
15 
16 void union_set(int x,int y)
17 {
18     int fx=getFather(x);
19     int fy=getFather(y);
20     if (fx!=fy) f[fx]=fy,num[fy]+=num[fx];
21 }
22 
23 void init()
24 {
25     for (int i=0;i<=n;++i)
26         num[i]=1, f[i]=i;
27 }
28 
29 int main()
30 {
31 #ifndef ONLINE_JUDGE
32     freopen("test.txt","r",stdin);
33 #endif // ONLINE_JUDGE
34     while(cin>>n>>m)
35     {
36         if (n==0 && m==0) break;
37         init();
38         int x,y;
39         for (int i=1;i<=m;++i) scanf("%d%d",&x,&y), union_set(x,y);
40         int ans=getFather(1);
41         printf("%d\n",num[ans]-1);
42     }
43     return 0;
44 }

 

posted @ 2018-04-20 22:40  只会一点暴力  阅读(214)  评论(0编辑  收藏  举报