70分TLE求助

P3367 【模板】并查集

zhoujinhong @ 2023-09-22 14:22:26

#include<bits/stdc++.h>
using namespace std;
int s[10010];
int find(int t)
{
    if(t==s[t]) return t;
    else return find(s[t]);
}
void merge(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x!=y) s[x]=s[y];
}
bool check(int x,int y)
{
    x=find(x);
    y=find(y);
    if(s[x]==s[y]) return 1;
    else return 0; 
}
int main()
{
    int n,m;
    int z,x,y;
    cin>>n>>m;
    for(int i=1;i<=n;i++) s[i]=i;
    while(m--)
    {
        cin>>z>>x>>y;
        if(z==1)
        {
            merge(x,y);
        }
        else
        {
            if(check(x,y)) cout<<"Y"<<'\n';
            else cout<<"N"<<'\n';
        }
    }
    return 0;
}

by zhoujinhong @ 2023-09-22 14:35:26

以AC,不用回复


by wsdyz2010 @ 2023-10-19 20:19:05

我和你一样,也T了...能讲下为什么嘛


by huangmingyi @ 2023-11-05 15:06:16

@wsdyz2010 要把 return find(s[t]); 改成 return s[t]=find(s[t]);


by wsdyz2010 @ 2023-11-06 19:08:08

@huangmingyisunny1804 嗯嗯,当时找出原因了,就是这个


|