没写路径压缩,tle

P3367 【模板】并查集

zc_zmb @ 2023-11-12 11:05:41

路径压缩不会写,全忘了

#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
#include<math.h>
#include<cmath>
#include<time.h>
#include<ctime>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<cstdlib>
#include<vector>
#include<bitset>
#include<memory>
#include<utility>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<bits/stdc++.h>
using namespace std;
int a[10008],n,m,z,x,y;
int fd(int x){
    if(a[x]==x){
        return x;
    }
    else{
        return fd(a[x]);
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=10008;i++){
        a[i]=i;
    }
    while(m--){
        cin>>z>>x>>y;
        int tx=fd(x);
        int ty=fd(y);
        if(z==1){
            a[ty]=tx;
        }
        else{
            if(tx==ty){
                cout<<"Y"<<endl;
            }
            else{
                cout<<"N"<<endl;
            }
        }
    }
    return 0;
}

by angiing1222 @ 2023-11-12 11:10:04

将fd函数中的

return fd(a[x]);

改为

return a[x]=fd(a[x]);

by zc_zmb @ 2023-11-12 11:27:37

@angiing1222 谢


|