并查集 2025/11/2

#include<bits/stdc++.h>
using namespace std;
#define N 200005


int fa[N];
int sz[N];

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

int main(){
	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	int n,m;
	cin >> n >> m;
	for(int i = 1;i <= n; i++){
		fa[i] = i;
		sz[i] = 1;
	}
	for(int i = 1; i <= m; i++){
		int z,x,y;
		cin >> z >> x >> y;
		if(z == 1){
			int m = find(x);
			int n = find(y);
			if(sz[m] <= sz[n]){  //按秩合并
				fa[m] = n;
				sz[m]++;
			}
			else {
				fa[n] = m;
				sz[n]++;
			}
		}
		else {
			if(find(x) == find(y)){
				cout << "Y" << endl;
			}
			else cout << "N" << endl;
		}
	}
	return 0;
}
posted @ 2025-11-05 21:15  XYu1230  阅读(3)  评论(0)    收藏  举报