UVA10608 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


问题链接:UVA10608 Friends

问题简述:(略)

问题分析

  这个问题基本上是一个经典的并查集问题,只是还需要统计朋友圈的大小,最后求出最大朋友圈的人数。  

  总共有n个人,给出m个朋友关系进行计算。

程序说明:(略)

题记:(略)

参考链接:(略)


AC的C++语言程序如下:

/* UVA10608 Friends */

#include 

using namespace std;

const int N = 30000;
int f[N + 1], cnt[N + 1];
int n, m;

void Init()
{
    for (int i = 1; i <= n; i++) {
        f[i] = i;
        cnt[i] = 1;
    }
}

int Find(int a) {
    return a == f[a] ? a : f[a] = Find(f[a]);
}

//void Union(int a, int b)
//{
//    int pa = Find(a);
//    int pb = Find(b);
//    if (pa != pb) {
//        f[pa] = pb;
//    }
//}

int main()
{
    int t, x, y;

    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &n, &m);

        Init();

        for(int i = 1; i <= m; i++) {
            scanf("%d%d", &x, &y);
            int px = Find(x);
            int py = Find(y);
            if(px != py) {
                cnt[px] += cnt[py];
                f[py] = px;
            }
        }

        int max = 0;
        for(int i = 1; i <= n; i++)
            if(f[i] == i && max < cnt[i])
                max = cnt[i];

        printf("%d\n", max);
    }

    return 0;
}







你可能感兴趣的:(#,ICPC-备用二,#,ICPC-并查集与LCA,#,ICPC-UVA)