并查集

#include<bits/stdc++.h>

using namespace std;

int pre[2000];

int find1(int x)
{
    int r=x;
    while(pre[r]!=r)
    {
        r=pre[r];
    }
    return r;
}

void join(int x,int y)
{
    int fx=find1(x);
    int fy=find1(y);
    if(fx!=fy)
        pre[fy]=fx;
}

int main()
{

    int n,m,k,a,b;
    int t;
    cin>>t;
    while(t--)
    {
        for(int i=1;i<1200;i++)
            pre[i]=i;
        cin>>n>>m;
        while(m--)
        {
            cin>>a>>b;
            if(a>b) swap(a,b);
            join(a,b);
        }
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            if(find1(i)==i)
            {
                ans++;
            }
        }
        cout<<ans<<endl;
    }

    return 0;
}
anytime you feel the pain.hey,refrain.don't carry the world upon your shoulders
原文地址:https://www.cnblogs.com/gaoss/p/5316390.html