本文主要是介绍codeup-More is better,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
输入
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
输出
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
样例输入
3
1 3
1 5
2 5
4
3 2
3 4
1 6
2 6
样例输出
4
5
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<cstdio>
#include<string.h>
int find(int x);
void pre(int x);
void Union(int a,int b);
int pn[10000010],p[10000010];
int main()
{int n,m,i,j,t;int a,b;while(scanf("%d",&n)!=EOF){if(n==0)printf("1\n");else{int cnt,max,Max;memset(p,0,sizeof(p));cnt=0,max=0,Max=0;pre(10000000);for(i=1;i<=n;i++){scanf("%d%d",&a,&b);if(a>Max)Max=a;if(b>Max)Max=b;Union(a,b);} for(i=1;i<=Max;i++){p[find(i)]++;}for(i=1;i<=Max;i++){if(p[i]>max)max=p[i];} printf("%d\n",max); } }return 0;
}
void pre(int x)
{int i;for(i=1;i<=x;i++){pn[i]=i;}
}
int find(int x)
{int r,z;r=x;while(r!=pn[r]){r=pn[r];}while(x!=pn[x]){z=x;x=pn[x];pn[z]=r;}return r;
}
void Union(int a,int b)
{int fa,fb;fa=find(a);fb=find(b);if(fa!=fb){pn[fb]=fa;}
}
这篇关于codeup-More is better的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!