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

More is better-多多益善

时间:2015-12-02 22:23:04      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:
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 roo
3 4
5 6
1 6
4
1 2m 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.
输入:
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)
输出:
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
样例输入:
4
1 2
3 4
5 6
7 8
样例输出:
4
2

 


思路:在图中所有的连通分量中找出包含顶点最多的个数。继续使用并查集解决!

#include <iostream>
using namespace std;


const int MAX = 1001;
int tree[MAX];
int counts[MAX];

int getRoot(int x)
{
    if (tree[x] == -1)
        return x;
    else
    {
        int tmp = getRoot(tree[x]);
        tree[x] = tmp;
        return tmp;
    }
}

int main()
{
    int n;
    int town1, town2;
    int result;
    while (cin >> n && n != 0)
    {
        for (int i = 0; i < MAX; i++)
        {
            tree[i] = -1;
            counts[i] = 1;
        }

        result = 1;
        for (int i = 1; i <= n; i++)
        {
            cin >> town1 >> town2;
            town1 = getRoot(town1);
            town2 = getRoot(town2);
            if (town1 != town2)
            {
                tree[town1] = town2;
                counts[town2] += counts[town1];
            }

        }

        for (int i = 1; i <= MAX; i++)
        {
            if (result < counts[i])
                result = counts[i];
        }
    
        cout << result << endl;
    }
    return 0;
}

 

More is better-多多益善

标签:

原文地址:http://www.cnblogs.com/tgycoder/p/5014333.html

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