并查集

· · 算法·理论

课件

n 截屏-3.jpeg

A

A题目传送门

代码

#include<bits/stdc++.h>
using namespace std;
int n,m;
int a,b,c;
int fa[200005],h[200005];
int get(int x){
    if(fa[x]==0){
        return x;
    }
    return fa[x]=get(fa[x]);
}
int main(){
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin>>n>>m;
    for (int i=1;i<=m;i++){
        cin>>a>>b>>c;
        int fx=get(b),fy=get(c);
        if(a==1){
            if(fx!=fy){
                if(h[fx]>h[fy]){
                    swap(fx,fy);
                }
                fa[fx]=fy;
                h[fy]=max(h[fx]+1,h[fy]);    
            }
        }
        else{
            if(fx==fy){
                cout<<"Y"<<endl;
            }
            else{
                cout<<"N"<<endl;
            }
        }
    }
    return 0;
}