More is better
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 327680/102400 K (Java/Others)
Total Submission(s): 14437 Accepted Submission(s): 5305
Problem Description
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.
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.
Input
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)
Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
Sample Input
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
Sample Output
4
2
Hint
A 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.
Author
lxlcrystal@TJU
Source
Recommend
lcy
并查集入门题
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 "); 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 ",cnt); 56 } 57 return 0; 58 }