数据结构与算法题目集(中文)---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 using namespace std; 4 5 const int maxn = 300100; 6 int father[maxn]; 7 int isRoot[maxn] = {0}; 8 void init(int n) { 9 for(int i = 1; i <= n; ++i) 10 father[i] = i; 11 } 12 13 int findfather(int a) { 14 int b = a; 15 while(a != father[a]) 16 a = father[a]; 17 while(b != father[b]) { 18 int t = b; 19 b = father[b]; 20 father[t] = a; 21 } 22 return a; 23 } 24 25 void Union(int a,int b) { 26 int fa = findfather(a); 27 int fb = findfather(b); 28 if(fa != fb) 29 father[fa] = fb; 30 } 31 int main() { 32 int n,m; 33 cin>>n>>m; 34 init(n); // 初始化所有集合 35 for(int i = 0; i < m; ++i) { 36 int k,t,tt; 37 cin>>k; 38 for(int j = 0; j < k; ++j) { 39 cin>>t; 40 if(j == 0) tt = t; 41 Union(t,tt); 42 } 43 } 44 int MAX = -1; 45 for(int i = 1 ; i <= n; ++i) { 46 int f = findfather(i); 47 isRoot[f]++; 48 MAX = max(MAX,isRoot[f]); 49 } 50 printf("%d",MAX); 51 return 0; 52 }


浙公网安备 33010602011771号