一个并查集的题, 但是由于要求出每个X下面有多少个石头, 所以我们回退的时候更新,这个一定要注意
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#define MAXN 33333
int fa[MAXN], num[MAXN], down[MAXN];
void init()
{
for( int i = 0 ; i<= 30010; i++)
{
num[i] = 1;
down[i] = 0;
fa[i] = i;
}
}
int findfa(int x)
{
if(fa[x] == x)
return x;
else
{
int tem = fa[x];
fa[x] = findfa(fa[x]);
down[x] += down[tem];
return fa[x];
}
}
void unit( int x, int y)
{
int fax = findfa(x);
int fay = findfa(y);
if(fax != fay)
{
fa[fax] = fay;
down[fax] = num[fay];
num[fay] += num[fax];
}
}
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
char command[2];
init();
for (int i = 0; i < n; ++i)
{
scanf("%s", command);
if (command[0] == 'M')
{
int a, b;
scanf("%d%d", &a, &b);
unit(a, b);
}
else if (command[0] == 'C')
{
int a;
scanf("%d", &a);
findfa(a);
printf("%d\n", down[a]);
}
}
}
return 0;
}