One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
#include <iostream>
#include <stdio.h>
using namespace std;
int sum, n, m;
int father[1000];
void makeset(int x)
{
for(int i=1; i<=x; i++)
father[i]=i;
}
int findset(int x)//查找
{
if(x!=father[x])
father[x]=findset(father[x]);//回溯,路徑壓縮
return father[x];
}
void Union(int a, int b)//合併
{
int x=findset(a);
int y=findset(b);
if(x==y)
return;
sum=sum-1;
father[y]=x;
}
int main()
{
int t;
scanf("%d", &t);
for(int j=1; j<=t; j++)
{
scanf("%d%d", &n, &m);
sum=n;
makeset(n);
int first, second;
for(int i=1; i<=m; i++)
{
scanf("%d%d", &first, &second);
Union(first, second);
}
printf("%d\n", sum);
getchar();
}
return 0;
}