How Many Tables-- disjoint-set template title

Topic Link

Meaning of the questions:

n people attended the dinner; two people did not know can not be allocated the same table; understanding transitive: A BB know know C , then A and C are also recognized.

answer:

We will recognize two people merge into the same collection ; how many different sets of statistics can finally have;

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
typedef long long ll;
const int maxn=5e5+5;
int f[maxn];
int n,m;
int num[maxn];
int a[maxn];
int Find(int x)
{
    return x==f[x]?x:f[x]=Find(f[x]);
}
void join(int x,int y)
{
    int fx=Find(x);
    int fy=Find(y);
    if(fx!=fy)
    {
        f[fx]=fy;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)f[i]=i;
        while(m--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            join(x,y);
        }
        int ans=0;
        for(int i=1;i<=n;i++)if(f[i]==i)ans++;
        printf("%d\n",ans);
    }
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/j666/p/11610018.html