题目大意:王先生想让男孩们帮助他,男孩越多越好,但是房子有限,他只想留住那些有朋友关系或者间接有朋友关系的人,如果所有的人都没有朋友关系的话,他随机选一个人去帮他,问最多能留住多少人。
并查集的基础题,但是当n等于0时好多人看题不清可能会写错,所有人都没关系就输出一个人。合并两个人的时候判断一下两个人是否已经直接或者间接有朋友关系,再合并一下这个集合中所包含元素的个数,找出最大的即可。
代码如下:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000500;
int pre[maxn],num[maxn];
void creat()
{
for(int i=0;i<maxn;i++)
{
pre[i]=i;
num[i]=1;
}
}
int findroot(int root)
{
if(root==pre[root])
return root;
pre[root]=findroot(pre[root]);
return pre[root];
}
int main()
{
int t,n,m,maxx;
while(scanf("%d",&t)!=EOF)
{
if(t==0)
{
puts("1");
continue;
}
maxx=-1;
creat();
while(t--)
{
scanf("%d %d",&n,&m);
int root1=findroot(n);
int root2=findroot(m);
if(root1!=root2)
{
if(root1<root2)
swap(root1,root2);
pre[root2]=root1;
num[root1]+=num[root2];
maxx=max(maxx,num[root1]);
}
}
printf("%d\n",maxx);
}
return 0;
}