标签:模板 roo return bsp one 实践 assert parent i++
class UnionFind{ private: int* parent; int* rank; int count; public: UnionFind(int count){ parent = new int[count]; rank = new int[count]; this->count = count; for(int i = 0;i < count; i++){ parent[i] = i; rank[i] = 1; } } ~UnionFind(){ delete[] parent; delete[] rank; } int find(int p){ assert(p >= 0&&p < count); /* while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; }*/ // 实践更好 if(p != parent[p]) //理论更好 parent[p] = find(parent[p]); return parent[p]; } bool isConnected(int p,int q){ return find(p) == find(q); } void unionElements(int p,int q){ int pRoot = find(p); int qRoot = find(q); if(pRoot == qRoot) return; if(rank[pRoot] < rank[qRoot]){ parent[pRoot] = qRoot; }else if(rank[pRoot] > rank[qRoot]){ parent[qRoot] = pRoot; }else{ parent[pRoot] = qRoot; rank[qRoot]++ ; } } };
标签:模板 roo return bsp one 实践 assert parent i++
原文地址:http://www.cnblogs.com/zhangjiuding/p/7710721.html