路径压缩时,加个else为什么会出现RE

P3367 【模板】并查集

yan_513543429 @ 2021-04-20 09:28:51

#include<bits/stdc++.h>
using namespace std;
int n, m;
int fa[10005];
int x, y, z;
void init(){
    for(int i=1; i<=n; i++)fa[i]=i;
}
int find_fa(int x){
    if(x!=fa[x])fa[x]=find_fa(fa[x]);
    return fa[x];//如果此处多加else 就会出现RE,WHY?WHY?WHY?
}
int main()
{
    scanf("%d%d", &n, &m);
    init();
    while(m--){
        scanf("%d%d%d", &z, &x, &y);
        int fx=find_fa(x), fy=find_fa(y);
        if(z==1){
            if(fx!=fy)fa[fx]=fy;
        }
        if(z==2){
            if(fx!=fy)printf("N\n");
            else printf("Y\n");
        }
    }
    return 0;
}
并查集递归中(如代码注释处)加上else会出现RE,

WHY?

WHY?

WHY?


by WYXkk @ 2021-04-20 09:32:29

@yan513543429 加上else的话,x!=fa[x] 函数没有返回值,就炸了


by yan_513543429 @ 2021-04-20 09:47:44

@WYXkk 谢谢!


|