您的位置:首页 > 其它

PTA - 朋友圈

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

输入格式:

输入的第一行包含两个正整数N(\le≤30000)和M(\le≤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


感觉自己老了,忘性大了,并查集都忘了也是没谁了。

这个题目就是先用并查集找每个人的祖先,然后找出现最多次的祖先的次数。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int Max = 30010;
int n,m;
int pre[Max],People[Max];

int find(int x){
while(x != pre[x])
x = pre[x];
return x;
}
void Union(int x,int y){
x = find(x);
y = find(y);
if(x!=y)
pre[y] = x;
}
int main(){
scanf("%d %d",&n,&m);
int a,b,num;
for(int i = 1; i <= n; i++)
pre[i] = i;
while(m--){
scanf("%d",&num);
if(num>0)
scanf("%d",&a);
for(int i = 1; i < num; i++){
scanf("%d",&b);
Union(a,b);
}
}
for(int i = 1; i <= n; i++)
People[i] = 0;
int k;
for(int i = 1; i <= n; i++){
k = find(i);
People[k]++;
}
int maxn = 0;
for(int i = 1; i <= n; i++)
maxn = max(maxn,People[i]);
printf("%d\n",maxn);
return 0;
}


 
时间限制:400ms
内存限制:64MB
代码长度限制:16kB
判题程序:系统默认
作者:DS课程组
单位:浙
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PTA