zoukankan      html  css  js  c++  java
  • acm集训训练赛(二)D题【并查集】

    一、题目

    Description

    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 one number denoting how many people there are in the largest group of friends.

    Sample Input

    Sample Output

    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 10

    1 2

    9 10

    8 9

    3

    6

    二、题目源程序

    #include <cstdio>
    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    int parent[30005];
    int num[30005];
    int n, m;
    int find (int x) {
        return parent[x] == x ? x : find(parent[x]);
    }
    void init () {
        int i;
        for (i = 0; i < n; i ++)
            parent[i] = i;
        for (i = 0; i < n; i ++)
            num[i] = 0;
    }
    void Union(int a, int b) {
        int fa = find(a);
        int fb = find(b);
        if(fa != fb) {
            parent[fa] = fb;
        }
    }
    int main () {
        int cases;
        int a, b;
        int i;
        scanf("%d", &cases);
        while (cases --) {
            scanf("%d%d", &n, &m);
            init ();
            for (i = 0; i < m; i ++) {
                scanf("%d%d", &a, &b);
                Union(a, b);
            }
            for (i = 0; i < n; i ++) {
                int x = find(i);
                num[x] ++;
            }
            int max = 0;
            for (i = 0; i < n; i ++) {
                if(num[i] > max)
                    max = num[i];
            }
            printf("%d
    ", max);
        }
        return 0;
    }

    三、解题思路

    一个简单的运用并查集的知识的题目。

    练习基本的并查集的运用可以用这道题。

  • 相关阅读:
    底部导航栏
    判断手机是否连接网络
    瀑布流(圆角,卡片效果)
    列表卡片效果
    使用Glide改变图片的圆角
    条形码EAN-13码和EAN-8码的原理
    自定义底部弹窗
    【代码笔记】Java常识性基础补充(一)——赋值运算符、逻辑运算符、三元运算符、Scanner类、键盘输入、Random类、随机数
    【Android】9.0活动的生命周期(二)——实际代码演示
    【Android】8.0活动的生命周期(一)——理论知识、活动的启动方式
  • 原文地址:https://www.cnblogs.com/fightfor/p/3871547.html
Copyright © 2011-2022 走看看