- 并查集升级版
1
- @ 2026-7-20 10:14:22
#include<bits/stdc++.h>
using namespace std;
#define ll long long
struct DSU {
vector<int> sz, f;
DSU(int n) {
sz.assign(n + 1, 1);
f.assign(n + 1, 0);
for (int i = 1; i <= n; i++) f[i] = i;
}
int root(int u) {
if (u == f[u]) return u;
return root(f[u]);
}
void merge(int u, int v) {
u = root(u), v = root(v);
if (u == v) return;
if (sz[u] > sz[v]) swap(u, v);
sz[v] += sz[u];
f[u] = v;
}
int size(int u) {
return sz[root(u)];
}
bool same(int u, int v) {
return root(u) == root(v);
}
};
void solve() {
int n, m;
cin >> n >> m;
DSU Dsu(n);
while (m--) {
int o, x, y;
cin >> o;
if (o == 1) {
cin >> x >> y;
// merge
Dsu.merge(x, y);
} else if (o == 2) {
cin >> x >> y;
// same?
cout << (Dsu.same(x, y) ? "Y" : "N") << '\n';
} else {
cin >> x;
// size?
cout << Dsu.size(x) << '\n';
}
}
}
signed main() {
int t = 1;
// cin >> t;
while (t--) solve();
}
/*
g++ -std=c++20 1.cpp -o 1 && 1 < in.txt > out.txt
*/
0 条评论
目前还没有评论...
信息
- ID
- 485
- 时间
- ms
- 内存
- MiB
- 难度
- 5
- 标签
- 递交数
- 112
- 已通过
- 44
- 上传者