为什么三个点超时???

P3367 【模板】并查集

Mr__Meng @ 2019-07-20 17:32:40

三个点超时???为什么啊

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
char ch;
int n,m,i;
int x,y,z;
int father[10005];
inline int r()
{
    int x=0,f=1;
    ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return f*x;
}
int find(int x)
{
    if(father[x]==x)return x;
    return find(father[x]);
}
int main()
{
    n=r(),m=r();
    for(i=1;i<=n;i++)
        father[i]=i;
    for(i=1;i<=m;i++)
    {
        z=r(),x=r(),y=r();
        if(z==1)
            father[find(y)]=find(x);
        else
        {
            int t1=find(x);
            int t2=find(y);
            if(t1==t2)
                printf("Y\n");
            else 
                printf("N\n");
        }
    }
    return 0;
}

by 狸狸养的敏敏 @ 2019-07-20 17:37:40

@1596093267ybd 考虑一下路径压缩?


by Nickel_Angel @ 2019-07-20 17:38:07

请写并查集的优化,路径压缩 or 按秩合并


by Mr__Meng @ 2019-07-20 17:40:26

@狸狸养的敏敏 过了我的问题谢谢


by Mr__Meng @ 2019-07-20 17:40:43

@Nickel_Angel 过了谢谢


by 1saunoya @ 2019-07-20 18:16:41

return fa[x] == x ? x : fa[x] = find(fa[x]) ;

by 1saunoya @ 2019-07-20 18:16:55

@1596093267ybd


by MiKu_Yin @ 2019-07-23 20:06:19

少了个路径压缩


|