openjij
Framework for the Ising model and QUBO.
Loading...
Searching...
No Matches
union_find.hpp
Go to the documentation of this file.
1// Copyright 2023 Jij Inc.
2
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6
7// http://www.apache.org/licenses/LICENSE-2.0
8
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
17#include <algorithm>
18#include <cstddef>
19#include <numeric>
20#include <vector>
21
22namespace openjij {
23namespace utility {
24struct UnionFind {
25 using Node = std::size_t;
26 using Parent = std::vector<Node>;
27 using Rank = std::vector<Node>;
28 using size_type = Parent::size_type;
29
30 explicit UnionFind(size_type n) : _parent(n), _rank(n, 0) {
31 std::iota(_parent.begin(), _parent.end(), 0);
32 }
33
34 void unite_sets(Node x, Node y) {
35 auto root_x = find_set(x);
36 auto root_y = find_set(y);
37
38 if (root_x == root_y)
39 return;
40
41 if (_rank[root_x] > _rank[root_y]) {
42 _parent[root_y] = root_x;
43 } else {
44 _parent[root_x] = root_y;
45 if (_rank[root_x] == _rank[root_y])
46 ++_rank[root_y];
47 }
48 }
49
51 auto base_node = node;
52
53 // find root node
54 auto parent_node = _parent[node];
55 while (parent_node != node) {
56 node = parent_node;
57 parent_node = _parent[node];
58 }
59 auto root_node = parent_node;
60
61 // do path compression
62 node = _parent[base_node];
63 while (root_node != node) {
64 _parent[base_node] = root_node;
65 base_node = node;
66 node = _parent[base_node];
67 }
68 return root_node;
69 }
70
71 Parent get_roots() const {
72 auto roots_list = _parent;
73 std::sort(roots_list.begin(), roots_list.end());
74 roots_list.erase(std::unique(roots_list.begin(), roots_list.end()),
75 roots_list.end());
76 return roots_list;
77 }
78
79private:
82};
83} // namespace utility
84} // namespace openjij
Definition algorithm.hpp:24
Definition union_find.hpp:24
Node find_set(Node node)
Definition union_find.hpp:50
std::vector< Node > Rank
Definition union_find.hpp:27
UnionFind(size_type n)
Definition union_find.hpp:30
Parent get_roots() const
Definition union_find.hpp:71
Parent::size_type size_type
Definition union_find.hpp:28
Rank _rank
Definition union_find.hpp:81
std::size_t Node
Definition union_find.hpp:25
Parent _parent
Definition union_find.hpp:80
std::vector< Node > Parent
Definition union_find.hpp:26
void unite_sets(Node x, Node y)
Definition union_find.hpp:34