HDU1213

节点的合并问题,注意输出格式,下面是AC代码: 

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=1005;
int n,m,t;
int root;//开始时桌子的数量
int pre[maxn];
int pp,qq;//当前可能合并的两个结点
void make_set()
{
    for(int i=1; i<=n; i++)
        pre[i]=i;
    root=n;//开始为每个人准备一张桌子
}
int finds(int x)
{
    if(x!=pre[x])
    {
        pre[x]=finds(pre[x]);
    }
    return pre[x];
}
void unions(int x,int y)
{
    int a=finds(x);
    int b=finds(y);//a,b代表根节点
    if(a==b)
        return;
    else
    {
        pre[a]=b;
        root--;//两个节点合并,桌子数-1
    }
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        make_set();
        for(int i=0; i<m; i++)
        {
            cin>>pp>>qq;
            unions(pp,qq);
        }
        cout<<root<<endl;
        ///if(t)cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41658955/article/details/81353839