00001 #ifndef __DISJOINTSETS_H__
00002 #define __DISJOINTSETS_H__
00003
00004 #pragma once
00005
00006 #include <iostream>
00007 #include <fstream>
00008 #include <vector>
00009
00010 class DisjointSets {
00011
00012 private:
00013 unsigned int n;
00014
00015 std::vector<int> set;
00016 std::vector<int> rank;
00017
00018 inline int get_ID(int n) {
00019 int query = n;
00020 while (set[n] != n) {
00021 n = set[n];
00022 }
00023 set[query] = n;
00024 return n;
00025 }
00026
00027 inline void merge_sets(int ID_set_a, int ID_set_b) {
00028 if (rank[ID_set_a] < rank[ID_set_b]) {
00029 set[ID_set_a] = ID_set_b;
00030 } else if (rank[ID_set_a] > rank[ID_set_b]) {
00031 set[ID_set_b] = ID_set_a;
00032 } else {
00033 set[ID_set_a] = ID_set_b;
00034 rank[ID_set_b]++;
00035 }
00036 }
00037
00038 public:
00043 inline DisjointSets(unsigned int n) :
00044 n(n)
00045 {
00046 for (unsigned int i = 0; i < n; i++) {
00047 set.push_back(i);
00048 rank.push_back(0);
00049 }
00050 }
00051
00056 inline unsigned int get_n() const {
00057 return n;
00058 }
00059
00065 inline void merge_sets_of(int ID_node_a, int ID_node_b) {
00066 int ID_set_a = get_ID(ID_node_a);
00067 int ID_set_b = get_ID(ID_node_b);
00068 if (ID_set_a != ID_set_b) {
00069 merge_sets(ID_set_a, ID_set_b);
00070 }
00071 }
00072
00078 inline bool same_set(int ID_node_a, int ID_node_b) {
00079 return get_ID(ID_node_a) == get_ID(ID_node_b);
00080 }
00081
00082 friend class Maze;
00083 };
00084
00085 #endif
00086