並查集

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.
this

 

Inputspa

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.
code

 

Outputinput

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

 

Sample Inputio

2
5 3
1 2
2 3
4 5

5 1
2 5

 

Sample Outputtable

2
4

 

#include<stdio.h>
int bb[1010];
int find(int x)//查找其祖先節點即屬於那個集合
{
    if(x!=bb[x])
        return find(bb[x]);
    return x;
}
void mix(int x,int y)//將兩個有共同祖先的放同一個集合
{
     int fx=find(x),fy=find(y);
     if(fx!=fy)
           bb[fx]=fy;
}
int main()
{
    int t,i,j,k,m,n,a,b,sum;
    scanf("%d",&t);
    while(t--)
    {
        sum=0;
        scanf("%d%d",&m,&n);
        for(i=1; i<=m; i++)         //  初始化  將每一個元素獨立當作一個集合ast

                bb[i]=i;
        for(i=0; i<n; i++)
        {
            scanf("%d%d",&a,&b);
            mix(a,b);
        }
        for(i=1; i<=m; i++)
            if(bb[i]==i)
                sum++;//判斷有幾個集合
        printf("%d\n",sum);
    }
    return 0;
}
test

相關文章
相關標籤/搜索