并查集

实现的功能:管理元素所属集合

洛谷模板题:Luogu P3367

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

class DSU{
private:
vector<ll> parents, size;
public:
explicit DSU(ll n) : parents(n + 1), size(n + 1, 1) { iota(parents.begin(), parents.end(), 0); }
ll find(ll x) { return (parents[x] == x) ? x : (parents[x] = find(parents[x])); }
void merge(ll a, ll b)
{ // merge a and b
a = find(a);
b = find(b);
if (a == b) return;
//启发式合并,定向merge删去,merge a -> b
if (size[a] > size[b]) swap(a, b);
parents[a] = b;
size[b] += size[a];
}
};

int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);

ll n, m;
cin >> n >> m;
DSU dsu(n);
while (m--)
{
ll opt, a, b;
cin >> opt >> a >> b;
if (opt == 1) // merge
dsu.merge(a, b);
else // query
cout << (dsu.find(a) == dsu.find(b) ? "Y" : "N") << endl;
}
return 0;
}