HDU 1856 并查集
Posted zzq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1856 并查集相关的知识,希望对你有一定的参考价值。
http://acm.hdu.edu.cn/showproblem.php?pid=1856
More is better
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 327680/102400 K (Java/Others)
Total Submission(s): 29843 Accepted Submission(s): 10605
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
题意没大看懂,直接并查集注意N==0时候输出1,判断最大的联通快的个数。一开始忘了路径压缩T了真是zz
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<vector> 6 #include<map> 7 using namespace std; 8 #define pii pair<int,int> 9 #define inf 0x3f3f3f3f 10 int f[100005],tot[100005]; 11 int getf(int v){return f[v]==v?v:f[v]=getf(f[v]);} 12 map<int,int>M; 13 int main() 14 { 15 int N,i,j,k; 16 while(scanf("%d",&N)==1){memset(tot,0,sizeof(tot)); 17 if(N==0){puts("1");continue;} 18 M.clear(); 19 int p=0,ans=0,u,v; 20 for(i=1;i<=100000;++i)f[i]=i; 21 for(i=1;i<=N;++i) 22 { 23 scanf("%d%d",&u,&v); 24 int _u=M[u]; 25 int _v=M[v]; 26 if(!_u){M[u]=++p;_u=p;} 27 if(!_v){M[v]=++p;_v=p;} 28 int fu=getf(_u); 29 int fv=getf(_v); 30 if(fu!=fv){ 31 f[fv]=fu; 32 } 33 } 34 for(i=1;i<=p;++i) tot[getf(i)]++; 35 for(i=1;i<=p;++i) ans=max(ans,tot[i]); 36 printf("%d\n",ans); 37 } 38 return 0; 39 }
以上是关于HDU 1856 并查集的主要内容,如果未能解决你的问题,请参考以下文章
HDU 1856More is better (裸并查集+记录秩)