disjoint-set.h 1.8 KB

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