• UVA-10608 Friends 【并查集】


    There is a town with N citizens. It is known that some pairs of people are friends. According to the
    famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends
    and B and C are friends then A and C are friends, too.
    Your task is to count how many people there are in the largest group of friends.


    Input
    Input consists of several datasets. The first line of the input consists of a line with the number of test
    cases to follow.
    The first line of each dataset contains tho numbers N and M, where N is the number of town’s
    citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known
    to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N,
    A  !=  B) which describe that A and B are friends. There could be repetitions among the given pairs.


    Output
    The output for each test case should contain (on a line by itself) one number denoting how many people
    there are in the largest group of friends on a line by itself.


    Sample Input
    2
    3 2
    1 2
    2 3
    10 12
    1 2
    3 1
    3 4
    5 4
    3 5
    4 6
    5 2
    2 1
    7 1
    1 2
    9 10
    8 9


    Sample Output
    3
    7

    注意: 数据范围M为零的情况。

    #include <bits/stdc++.h>
    using namespace std;
    
    const int maxn = 10001;
    int N, M;
    int ans;
    int p[maxn];
    int cnt[maxn];
    
    int ffind(int x)
    {
        return p[x] == x? x : p[x] = ffind(p[x]);
    }
    
    void init(int n)
    {
        ans = 1;
        for(int i = 1; i <= n ; i++)
            p[i] = i, cnt[i] = 1;
    
    }
    
    void uunion(int u, int v)
    {
        int a = ffind(u);
        int b = ffind(v);
        if(a != b)
            p[b] = a, cnt[a] += cnt[b];
        ans = max(cnt[a],ans);
    }
    
    
    int main()
    {
    #ifndef ONLINE_JUDGE
        freopen("in.ini", "r",stdin);
    #endif // ONLINE_JUDGE
        int T;
        cin >> T;
        while(T--)
        {
            cin >> N >> M;
            init(N);
            int a,b;
            for(int i = 0; i < M; i++)
            {
                cin >> a >> b;
                uunion(a,b);
            }
    
            cout << ans << endl;
        }
        return 0;
    }
  • 相关阅读:
    [CSP-S模拟测试]:迷宫(最短路)
    [CSP-S模拟测试]:五子棋(模拟)
    [CSP-S模拟测试]:点亮(状压DP+树上背包DP)
    [CSP-S模拟测试]:统计(树状数组+乱搞)
    [CSP-S模拟测试]:组合(欧拉路)
    [CSP-S模拟测试]:笨小猴(随机化)
    最小表示法
    BZOJ4868 [Shoi2017]期末考试 【三分 + 贪心】
    BZOJ4870 [Shoi2017]组合数问题 【组合数 + 矩乘】
    BZOJ4919 [Lydsy1706月赛]大根堆 【dp + 启发式合并】
  • 原文地址:https://www.cnblogs.com/YY666/p/11222182.html
Copyright © 2020-2023  润新知