本文地址: http://blog.csdn.net/caroline_wendy
并查集(disjoint set)是一种常用的数据结构.树形结构, 包含查询(find)和合并(unite)操作.
时间复杂度O(a(n)), 比O(logn)要快.
代码:
class DisjoinSet { static const int MAX_N = 10000; int par[MAX_N]; int rank[MAX_N]; public: void init(int n) { for (int i=0; i<n; i++) { par[i] = i; rank[i] = 0; } } int find (int x) { if(par[x] == x) { return x; } else { return par[x] = find(par[x]); } } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) { par[x] = y; } else { par[y] = x; if (rank[x] == rank[y]) rank[x]++; } } bool same(int x, int y) { return find(x) == find(y); } };
编程算法 - 并查集(disjoint set) 代码(C)
原文地址:http://blog.csdn.net/caroline_wendy/article/details/38025341