#ifndef _UNIONFIND_H #define _UNIONFIND_H #include #include #include "Array.h" // union/find data structure // use like this: // // #include "UnionFind.h" // // UnionFind a, b, c; // // a.merge(b); // // if (a.find() == b.find()) ... // // be careful to class UnionFind { private: static int _n_components; UnionFind* parent; int _size; UnionFind(const UnionFind &a) { std::cerr << "UnionFind copy constructor called" << std::endl; exit(-1); } public: ~UnionFind() {} UnionFind() { _size = 1; parent = this; ++_n_components;} UnionFind * find() { UnionFind * root = this; while (root->parent != root) root = root->parent; // path compression UnionFind * p = this; while (p->parent != root) { UnionFind * pp = p->parent; p->parent = root; p = pp; } return root; } void merge(UnionFind& a) { UnionFind * r = find(); UnionFind * ar = a.find(); if (r != ar) { --_n_components; if (r->_size < ar->_size) { r->parent = ar; ar->_size += r->_size; } else { ar->parent = r; r->_size += ar->_size; } } } int size() const { return _size; } static int n_components() { return _n_components; } }; int UnionFind::_n_components = 0; #endif