为什么最后三个点会TLE?

P3367 【模板】并查集

夕见 @ 2016-11-16 10:55:14

#include<cstdio>
using namespace std;
long long pre[100010],n,m;//pre:前驱
long long find(long long x){//找前驱
    while(pre[x]!=x)x=pre[x];
    return x;
}
void join(long long x,long long y){//并
    long long a,b;
    a=find(x);
    b=find(y);
    pre[a]=b;
}
void judge(long long x,long long y){//查
    long long a,b;
    a=find(x);
    b=find(y);
    if(a==b)printf("Y\n");
    else printf("N\n");
}
int main(){
    //freopen("bingchaji.in","r",stdin);
    scanf("%lld%d",&n,&m);
    long long i,z,x,y;
    for(i=1;i<=n;i++)pre[i]=i;//初始化
    for(i=1;i<=m;i++){
        scanf("%lld%lld%lld",&z,&x,&y);
        if(z==1)join(x,y);
        if(z==2)judge(x,y);
    }
    return 0;
}

by 夕见 @ 2016-11-16 12:49:14

求帮助QAQ


by character @ 2016-11-16 15:48:28

你没有路径压缩orz,不TLE我是不相信的【手动头像】

int find(int x){
         if(pre[x]==x) return x;
         else return pre[x]=fi(pre[x]);
}
你完全是连了一条链,并查集的优点是越并越快(差不多这个意思

by 夕见 @ 2016-11-18 09:13:43

@character

谢谢!


|