disjoint-set.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #include "disjoint-set.h"
  16. // disjoint-set forests using union-by-rank and path compression (sort of).
  17. using namespace felzenszwalb;
  18. universe::universe(int elements) {
  19. elts = new uni_elt[elements];
  20. num = elements;
  21. for (int i = 0; i < elements; i++) {
  22. elts[i].rank = 0;
  23. elts[i].size = 1;
  24. elts[i].p = i;
  25. }
  26. }
  27. universe::~universe() {
  28. delete [] elts;
  29. }
  30. int universe::find(int x) {
  31. int y = x;
  32. while (y != elts[y].p)
  33. y = elts[y].p;
  34. elts[x].p = y;
  35. return y;
  36. }
  37. void universe::join(int x, int y) {
  38. if (elts[x].rank > elts[y].rank) {
  39. elts[y].p = x;
  40. elts[x].size += elts[y].size;
  41. } else {
  42. elts[x].p = y;
  43. elts[y].size += elts[x].size;
  44. if (elts[x].rank == elts[y].rank)
  45. elts[y].rank++;
  46. }
  47. num--;
  48. }