標籤:des style blog http color java os io
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 DescriptionMr 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.
InputThe 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)
OutputThe output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
Sample Input41 23 45 61 641 23 45 67 8
Sample Output42
HintA 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[email protected]
SourceHDU 2007 Programming Contest - Final
Recommendlcy 並查集入門題
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 }View Code