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

More is better(并查集)

时间:2015-07-30 18:30:27      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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): 18767    Accepted Submission(s): 6896


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
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.
 

 

题意:王老师要找一些男生帮助他完成一项工程。要求最后挑选出的男生之间都是朋友关系,可以说直接的,也可以是间接地。问最多可以挑选出几个男生(最少挑一个)。
         并查集,这里合并的时候注意看清将谁的父亲指向谁,要是将F[fa] = fb说明fb是fa的父亲,下面在写个数叠加的时候要将fa的个数加到fb上,一开始写反了找了半天错,哎,傻呀
给出代码
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 #define N 100010
 7 int F[N];
 8 int G[N];
 9 int Gf(int t)
10 {
11     if(F[t]==-1) return t;
12     F[t] = Gf(F[t]);
13     return F[t];
14 }
15 int mx;
16 void bing (int a , int b)
17 {
18     int fa = Gf(a);
19     int fb = Gf(b);
20     if(fa!=fb)
21     {
22         F[fa] = fb;
23         G[fb] += G[fa];
24         mx = max(mx,G[fb]);
25     }
26 }
27 int main()
28 {
29     int n;
30     while(~scanf("%d",&n))
31     {
32         mx = 0;
33         memset(F,-1,sizeof(F));
34         for(int i = 1 ;i <= N ;i++)
35         {
36             G[i] = 1;
37         }
38         for(int i = 0 ;i < n ;i++)
39         {
40             int a , b;
41             scanf("%d%d",&a,&b);
42             bing (a, b);
43         }
44         printf("%d\n",mx);
45     }
46     return 0;
47 }

 

More is better(并查集)

标签:

原文地址:http://www.cnblogs.com/shanyr/p/4689824.html

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