洛谷 P1196 【银河英雄传说】
这道题其实就是一个带权并查集的基础题,维护的是点权,所以我们要维护两个数组dis:表示当前点到父亲节点的距离,size:当前子树的大小。那么程序就自然出来了:
代码:
#include <bits/stdc++.h>
using namespace std;
int T;
int fa[30010] , size[30010] , dis[30010];
int find(int x){
if(x == fa[x]) return x;
int root = find(fa[x]);
dis[x] += dis[fa[x]];
return fa[x] = root;
}
void un(int x , int y){
int xx = find(x) , yy = find(y);
if(xx == yy) return;
fa[xx] = yy;
dis[xx] += size[yy];
size[yy] += size[xx];
}
int main(){
cin >> T;
for(int i = 1; i <= 30000; i++) fa[i] = i , size[i] = 1;
while(T--){
int x , y;
char st;
cin >> st >> x >> y;
if(st == 'M') un(x , y);
else{
int xx = find(x) , yy = find(y);
if(xx != yy) cout << -1 << endl;
else cout << abs(dis[x] - dis[y]) - 1 << endl;
}
}
return 0;
}