#include <stdio.h>
#include <cstdio>
#include <string.h>
#include <cstring>
using namespace std;
const int N = 1000;
int pre[N];
int findd(int x)
{
int r = x;
while(r != pre[r])
r = pre[r];
int i = x, j;
if(i != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
int main()
{
// freopen("in.txt", "r", stdin);
int i, N, M, p1, p2, f1, f2, total, num;
scanf("%d", &num);
while(num --)
{
scanf("%d%d", &N, &M);
total = N;
for(i = 1; i <= N; i ++)
pre[i] = i;
while(M --)
{
scanf("%d%d", &p1, &p2);
f1 = findd(p1);
f2 = findd(p2);
if(f1 != f2)
{
pre[f2] = f1;
total --;
}
}
printf("%d\n", total);
}
return 0;
#include <cstdio>
#include <string.h>
#include <cstring>
using namespace std;
const int N = 1000;
int pre[N];
int findd(int x)
{
int r = x;
while(r != pre[r])
r = pre[r];
int i = x, j;
if(i != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
int main()
{
// freopen("in.txt", "r", stdin);
int i, N, M, p1, p2, f1, f2, total, num;
scanf("%d", &num);
while(num --)
{
scanf("%d%d", &N, &M);
total = N;
for(i = 1; i <= N; i ++)
pre[i] = i;
while(M --)
{
scanf("%d%d", &p1, &p2);
f1 = findd(p1);
f2 = findd(p2);
if(f1 != f2)
{
pre[f2] = f1;
total --;
}
}
printf("%d\n", total);
}
return 0;
}
心得:并查集水