@[lihaochen1234567890](/user/247193)
个人理解,输出 `-1` 的原因是
```cpp
int fi = find(i),fj = find(j);
if(fi != fj) cout << "-1" << endl;
else cout << abs(fr[i]-fr[j])-1 << endl;
// ^~~~~~~~~~~ ^~
```
这里 $fr_i-fr_j=0$,$0-1=-1$,所以输出 $-1$。
解决方法应该是把式子改成 $\max(0,|fr_i-fr_j|-1)$。
by _caiji_ @ 2021-08-15 15:01:24
应该是要特判一下吧
```max(0, abs(dist[y]- dist[x])- 1)```
by lqt1217 @ 2021-09-04 12:55:18
是特判,a!=b else返回0也行
by A_sh @ 2021-09-25 11:09:16
acwing上过了的代码
修了特判
望神犇指正
```cpp
#include<bits/stdc++.h>
using namespace std;
const int N=30010,M=100010;
int m,n,k,rf;
int fa[N],sum[N],num[N];
inline void init(){
for(int i=1;i<=N;i++){
fa[i]=i;
sum[i]=0;
num[i]=1;
}
}
inline int get(int a){
if(fa[a]==a)return a;
rf=get(fa[a]);//real father
sum[a]+=sum[fa[a]];//回溯 前缀和
return fa[a]=rf;
}
inline void merge(int a,int b){
a=get(a);
b=get(b);
if(a!=b){
fa[a]=b;
sum[a]+=num[b];
num[b]+=num[a];
num[a]=0;
}
}
inline int query(int a,int b){
if(get(a)==get(b)) if(a!=b)return abs(sum[a]-sum[b])-1;else return 0;
else return -1;
}
inline int qr(){
char ch;int f=1,res=0;
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
};
while(ch>='0'&&ch<='9'){
res=(res<<1)+(res<<3)+(ch^48);
ch=getchar();
}
return res*f;
}
int main(){
//freopen("in.txt","r",stdin);//w,stdout
init();
n=qr();
for(int i=1;i<=n;i++){
char c;int x,y;
c=getchar();
x=qr();
y=qr();
if(c=='M') merge(x,y);
if(c=='C') printf("%d\n",query(x,y));
}
return 0;
}
```
by A_sh @ 2021-09-25 11:14:03
洛谷这里一直报too short
scanf改过但莫名爆了
好像评测姬那贴差不多的情况
by A_sh @ 2021-09-25 11:15:52
@[pzj666](/user/422940) n是30000,不是t,t是操作次数(不知道是不是这个原因)
by y_kx_b @ 2022-02-08 09:44:24