HDOJ 1213 How Many Tables(并查集)

How Many Tables

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18405    Accepted Submission(s): 9108


Problem Description
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.
 

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

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

Sample Input
   
   
   
   
2 5 3 1 2 2 3 4 5 5 1 2 5
 

Sample Output
   
   
   
   
2 4
 

Author
Ignatius.L
 

Source
杭电ACM省赛集训队选拔赛之热身赛
 

Recommend
Eddy   |   We have carefully selected several similar problems for you:   1272  1232  1856  1325  1233
 

有用到并查集知识

注意若输入 1 2     2 3     1 3 或3 1    一个循环结果为1.

#include<stdio.h>
#include<string.h>
int num[1010];

int find(int x)
{
    if(x!=num[x])
	num[x]=find(num[x]);
    //printf("num[%d]=%d\n",x,num[x]);//可以在这里加一句试试看结果是什么,如下:
    return num[x];
}//用到了并查集
int main(){
    int t,n,m,i,a,b,sum;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        memset(num,0,sizeof(num));
        for(i=0;i<=n;i++) num[i]=i;
        for(i=0;i<m;i++){
            scanf("%d%d",&a,&b);
            a=find(a);//a一串数的边沿
			b=find(b);//b一串数的边沿
			num[a]=b;
			//printf("num[a=%d]=b=%d\n",a,b);//可以在这里加一句试试看结果是什么,如下:
        }//为了让那个自己等于自己的计数的有数等,让边沿不是边沿
        for(sum=0,i=1;i<=n;i++)
            if(num[i]==i)
                sum++;
        printf("%d\n",sum);
    }
    return 0;
}

2
5 3
1 3
num[1]=1
num[3]=3
num[a=1]=b=3
3 5
num[3]=3
num[5]=5
num[a=3]=b=5
1 4
num[5]=5
num[3]=5
num[1]=5
num[4]=4
num[a=5]=b=4
2


你可能感兴趣的:(数据结构,并查集,hdoj)