并查集不解释……
#include <stdio.h>
#include <memory.h>
#include <math.h>
int T;
int *father;
int *children;
int find_father(int x) {
while (father[x] != -1) x = father[x];
return x;
} //找到根节点
int find_children(int x) {
while (children[x] != -1) x = children[x];
return x;
} //找到子节点
int hb(int x, int y) //y放到x的尾端
{
int cx = find_children(x), fy = find_father(y);
father[fy] = cx;
children[cx] = fy;
}
int ask(int x, int y) {
int fx = find_father(x);
int fy = find_father(y);
if (fx != fy)
return -1;
else {
int k1 = 0;
int k2 = 0;
while (father[x] != -1) {
x = father[x];
k1++;
}
while (father[y] != -1) {
y = father[y];
k2++;
}
return int(fabs(k1 - k2)) - 1;
}
}
int main() {
freopen("Problem6.in", "r", stdin);
freopen("Problem6.out", "w", stdout);
scanf("%d/n", &T);
char c;
int x, y;
father = new int[T + 1];
children = new int[T + 1];
memset(father + 1, -1, sizeof(int) * T);
memset(children + 1, -1, sizeof(int) * T);
int p = 0;
for (int i = 1; i <= T; i++) {
scanf("%c %d %d/n", &c, &x, &y);
if (c == 'M') {
hb(x, y);
p++;
}
if (c == 'C') {
printf("%d/n", ask(x, y));
p++;
}
}
return 0;
}