题面链接:238. 银河英雄传说 - AcWing题库
题面:
思路:并查集, 如果没有求两艘战舰之间的战舰数量,这就是一题很简单的并查集
但是这题需要计算两艘战舰之间的数量,我们就需要维护一个d数组,保存的是当前战舰到战舰头的距离,前面战舰队不需要修改,后面的战舰队就会在原来的基础加上前面战舰队的数量,查询的时候我们只需要判断两艘战舰是否在同一队列,已经d的差值-1,但是如果是同一艘战舰,答案为0
#include
using namespace std;
#define endl "\n"
#define N 30005
int s[N];
int d[N];
int num[N];
int findx(int x){
if(s[x] == x){
return x;
}
int root = findx(s[x]);
d[x] += d[s[x]];
return s[x] = root;
}
int main(){
ios::sync_with_stdio(false);
for(int i = 1; i <= 30005; i++){
s[i] = i;
d[i] = 0;
num[i] = 1;
}
int n;
cin >> n;
while(n--){
char c;
int x, y;
cin >> c >> x >> y;
if(c == 'M'){
int fx = findx(x);
int fy = findx(y);
if(fx != fy){
s[fx] = fy;
d[fx] += num[fy];
num[fy] += num[fx];
}
}else{
if(findx(x) != findx(y)){
cout << -1 << endl;
}else{
cout << max(abs(d[x] - d[y]) - 1, 0) << endl;
}
}
}
return 0;
}