为什么全错哇,求助大佬

P3367 【模板】并查集

skiy_gyx @ 2019-07-23 22:54:24

#include<bits/stdc++.h>
using namespace std;
#define long long long
const int max_n=10000+10;
int n,m,far[max_n],rank[max_n];
inline int read(){
    int s=0,f=1;
    char ch=getchar();
    while(ch=='-')f*=-1,ch=getchar();
    while(isdigit(ch))s=s*10+(ch-'0'),ch=getchar();
    return s*f;
}
int find(int x){
    if(far[x]==x)return x;
    else return find(far[x]);
}
void merge(int x,int y){
    x=find(x);
    y=find(y);
    if(x==y) return;
    if(rank[x]<rank[y]){
        far[x]=y;
    } else {
        far[y]=x;
        if(rank[x]==rank[y])rank[x]++;
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    n=read(),m=read();
    for(int i=1;i<=n;i++){
        far[i]=i;
        rank[i]=0;
    }
    while(m--){
        int z=read(),x=read(),y=read();
        if(z==1)merge(x,y);
        if(z==2){
            if(find(x)==find(y))cout<<"Y"<<"\n";
            else cout<<"N"<<"\n";
        }
    }
    return 0;
}

路径压缩后的并查集,本地测试全部正确,交上去就红了一片,why?


by Substitute0329 @ 2019-07-23 22:58:48

void merge(int x,int y){
    x=find(x);
    y=find(y);
    if(x==y) return;
    if(rank[x]<rank[y]){
        far[x]=y;
    } else {
        far[y]=x;
        if(rank[x]==rank[y])rank[x]++;
    }
}

我帮你改改


by Substitute0329 @ 2019-07-23 23:00:42

这不用这么复杂,直接合并x和y的老爹就好了, 记住,他(x)爹(find x)的爹(fa [ find x ] )是他(y)爹(find y)


by Substitute0329 @ 2019-07-23 23:03:34

void merge(int x,int y){
    int fax=find(x),fay=find(y);
    far[fax]=fay;
    return ;
}

by Substitute0329 @ 2019-07-23 23:03:46

就这样就好了


by 江南小巫 @ 2019-07-23 23:08:54

@情谊、暴走 您还说您不是dalao,%%%


by Substitute0329 @ 2019-07-23 23:11:47

@江南小巫 这都能被你看到?


by 江南小巫 @ 2019-07-23 23:12:14

@情谊、暴走 嘤嘤嘤


by Substitute0329 @ 2019-07-23 23:12:14

@江南小巫 拓个友链?


by skiy_gyx @ 2019-07-24 07:34:44

@情谊、暴走

仍然全错

#include<bits/stdc++.h>
using namespace std;
#define long long long
const int max_n=10000+10;
int n,m,far[max_n],rank[max_n];
inline int read(){
    int s=0,f=1;
    char ch=getchar();
    while(ch=='-')f*=-1,ch=getchar();
    while(isdigit(ch))s=s*10+(ch-'0'),ch=getchar();
    return s*f;
}
int find(int x){
    if(far[x]==x)return x;
    else return find(far[x]);
}
void merge(int x,int y){
    x=find(x);
    y=find(y);
    far[x]=y;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    n=read(),m=read();
    for(int i=1;i<=n;i++){
        far[i]=i;
        rank[i]=0;
    }
    while(m--){
        int z=read(),x=read(),y=read();
        if(z==1)merge(x,y);
        if(z==2){
            if(find(x)==find(y))cout<<"Y"<<"\n";
            else cout<<"N"<<"\n";
        }
    }
    return 0;
}

蜜汁WA


by skiy_gyx @ 2019-07-24 07:45:05

@情谊、暴走


| 下一页