数据结构与算法题目集(中文)---7-25 朋友圈 (考察并查集)

  某学校有N个学生,形成M个俱乐部。每个俱乐部里的学生有着一定相似的兴趣爱好,形成一个朋友圈。一个学生可以同时属于若干个不同的俱乐部。根据“我的朋友的朋友也是我的朋友”这个推论可以得出,如果A和B是朋友,且B和C是朋友,则A和C也是朋友。请编写程序计算最大朋友圈中有多少人。

输入格式:

输入的第一行包含两个正整数N(≤30000)和M(≤1000),分别代表学校的学生总数和俱乐部的个数。后面的M行每行按以下格式给出1个俱乐部的信息,其中学生从1~N编号:

第i个俱乐部的人数Mi(空格)学生1(空格)学生2 … 学生Mi

输出格式:

输出给出一个整数,表示在最大朋友圈中有多少人。

输入样例:

7 4
3 1 2 3
2 1 4
3 5 6 7
1 6

输出样例:

4
 1 #include<iostream>
 2 #include<vector>
 3 #include<map>
 4 using namespace std;
 5 
 6 const int maxn = 300100;
 7 int father[maxn];
 8 int isRoot[maxn] = {0};
 9 map<int,vector<int> > mp;
10 void init(int n) {
11     for(int i = 1; i <= n; ++i)
12         father[i] = i;
13 }
14 
15 int findfather(int a) {
16     int b = a;
17     while(a != father[a])
18         a = father[a];
19     while(b != father[b]) {
20         int t = b;
21         b = father[b];
22         father[t] = a;
23     }
24     return a;
25 }
26 
27 void Union(int a,int b) {
28     int fa = findfather(a);
29     int fb = findfather(b);
30     if(fa != fb)
31         father[fa] = fb;
32 }
33 int main() {
34     int n,m;
35     cin>>n>>m;
36     for(int i = 0; i < m; ++i) { //保存输入
37         int k,t;
38         cin>>k;
39         for(int j = 0; j < k; ++j) {
40             cin>>t;
41             mp[i].push_back(t);
42         }
43     }
44     init(n);
45     for(auto it = mp.begin(); it != mp.end(); ++it) { //合并每个俱乐部的成员所在的集合
46         if(it->second.size() > 1) {
47             for(int i = 1; i < it->second.size(); ++i)
48                 Union(it->second[0],it->second[i]);
49         }
50     }
51     int MAX = -1;
52     for(int i = 1 ; i <= n; ++i) {
53         int f = findfather(i);
54         isRoot[f]++;
55         MAX = max(MAX,isRoot[f]);
56     }
57     printf("%d",MAX);
58     return 0;
59 }

 

猜你喜欢

转载自www.cnblogs.com/keep23456/p/12416705.html