如有不对,不吝赐教
进入正题:
某学校有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
这道题用并查集来做就很简单了,但是大家可以去想一想当M更大的时候,不能一次开出数组的时候该怎么来做,我的想法就是想归并排序一样,分隔成几个部分,每个部分进行并查集操作,然后在来总的。
下面给出这道题的代码:
#include<stdio.h>
#include<stdlib.h>
int max=1;
short FindRoot(short cur,short people[]);
short GetNum(short *t);
int main(void)
{
short M,N;
short i;
scanf("%hd %hd",&M,&N);
short people[M+1];
int number[M+1];
for(i=0;i<M+1;i++){
people[i]=i; //初始化并查集
number[i]=1; //初始化各个朋友圈的数量
}
for(i=0;i<N;i++){
short t,count,time;
short mainRoot;
scanf("%hd",&count); //读取该行数据
for(time=0;time<count;time++){
scanf("%hd",&t);
if(!time) //第一个元素
mainRoot=FindRoot(t,people); //找到主根
else{ //不是第一个元素
t=FindRoot(t,people); //找到该元素所在朋友圈的根
if(t!=mainRoot){ //该元素和主元素的根不是一个朋友圈 就进行合并
people[t]=mainRoot; //合并朋友圈
number[mainRoot]+=number[t]; //改变朋友圈的大小
number[t]=0; //规定节点没有大小
max=(max>number[mainRoot])?max:number[mainRoot]; //更新最大值
}
}
}
}
printf("%d",max);
return 0;
}
short FindRoot(short cur,short people[])
{
short root;
if(cur==people[cur])
root=cur;
else{
short t=cur;
cur=people[cur]; //向上一级寻找
root=FindRoot(cur,people); //递归寻找
people[t]=root; //压缩并查集的树状结构
}
return root;
}
测试结果: