Fork me on GitHub

HDU ACM 1856 More is better(并查集)

【题目链接】http://acm.hdu.edu.cn/showproblem.php?pid=1856

【解题思路】给的数据有点大,干脆少开点数组,直接上set存储有朋友的孩子的编号,同时根据编号初始化对应的在father数组中的下标,同时也更新集合,后面开一个数组存储同属于于一个集合的数有多少个(在以根为数组的下标中存储),然后遍历一次找到最大的数

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <set>
 4 #include <algorithm>
 5 #define SIZE 10000001
 6 #define MAXN  100002
 7 using namespace std;
 8 int father[SIZE];
 9 int num[SIZE];
10 
11 set<int>exist;
12 
13 
14 int find(int f)
15 {
16     return father[f] = f == father[f] ? f : find(father[f]);
17 }
18 
19 
20 int main()
21 {
22     #ifndef ONLINE_JUDGE
23     freopen("input.txt", "r", stdin);
24     #endif
25     int n;
26     while(scanf("%d", &n) != EOF)
27     {
28         if(!n)
29         {
30             printf("1\n");
31             continue;
32         }
33         exist.clear();
34         memset(num, 0, sizeof(num));
35         for(int i=0; i<n; ++i)
36         {
37             int u, v;
38             scanf("%d%d", &u, &v);
39             if(exist.find(u) == exist.end())
40             {
41                 father[u] = u;
42                  exist.insert(u);
43                  num[u] = 0;
44             }
45             if(exist.find(v) == exist.end())
46             {
47                  exist.insert(v);
48                 father[v] = v;
49                 num[v] = 0;
50             }
51             u = find(u);
52             v = find(v);
53             father[u] = v;
54         }
55         for(set<int>::const_iterator iter = exist.begin(); iter != exist.end(); ++iter)
56         {
57             num[find(*iter)]++;
58         }
59         int curmax = 0;
60         for(set<int>::const_iterator iter = exist.begin(); iter != exist.end(); ++iter)
61         {
62             if(curmax < num[*iter]) curmax = num[*iter];
63         }
64         printf("%d\n", curmax);
65     }
66     return 0;
67 }

 

posted @ 2013-07-29 13:54  Gifur  阅读(264)  评论(0编辑  收藏  举报
TOP