3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2006
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_UNION_FIND_H
20 #define LEMON_UNION_FIND_H
24 //!\brief Union-Find data structures.
32 #include <lemon/bits/invalid.h>
36 //! \addtogroup auxdat
39 /// \brief A \e Union-Find data structure implementation
41 /// The class implements the \e Union-Find data structure.
42 /// The union operation uses rank heuristic, while
43 /// the find operation uses path compression.
44 /// This is a very simple but efficient implementation, providing
45 /// only four methods: join (union), find, insert and size.
46 /// For more features see the \ref UnionFindEnum class.
48 /// It is primarily used in Kruskal algorithm for finding minimal
49 /// cost spanning tree in a graph.
52 /// \pre You need to add all the elements by the \ref insert()
54 template <typename Item, typename ItemIntMap>
58 typedef Item ElementType;
61 // If the items vector stores negative value for an item then
62 // that item is root item and it has -items[it] component size.
63 // Else the items[it] contains the index of the parent.
64 std::vector<int> items;
67 bool rep(int idx) const {
68 return items[idx] < 0;
71 int repIndex(int idx) const {
77 int next = items[idx];
78 const_cast<int&>(items[idx]) = k;
86 /// \brief Constructor
88 /// Constructor of the UnionFind class. You should give an item to
89 /// integer map which will be used from the data structure. If you
90 /// modify directly this map that may cause segmentation fault,
91 /// invalid data structure, or infinite loop when you use again
93 UnionFind(ItemIntMap& m) : index(m) {}
95 /// \brief Returns the index of the element's component.
97 /// The method returns the index of the element's component.
98 /// This is an integer between zero and the number of inserted elements.
100 int find(const Item& a) {
101 return repIndex(index[a]);
104 /// \brief Inserts a new element into the structure.
106 /// This method inserts a new element into the data structure.
108 /// The method returns the index of the new component.
109 int insert(const Item& a) {
110 int n = items.size();
116 /// \brief Joining the components of element \e a and element \e b.
118 /// This is the \e union operation of the Union-Find structure.
119 /// Joins the component of element \e a and component of
120 /// element \e b. If \e a and \e b are in the same component then
121 /// it returns false otherwise it returns true.
122 bool join(const Item& a, const Item& b) {
123 int ka = repIndex(index[a]);
124 int kb = repIndex(index[b]);
129 if (items[ka] < items[kb]) {
130 items[ka] += items[kb];
133 items[kb] += items[ka];
139 /// \brief Returns the size of the component of element \e a.
141 /// Returns the size of the component of element \e a.
142 int size(const Item& a) {
143 int k = repIndex(index[a]);
150 /// \brief A \e Union-Find data structure implementation which
151 /// is able to enumerate the components.
153 /// The class implements a \e Union-Find data structure
154 /// which is able to enumerate the components and the items in
155 /// a component. If you don't need this feature then perhaps it's
156 /// better to use the \ref UnionFind class which is more efficient.
158 /// The union operation uses rank heuristic, while
159 /// the find operation uses path compression.
161 /// \pre You need to add all the elements by the \ref insert()
164 template <typename _Item, typename _ItemIntMap>
165 class UnionFindEnum {
169 typedef _ItemIntMap ItemIntMap;
173 // If the parent stores negative value for an item then that item
174 // is root item and it has -items[it].parent component size. Else
175 // the items[it].parent contains the index of the parent.
177 // The \c nextItem and \c prevItem provides the double-linked
178 // cyclic list of one component's items. The \c prevClass and
179 // \c nextClass gives the double linked list of the representant
185 int nextItem, prevItem;
186 int nextClass, prevClass;
189 std::vector<ItemT> items;
195 bool rep(int idx) const {
196 return items[idx].parent < 0;
199 int repIndex(int idx) const {
205 int next = items[idx].parent;
206 const_cast<int&>(items[idx].parent) = k;
212 void unlaceClass(int k) {
213 if (items[k].prevClass != -1) {
214 items[items[k].prevClass].nextClass = items[k].nextClass;
216 firstClass = items[k].nextClass;
218 if (items[k].nextClass != -1) {
219 items[items[k].nextClass].prevClass = items[k].prevClass;
223 void spliceItems(int ak, int bk) {
224 items[items[ak].prevItem].nextItem = bk;
225 items[items[bk].prevItem].nextItem = ak;
226 int tmp = items[ak].prevItem;
227 items[ak].prevItem = items[bk].prevItem;
228 items[bk].prevItem = tmp;
234 UnionFindEnum(ItemIntMap& _index)
235 : items(), index(_index), firstClass(-1) {}
237 /// \brief Inserts the given element into a new component.
239 /// This method creates a new component consisting only of the
242 void insert(const Item& item) {
245 int idx = items.size();
246 index.set(item, idx);
253 t.nextClass = firstClass;
254 if (firstClass != -1) {
255 items[firstClass].prevClass = idx;
263 /// \brief Inserts the given element into the component of the others.
265 /// This methods inserts the element \e a into the component of the
267 void insert(const Item& item, const Item& comp) {
268 int k = repIndex(index[comp]);
271 int idx = items.size();
272 index.set(item, idx);
275 t.nextItem = items[k].nextItem;
276 items[items[k].nextItem].prevItem = idx;
277 items[k].nextItem = idx;
287 /// \brief Finds the leader of the component of the given element.
289 /// The method returns the leader of the component of the given element.
290 const Item& find(const Item &item) const {
291 return items[repIndex(index[item])].item;
294 /// \brief Joining the component of element \e a and element \e b.
296 /// This is the \e union operation of the Union-Find structure.
297 /// Joins the component of element \e a and component of
298 /// element \e b. If \e a and \e b are in the same component then
299 /// returns false else returns true.
300 bool join(const Item& a, const Item& b) {
302 int ak = repIndex(index[a]);
303 int bk = repIndex(index[b]);
309 if ( items[ak].parent < items[bk].parent ) {
311 items[ak].parent += items[bk].parent;
312 items[bk].parent = ak;
315 items[bk].parent += items[ak].parent;
316 items[ak].parent = bk;
323 /// \brief Returns the size of the component of element \e a.
325 /// Returns the size of the component of element \e a.
326 int size(const Item &item) const {
327 return - items[repIndex(index[item])].parent;
330 /// \brief Splits up the component of the element.
332 /// Splitting the component of the element into sigleton
333 /// components (component of size one).
334 void split(const Item &item) {
335 int k = repIndex(index[item]);
336 int idx = items[k].nextItem;
338 int next = items[idx].nextItem;
340 items[idx].parent = -1;
341 items[idx].prevItem = idx;
342 items[idx].nextItem = idx;
344 items[idx].nextClass = firstClass;
345 items[firstClass].prevClass = idx;
351 items[idx].parent = -1;
352 items[idx].prevItem = idx;
353 items[idx].nextItem = idx;
355 items[firstClass].prevClass = -1;
358 /// \brief Sets the given element to the leader element of its component.
360 /// Sets the given element to the leader element of its component.
361 void makeRep(const Item &item) {
362 int nk = index[item];
363 int k = repIndex(nk);
366 if (items[k].prevClass != -1) {
367 items[items[k].prevClass].nextClass = nk;
371 if (items[k].nextClass != -1) {
372 items[items[k].nextClass].prevClass = nk;
375 int idx = items[k].nextItem;
377 items[idx].parent = nk;
378 idx = items[idx].nextItem;
381 items[nk].parent = items[k].parent;
382 items[k].parent = nk;
385 /// \brief Removes the given element from the structure.
387 /// Removes the element from its component and if the component becomes
388 /// empty then removes that component from the component list.
390 /// \warning It is an error to remove an element which is not in
392 void erase(const Item &item) {
393 int idx = index[item];
396 if (items[k].parent == -1) {
400 int nk = items[k].nextItem;
401 if (items[k].prevClass != -1) {
402 items[items[k].prevClass].nextClass = nk;
406 if (items[k].nextClass != -1) {
407 items[items[k].nextClass].prevClass = nk;
410 int idx = items[k].nextItem;
412 items[idx].parent = nk;
413 idx = items[idx].nextItem;
416 items[nk].parent = items[k].parent + 1;
420 int k = repIndex(idx);
421 idx = items[k].nextItem;
423 items[idx].parent = k;
424 idx = items[idx].nextItem;
431 items[items[idx].prevItem].nextItem = items[idx].nextItem;
432 items[items[idx].nextItem].prevItem = items[idx].prevItem;
436 /// \brief Moves the given element to another component.
438 /// This method moves the element \e a from its component
439 /// to the component of \e comp.
440 /// If \e a and \e comp are in the same component then
441 /// it returns false otherwise it returns true.
442 bool move(const Item &item, const Item &comp) {
443 if (repIndex(index[item]) == repIndex(index[comp])) return false;
450 /// \brief Removes the component of the given element from the structure.
452 /// Removes the component of the given element from the structure.
454 /// \warning It is an error to give an element which is not in the
456 void eraseClass(const Item &item) {
457 unlaceClass(repIndex(index[item]));
460 /// \brief Lemon style iterator for the representant items.
462 /// ClassIt is a lemon style iterator for the components. It iterates
463 /// on the representant items of the classes.
466 /// \brief Constructor of the iterator
468 /// Constructor of the iterator
469 ClassIt(const UnionFindEnum& ufe) : unionFind(&ufe) {
470 idx = unionFind->firstClass;
473 /// \brief Constructor to get invalid iterator
475 /// Constructor to get invalid iterator
476 ClassIt(Invalid) : unionFind(0), idx(-1) {}
478 /// \brief Increment operator
480 /// It steps to the next representant item.
481 ClassIt& operator++() {
482 idx = unionFind->items[idx].nextClass;
486 /// \brief Conversion operator
488 /// It converts the iterator to the current representant item.
489 operator const Item&() const {
490 return unionFind->items[idx].item;
493 /// \brief Equality operator
495 /// Equality operator
496 bool operator==(const ClassIt& i) {
500 /// \brief Inequality operator
502 /// Inequality operator
503 bool operator!=(const ClassIt& i) {
508 const UnionFindEnum* unionFind;
512 /// \brief Lemon style iterator for the items of a component.
514 /// ClassIt is a lemon style iterator for the components. It iterates
515 /// on the items of a class. By example if you want to iterate on
516 /// each items of each classes then you may write the next code.
518 /// for (ClassIt cit(ufe); cit != INVALID; ++cit) {
519 /// std::cout << "Class: ";
520 /// for (ItemIt iit(ufe, cit); iit != INVALID; ++iit) {
521 /// std::cout << toString(iit) << ' ' << std::endl;
523 /// std::cout << std::endl;
528 /// \brief Constructor of the iterator
530 /// Constructor of the iterator. The iterator iterates
531 /// on the class of the \c item.
532 ItemIt(const UnionFindEnum& ufe, const Item& item) : unionFind(&ufe) {
533 idx = unionFind->repIndex(unionFind->index[item]);
536 /// \brief Constructor to get invalid iterator
538 /// Constructor to get invalid iterator
539 ItemIt(Invalid) : unionFind(0), idx(-1) {}
541 /// \brief Increment operator
543 /// It steps to the next item in the class.
544 ItemIt& operator++() {
545 idx = unionFind->items[idx].nextItem;
546 if (unionFind->rep(idx)) idx = -1;
550 /// \brief Conversion operator
552 /// It converts the iterator to the current item.
553 operator const Item&() const {
554 return unionFind->items[idx].item;
557 /// \brief Equality operator
559 /// Equality operator
560 bool operator==(const ItemIt& i) {
564 /// \brief Inequality operator
566 /// Inequality operator
567 bool operator!=(const ItemIt& i) {
572 const UnionFindEnum* unionFind;
583 #endif //LEMON_UNION_FIND_H