标签:
#include<stdio.h>
#include<string.h>
int ff[100005];//ff[x]表示x的父节点
int ss[100005];//
int x[100005],y[100005];
void ii(int n) //初始化
{
for(int i=1;i<=n;i++)
{
ff[i]=i;
ss[i]=1; //
}
}
int dd(int x) //带路径压缩的查找
{
if(x!=ff[x])
ff[x]=dd(ff[x]);
return ff[x];
}
void cc(int a,int b) //合并
{
ff[a] = b;
ss[b] += ss[a];
}
int main()
{
int i,m,a,b,t,k,j,N;
int count,max=0;
while(~scanf("%d",&N))
{
for(i=1;i<=N;i++)
{
scanf("%d%d",&x[i],&y[i]);
if(x[i]>max) max = x[i];
if(y[i]>max) max = y[i];
}
ii(max);
for(i=1;i<=N;i++)
{
int ta=dd(x[i]);
int tb=dd(y[i]);
if(ta!=tb)
cc(ta,tb);
}
int ans=0;
for (i=1;i<=max;i++)
{
if(ss[i] > ans)
ans = ss[i];
}
printf("%d\n",ans);
}
return 0;
}
并查集的运用
4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
4 2HintA and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect). In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
标签:
原文地址:http://blog.csdn.net/xinwen1995/article/details/45918929