cgv
Loading...
Searching...
No Matches
union_find.h
1#pragma once
2
3namespace cgv{
4 namespace math{
9{
10 int* sz;
11 int* id;
12 int components;
13 int N;
14
16 union_find(int N):N(N)
17 {
18 components=N;
19 id = new int[N];
20 sz = new int[N];
21 for(int i = 0; i < N;i++)
22 {
23 id[i] = i;
24 sz[i] = 1;
25 }
26
27 }
30 {
31 delete[] sz;
32 delete[] id;
33 }
34
37 {
38 return components;
39 }
40
41 //return the number of elements in the set which contains x
42 int num_in_set(int x)
43 {
44 int l= find(x);
45 return sz[l];
46 }
47
48 //retruns label of the first set this can be used in combination with next_set to iterate over all sets
49 int first_set()
50 {
51 int x =0;
52 while(x < N && x != id[x])
53 x++;
54 return x;
55 }
56 //returns the next set of x or -1 if x is the last one
57 int next_set(int x)
58 {
59
60 x++;
61 while(x <N &&x != id[x])
62 x++;
63 if(x == N)
64 x= -1;
65 return x;
66
67 }
68
70 int find(int x)
71 {
72 while(x != id[x])
73 {
74 id[x] = id[id[x]];
75 x=id[x];
76 }
77 return x;
78 }
79
80
81
83 void unite(int p, int q)
84 {
85 int i = find(p);
86 int j = find(q);
87 if (i == j) return;
88 if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
89 else { id[j] = i; sz[i] += sz[j]; }
90 components--;
91 }
92
94 bool find(int p, int q)
95 {
96 return find(p) == find(q);
97 }
98
99};
100
101 }
102}
the cgv namespace
Definition print.h:11
A union find data structure.
Definition union_find.h:9
~union_find()
destructor
Definition union_find.h:29
union_find(int N)
N number of all elements.
Definition union_find.h:16
int find(int x)
return label number of element x
Definition union_find.h:70
bool find(int p, int q)
check wether p and q are in the same set
Definition union_find.h:94
void unite(int p, int q)
unite the set containing p with the set containing q (if p and q are in the same set,...
Definition union_find.h:83
int num_of_components()
number of sets (initially number of all elements)
Definition union_find.h:36