标签:des style blog http color java os io
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 327680/102400 K (Java/Others)
Total Submission(s): 14437 Accepted Submission(s): 5305
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<stdlib.h> 5 #include<algorithm> 6 using namespace std; 7 const int MAXN=10000005; 8 int fa[MAXN]; 9 int num[MAXN]; 10 void init() //初始化 11 { //每个节点的父节点是自己,每个节点的初始时整个链上只有它一个点 12 for(int i=1;i<=MAXN;i++){ 13 fa[i]=i; 14 num[i]=1; 15 } 16 } 17 int fin(int x) //寻找父亲节点 18 { //这里给了一个优化就是我把我找过的点的父节点都设置成根节点 19 if(fa[x]!=x) //这样可以避免整条链很长的情况,因为链很长。每次查找起来会 20 fa[x]=fin(fa[x]); //花费大量时间,这样优化的话,直接判断他们根节点是不是一样如果一样的话, 21 return fa[x]; //那就在同一条链上面 22 } 23 void hb(int x,int y) //合并时,将一个节点设置成另外一个节点的父节点 24 { 25 int p=fin(x); 26 int q=fin(y); 27 if(p!=q) 28 { 29 fa[p]=q; 30 num[q]+=num[p]; 31 } 32 } 33 int main() 34 { 35 int n; 36 while(scanf("%d",&n)!=EOF) 37 { 38 if(n==0) //没有一对的时候最多留下一个人 39 { 40 printf("1\n"); 41 continue; 42 } 43 int maxn=0,a,b; 44 init(); 45 for(int i=1;i<=n;i++) 46 { 47 scanf("%d %d",&a,&b); 48 maxn=max(maxn,max(a,b)); 49 hb(a,b); 50 } 51 int cnt=0; 52 for(int i=1;i<=maxn;i++) //查找最大值 53 if(num[i]>cnt) 54 cnt=num[i]; 55 printf("%d\n",cnt); 56 } 57 return 0; 58 }
HDU 1856 More is better(并查集),布布扣,bubuko.com
标签:des style blog http color java os io
原文地址:http://www.cnblogs.com/clliff/p/3893576.html