【题目链接】
https://www.luogu.org/problemnew/show/P1196
【算法】
并查集
【代码】
#include<bits/stdc++.h> using namespace std; int i,n,x,y; char op[5]; int size[30010],d[30010],fa[30010]; inline int get_root(int x) { if (fa[x] == x) return x; int f = get_root(fa[x]); d[x] += d[fa[x]]; return fa[x] = f; } inline void merge(int x,int y) { int sx = get_root(x), sy = get_root(y); fa[sx] = sy; d[sx] = size[sy]; size[sy] += size[sx]; } int main() { scanf("%d",&n); for (i = 1; i <= 30000; i++) { fa[i] = i; d[i] = 0; size[i] = 1; } for (i = 1; i <= n; i++) { scanf("%s",&op); if (op[0] == 'M') { scanf("%d%d",&x,&y); merge(x,y); } else { scanf("%d%d",&x,&y); if (get_root(x) != get_root(y)) printf("-1\n"); else printf("%d\n",abs(d[x] - d[y]) - 1); } } return 0; }