HDU-1213-How Many Tables(并查集)

来源:互联网 发布:淘宝水族箱品牌排行榜 编辑:程序博客网 时间:2024/06/03 06:08

A - How Many Tables
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status

Practice

HDU 1213
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

题意:首行给出T,代表T组数据。每组数据第一行给出N,M,代表有N个人,接下来有M行,每行两个数A和B,代表A和B相互认识,或者理解成,A和B在同一集合内,输出一共有多少个集合

思路:并查集模板

代码

#include<stdio.h>#include<iostream>#include<algorithm>#include<string>#include<string.h>using namespace std;//并查集const int maxn=1005;int num[maxn];int N;int M;void init(){    for(int i=0; i<=N; i++)        num[i]=i;}int Query(int x)//查询x的祖先{    while(x!=num[x])//祖先不是自己就进入循环        x=num[x];//路径压缩    return x;}void Merge(int x,int y)//x,y合并到同一集合{    int flag_x=Query(x);    int flag_y=Query(y);//获取两者祖先    if(flag_x!=flag_y)//如果不在同一祖先内        num[flag_x]=flag_y;//y放到x集合内}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&N,&M);        init();        int A,B;        for(int i=1; i<=M; i++)        {            scanf("%d%d",&A,&B);            Merge(A,B);        }        int count=0;        for(int i=1; i<=N; i++)            if(num[i]==i)                count++;        printf("%d\n",count);    }    return 0;}
0 0