天天看點

How Many Tables(并查集)

How Many Tables(并查集)

問題描述:

Today is Ignatius’ birthday. He invites a lot of friends. Now it’s dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

(今天是伊格那丢的生日。他邀請了很多朋友。現在該吃晚飯了。伊格那丢想知道他至少需要多少張桌子。你必須注意到,并不是所有的朋友都認識對方,所有的朋友都不想和陌生人待在一起。

這個問題的一個重要規則是如果我告訴你A知道B, B知道C,這意味着A, B, C互相知道,是以它們可以在一個表中。

例如:如果我告訴你A知道B, B知道C, D知道E,那麼A, B, C可以留在一個表中,D, E必須留在另一個表中。Ignatius至少需要兩個表。)

輸入描述:

The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.

(輸入以一個整數T(1<=T<=25)開始,它表示測試用例的數量。然後是T測試用例。每個測試用例以兩個整數N和M開始(1<=N,M<=1000)。N表示好友的數量,好友标記從1到N,然後是M行。每一行由兩個整數A和B(A!=B)組成,這意味着朋友A和朋友B彼此認識。兩種情況之間有一條空白線。)

輸出描述:

For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

(對于每個測試用例,隻需輸出Ignatius至少需要多少個表。不要列印任何空白。)

樣例輸入:

2

5 3

1 2

2 3

4 5

5 1

2 5

樣例輸出:

2

4

AC代碼:

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <iostream>
int pre[1010];
int getf(int a)
{
    if(a==pre[a])
        return a;
    pre[a] = getf(pre[a]);
    return pre[a];
}
void mer(int a, int b)
{
    int fa = getf(a);
    int fb = getf(b);
    if(fa != fb)
        pre[fa] = fb;
}
int main()
{
    int t,n,m,x,y;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n, &m);
        for(int i = 1; i <= n; ++i)
            pre[i] = i;
        while(m--)
        {
            scanf("%d %d",&x, &y);
            mer(x,y);
        }
        int ans = 0;
        for(int i = 1; i <= n; ++i)
            if(pre[i] == i)
                ++ans;
        printf("%d\n",ans);
    }
    return 0;
}