题目1526:朋友圈

题目描述:

假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写程序求出这n个人里一共有多少个朋友圈。
假如:n = 5 , m = 3 , r = {{1 , 2} , {2 , 3} , {4 , 5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈,结果为2个朋友圈。

 

输入:

输入包含多个测试用例,每个测试用例的第一行包含两个正整数 n、m,1=<n,m<=100000。接下来有m行,每行分别输入两个人的编号f,t(1=<f,t<=n),表示f和t是好友。 当n为0时,输入结束,该用例不被处理。

 

输出:

对应每个测试用例,输出在这n个人里一共有多少个朋友圈。

 

样例输入:
5 3
1 2
2 3
4 5
3 3
1 2
1 3
2 3
0
样例输出:
2
1

 1 #include <set>  //1526
 2 #include <map>
 3 #include <list>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <deque>
 7 #include <queue>
 8 #include <stack>
 9 #include <cstdio>
10 #include <string>
11 #include <vector>
12 #include <cctype>
13 #include <cstring>
14 #include <sstream>
15 #include <fstream>
16 #include <cstdlib>
17 #include <cassert>
18 #include <iostream>
19 #include <algorithm>
20   
21 using namespace std;
22   
23   
24   
25   
26 const int MAX = 100005;
27   
28 int pre[MAX];
29   
30 int Ans;
31   
32  
33  
34  
35 int find(int x)
36 { 
37     int r = x; 
38     while(pre[r] != r) 
39         r = pre[r]; 
40     int i = x; 
41     int j; 
42     while(i != r) 
43     { 
44         j = pre[i]; 
45         pre[i] = r; 
46         i = j; 
47     } 
48  
49     return r;
50 }
51 void Merge(int x,int y)
52 {
53     int xf = find(x);
54     int yf = find(y);
55     if(xf != yf)
56     {
57         pre[xf] = yf;
58         --Ans;
59     }
60 }
61   
62 int main()
63 {
64     int N,M,i,x,y;
65   
66     while(cin >> N >> M)
67     {
68         if(N == 0) 
69             break;
70   
71         Ans = N; 
72   
73         for(i = 1;i <= N; ++i) 
74             pre[i] = i;
75   
76         while( M-- )
77         {
78             cin >> x >> y;
79             Merge(x,y);
80         }
81   
82         cout<<Ans<<endl;
83     }
84 }  
原文地址:https://www.cnblogs.com/chchche/p/3466022.html