某学校有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
#include<stdio.h>
#include<stdlib.h>int setunion(int s[],int root1,int root2)
{
if(s[root1]<=s[root2])
{
s[root1]=s[root1]+s[root2];//这个值既代表根节点,它的相反数代表该朋友圈的人数
s[root2]=root1;
return root1;
}
else
{
s[root2]=s[root1]+s[root2];
s[root1]=root2;
return root2;
}
}
int Find(int s[],int x)//值为负数的是根节点
{
for(;s[x]>=0;x=s[x]);
return x;
}
void Input(int s[])
{
int x,y,i;//x为俱乐部人数,y为编号
int root1,root2;
scanf("%d %d",&x,&y);
root1=Find(s,y);
for(i=1;i<x;i++)
{
scanf("%d",&y);
root2=Find(s,y);
if(root1!=root2)
root1=setunion(s,root1,root2);//合并不同的朋友圈,并将最大的根节点赋给root1
}
}
void Output(int s[],int N)
{
int i,max=0;
for(i=1;i<=N;i++)
{
if(s[i]<0&&(-s[i]>max))
max=-s[i];
}
printf("%d\n",max);
}
int main()
{
int *s,i,N,M;
scanf("%d %d",&N,&M);
s=malloc(sizeof(int)*(N+1));
for(i=1;i<=N;i++)//下标从1开始,因为学生编号为1~N
s[i]=-1;
for(i=0;i<M;i++)
Input(s);
Output(s,N);
//free(s);
return 0;
}