Kyopro Library
 
読み取り中…
検索中…
一致する文字列を見つけられません
dsu.hpp
[詳解]
1#pragma once
2#include"../../kyopro_library/template.hpp"
3
4/// @brief Disjoint Set Union
5struct DSU {
6 DSU()=default;
7
8 DSU(int n) {
9 par=vector<int>(n); iota(par.begin(),par.end(),0);
10 sz=vector<int>(n,1);
11 forest_count=n;
12 }
13
14 int find(int x) {
15 if(par[x]==x) return x;
16 return par[x]=find(par[x]);
17 }
18
19 bool merge(int x, int y) {
20 x=find(x); y=find(y);
21 if(x==y) return false;
22 if(sz[x]<sz[y]) swap(x,y);
23 par[y]=x; sz[x]+=sz[y];
24 forest_count--;
25 return true;
26 }
27
28 int size(int x) { return sz[find(x)]; }
29
30 bool same(int x, int y) { return find(x)==find(y); }
31
32 int count() { return forest_count; }
33
35 int n=par.size();
36 vector<vector<int>> ret(n);
37 for(int i=0; i<n; i++) ret[find(i)].push_back(i);
38 ret.erase(remove_if(ret.begin(),ret.end(),[&](const vector<int>& v) { return v.empty(); }),ret.end());
39 return ret;
40 }
41
42private:
43 vector<int> par,sz;
44 int forest_count;
45};
Disjoint Set Union
Definition dsu.hpp:5
vector< vector< int > > groups()
Definition dsu.hpp:34
int count()
Definition dsu.hpp:32
DSU()=default
int find(int x)
Definition dsu.hpp:14
bool merge(int x, int y)
Definition dsu.hpp:19
DSU(int n)
Definition dsu.hpp:8
bool same(int x, int y)
Definition dsu.hpp:30
int size(int x)
Definition dsu.hpp:28