HDU 3635
思路:并查集,在查找,路径压缩的时候,用num[i]记录i被移动的次数,有:sum[i] += sum[father[i]]。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int father[10005], num[10005], city[10005];
void init(int n)
{
for(int i = 1;i <= n;i ++)
{
father[i] = i;
city[i] = 1;
num[i] = 0;
}
}
int find(int x)
{
if(x == father[x])
return x;
int temp = find(father[x]);
num[x] += num[father[x]];
father[x] = temp;
return father[x];
}
void Unit(int x, int y)
{
int a = find(x);
int b = find(y);
if(a != b)
{
father[a] = b;
num[a] = 1;
city[b] += city[a];
city[a] = 0;
}
}
int main(int argc, char const *argv[])
{
int T, N, Q, a, b, cnt = 0;;
char str[2];
scanf("%d", &T);
while(T--)
{
printf("Case %d:\n", ++cnt);
scanf("%d%d", &N, &Q);
init(N);
for(int i = 0;i < Q;i ++)
{
scanf("%s", str);
if(str[0] == 'T')
{
scanf("%d%d", &a, &b);
Unit(a, b);
}
else
{
scanf("%d", &a);
int temp = find(a);
printf("%d %d %d\n", temp, city[temp], num[a]);
}
}
}
return 0;
}
浙公网安备 33010602011771号