码迷,mamicode.com
首页 > 其他好文 > 详细

并查集 hdu 1856

时间:2015-04-04 10:37:38      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

More is better

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 327680/102400 K (Java/Others) Total Submission(s): 16863    Accepted Submission(s): 6205

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. 
 

 

技术分享
 1 /*
 2 *第一次写并查集;
 3 *开始是这么写的 rank代表高度,然后num代表当前的关系人数,par代表父亲节点
 4 *可惜内存超了
 5 *思索了一下,就没按挑战那本书上说的,我将rank代表了关系人数
 6 *可是wrong answer
 7 *无奈只好百度去了
 8 *发现自己ans 初始值 是 0
 9 *此时如果所有人都没关系的话 输出 0
10 *倒霉
11 */
12 #include<iostream>
13 #define N 10000000
14 using namespace std;
15  
16 struct node{
17     int par, rank;
18 }stu[N];
19 
20 void init(  ){
21     int i;
22     for( i=0; i<N; i++ ){
23         stu[i].par = i;
24         stu[i].rank = 1;
25     }
26 }
27 
28 int find( int x ){
29     if( stu[x].par==x ) return x;
30     return stu[x].par = find( stu[x].par );
31 }
32 
33 int unite( int a, int b ){
34     int x = find( a );
35     int y = find( b );
36         //应该是父节点相连,判断是否计算过。
37     if( x != y ){
38         stu[x].rank += stu[y].rank;
39         stu[y].par = x;
40         return stu[x].rank;
41     }
42     return 0;
43 }
44 
45 int main(){
46     int n, i, ans, x, y, tmp;
47     while( scanf( "%d", &n )!=EOF ){
48         init();
49         ans = 1;
50         for( i=0; i<n; i++ ){
51             scanf( "%d%d", &x, &y );
52             tmp = unite( x-1, y-1 );
53             ans = ans > tmp ? ans : tmp;
54         }
55         printf( "%d\n", ans );
56     }
57     return 0;
58 }
View Code

 

并查集 hdu 1856

标签:

原文地址:http://www.cnblogs.com/GS-FIGHT/p/4391637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!