1 | /* |
---|
2 | Copyright (C) 2006 Pedro Felzenszwalb |
---|
3 | |
---|
4 | This program is free software; you can redistribute it and/or modify |
---|
5 | it under the terms of the GNU General Public License as published by |
---|
6 | the Free Software Foundation; either version 2 of the License, or |
---|
7 | (at your option) any later version. |
---|
8 | |
---|
9 | This program is distributed in the hope that it will be useful, |
---|
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
12 | GNU General Public License for more details. |
---|
13 | |
---|
14 | You should have received a copy of the GNU General Public License |
---|
15 | along with this program; if not, write to the Free Software |
---|
16 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
---|
17 | */ |
---|
18 | |
---|
19 | #ifndef DISJOINT_SET |
---|
20 | #define DISJOINT_SET |
---|
21 | |
---|
22 | // disjoint-set forests using union-by-rank and path compression (sort of). |
---|
23 | |
---|
24 | typedef struct { |
---|
25 | int rank; |
---|
26 | int p; |
---|
27 | int size; |
---|
28 | } uni_elt; |
---|
29 | |
---|
30 | class universe { |
---|
31 | public: |
---|
32 | universe(int elements); |
---|
33 | ~universe(); |
---|
34 | int find(int x); |
---|
35 | void join(int x, int y); |
---|
36 | int size(int x) const { return elts[x].size; } |
---|
37 | int num_sets() const { return num; } |
---|
38 | |
---|
39 | private: |
---|
40 | uni_elt *elts; |
---|
41 | int num; |
---|
42 | }; |
---|
43 | |
---|
44 | universe::universe(int elements) { |
---|
45 | elts = new uni_elt[elements]; |
---|
46 | num = elements; |
---|
47 | for (int i = 0; i < elements; i++) { |
---|
48 | elts[i].rank = 0; |
---|
49 | elts[i].size = 1; |
---|
50 | elts[i].p = i; |
---|
51 | } |
---|
52 | } |
---|
53 | |
---|
54 | universe::~universe() { |
---|
55 | delete [] elts; |
---|
56 | } |
---|
57 | |
---|
58 | int universe::find(int x) { |
---|
59 | int y = x; |
---|
60 | while (y != elts[y].p) |
---|
61 | y = elts[y].p; |
---|
62 | elts[x].p = y; |
---|
63 | return y; |
---|
64 | } |
---|
65 | |
---|
66 | void universe::join(int x, int y) { |
---|
67 | if (elts[x].rank > elts[y].rank) { |
---|
68 | elts[y].p = x; |
---|
69 | elts[x].size += elts[y].size; |
---|
70 | } else { |
---|
71 | elts[x].p = y; |
---|
72 | elts[y].size += elts[x].size; |
---|
73 | if (elts[x].rank == elts[y].rank) |
---|
74 | elts[y].rank++; |
---|
75 | } |
---|
76 | num--; |
---|
77 | } |
---|
78 | |
---|
79 | #endif |
---|