disjoint-set.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. namespace felzenszwalb{
  19. typedef struct {
  20. int rank;
  21. int p;
  22. int size;
  23. } uni_elt;
  24. class universe {
  25. public:
  26. universe(int elements);
  27. ~universe();
  28. int find(int x);
  29. void join(int x, int y);
  30. int size(int x) const { return elts[x].size; }
  31. int num_sets() const { return num; }
  32. private:
  33. uni_elt *elts;
  34. int num;
  35. };
  36. universe::universe(int elements) {
  37. elts = new uni_elt[elements];
  38. num = elements;
  39. for (int i = 0; i < elements; i++) {
  40. elts[i].rank = 0;
  41. elts[i].size = 1;
  42. elts[i].p = i;
  43. }
  44. }
  45. universe::~universe() {
  46. delete [] elts;
  47. }
  48. int universe::find(int x) {
  49. int y = x;
  50. while (y != elts[y].p)
  51. y = elts[y].p;
  52. elts[x].p = y;
  53. return y;
  54. }
  55. void universe::join(int x, int y) {
  56. if (elts[x].rank > elts[y].rank) {
  57. elts[y].p = x;
  58. elts[x].size += elts[y].size;
  59. } else {
  60. elts[x].p = y;
  61. elts[y].size += elts[x].size;
  62. if (elts[x].rank == elts[y].rank)
  63. elts[y].rank++;
  64. }
  65. num--;
  66. }
  67. }//namespace
  68. #endif