题目:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=2189
代码:
#include <stdio.h>
int pre[1010];
int Find(int x)
{
int r = x;
while (pre[r] != r)
{
r = pre[r];
}
int i = x, j;
while (pre[i] != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void mix(int x, int y)
{
int fx = Find(x), fy = Find(y);
if (fx != fy)
{
pre[fy] = fx;
}
}
int main()
{
int t, n, m;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++)
{
pre[i] = i;
}
int x, a, b;
for (int i = 0; i < m; i++)
{
scanf("%d", &x);
if (x == 0)
{
scanf("%d", &a);
int sum = 0;
for (int i = 1; i <= n; i++)
{
if (Find(a) == Find(i))
{
sum++;
}
}
printf("%d\n", sum);
}
if (x == 1)
{
scanf("%d %d", &a, &b);
mix(a, b);
}
}
}
return 0;
}