跳到正文

算法·理论

并查集

xiesean约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月6日
收录
2026年10月6日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

课件

截屏-0.jpeg 截屏-1.jpeg 截屏-2.jpegn 截屏-3.jpeg 截屏-4.jpeg 截屏-5.jpeg 截屏-6.jpeg 截屏-7.jpeg 截屏-8.jpeg 截屏-9.jpeg 截屏-10.jpeg 截屏-11.jpeg 截屏-12.jpeg 截屏-13.jpeg 截屏-14.jpeg

A

A题目传送门

代码

C++
#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;
}
原文