How Many Tables

#include <iostream>
#include <string>
using namespace std;

const int MAX = 1005;

int father[MAX], rank[MAX];
int n, m;

void MakeSet()
{
    for (int i = 1; i <= n; i++)
    {
        father[i] = i;
    }
}

int FindSet(int x)
{
    if (x != father[x])
    {
        father[x] = FindSet(father[x]);
    }
    return father[x];
}

 
bool Union(int x, int y)
{
    x = FindSet(x);
    y = FindSet(y);
    if (x == y) return false;
    father[y] = x;
    return true;  
}

int main()
{
    int T, i, cnt;
    int x, y;
    cin >> T;  
    while (T--)
    {
        cin >> n >> m;
        MakeSet();  
        cnt = 0;
        for (i = 1; i <= m; i++)
        {
            cin >> x >> y;
            if (Union(x, y))
            {
                cnt++;
            }
        }
        cout << n-cnt <<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/xuwanghu/p/3024601.html