C语言编程练习65:How Many Tables

今天是伊格内修斯的生日。他邀请了很多朋友。现在是晚餐时间。伊格内修斯想知道他至少需要多少张桌子。你必须注意,并非所有的朋友都彼此认识,所有的朋友都不想和陌生人呆在一起。这个问题的一个重要原则是,如果我告诉你A知道B,B知道C,那就意味着A,B,C彼此了解,所以他们可以呆在一张桌子里。例如:如果我告诉你A知道B,B知道C,D知道E,那么A,B,C可以留在一张桌子上,而D,E必须留在另一张桌子上。所以Ignatius至少需要2张牌桌。

Input:

输入以表示测试用例数的整数T(1 <= T <= 25)开始。然后是T测试用例。每个测试用例以两个整数N和M(1 <= N,M <= 1000)开始。N表示朋友的数量,朋友被标记从1到N.然后是M行。每行由两个整数A和B(A!= B)组成,这意味着朋友A和朋友B彼此了解。两种情况之间会有空白。

Output:

对于每个测试用例,只需输出Ignatius至少需要的表格数量。不要打印任何空白。

Sample  Input:

2
5 3
1 2
2 3
4 5

5 1

2 5

Sample  Output:

2

4

并查集

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn=1050;
int s[maxn];
int find(int x)
{
    if(s[x]==x)
    {
        return x;
    }
    return s[x]=find(s[x]);
}
void merge(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        s[fx]=fy;
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
        for(int i=1;i<=maxn;i++)
        {
            s[i]=i;
        }
        int x,y;
        for(int i=1;i<=m;i++)
        {
            cin>>x>>y;
            merge(x,y);
        }
        int ans;
        ans=0;
        for(int i=1;i<=n;i++)
        {
            if(s[i]==i)
            {
                ans++;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/FantasticDoubleFish/p/14496109.html