Posted on 2010-08-10 15:03
MiYu 阅读(434)
评论(0) 编辑 收藏 引用 所属分类:
ACM ( 并查集 )
MiYu原创, 转帖请注明 : 转载自 ______________白白の屋
题目地址:
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): 1710 Accepted Submission(s): 643
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.
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
题目分析:
如果对并查集比较熟习的话, 这道题就可以直接模板AC了. 不了解的话请点击 :
并查集 学习 详解 这道题目的意思就是在 所有选出的集合中选出最大的集合, 也就是人最多的集合, 另外, 如果所有点
都是孤立点, 也就是说所有人都互不认识, 那么 答案显然是 1 了.
代码如下 :
MiYu原创, 转帖请注明 : 转载自 ______________白白の屋
#include <iostream>
using namespace std;
typedef struct {
int parent;
int cnt;
}Tset;
int maxSet = 0;
typedef struct treeUFS{
public:
treeUFS(int n = 0):N(n+1) { set = new Tset[N];
for ( int i = 0; i != N; ++ i)
set[i].parent = i,set[i].cnt = 1;
}
~treeUFS(){ delete [] set; };
int find ( int x ){ int r = x; while ( set[r].parent != r )
r = set[r].parent;
int i = x;
while ( i != r) {
int j = set[i].parent;
set[i].parent = r;
i = j;
}
return r;
}
void init () { for ( int i = 0; i != N; ++ i) set[i].parent = i,set[i].cnt = 1; }
void Merge( int x,int y ){ x = find ( x ); y = find ( y );
if ( x == y ) return;
if ( set[x].cnt > set[y].cnt ){
set[y].parent = x;
set[x].cnt += set[y].cnt;
if ( set[x].cnt > maxSet ){
maxSet = set[x].cnt ;
}
}
else{
set[x].parent = y;
set[y].cnt += set[x].cnt;
if ( set[y].cnt > maxSet ){
maxSet = set[y].cnt ;
}
}
}
int getSetCount ( int x ){ return set[ find(x) ].cnt; }
private:
Tset *set;
int N;
}treeUFS;
int main ()
{
int N,a,b;
treeUFS UFS ( 10000000 );
while ( scanf ( "%d", &N ) != EOF )
{
maxSet = 0;
for ( int i = 1; i <= N; ++ i )
{
scanf ( "%d%d", &a,&b );
UFS.Merge ( a,b );
}
printf ( maxSet == 0 ? "1\n" : "%d\n",maxSet );
UFS.init ();
}
return 0;
}