标签:
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.
#include<stdio.h> #include<string.h> #include<algorithm> int maxn=-1; using namespace std; int root[10000001]; int res[10000001]; int find(int i){ if(root[i]==i) return i; return root[i]=find(root[i]); } void unio(int x,int y){ int p=find(x),q=find(y); if(p<=q) root[q]=p,res[p]+=res[q],maxn=max(maxn,res[p]); // 在合并的时候顺便查找最大值,减少时间开销,否则超时!!! else root[p]=q,res[q]+=res[p],maxn=max(maxn,res[q]); return; } int main(){ int n; while(~scanf("%d",&n)){ if(n==0){ printf("1\n"); continue; } memset(res,0,sizeof(res)); int i,x,y,a,b; maxn=-1; for(i=1;i<=10000000;++i) root[i]=i,res[i]=1; for(i=1;i<=n;++i){ scanf("%d%d",&a,&b); x=find(a);y=find(b); if(x!=y){ unio(x,y); } } printf("%d\n",maxn); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq_18062811/article/details/47029123