并查集C++实现
2016-07-23 14:52
429 查看
#include <iostream> using namespace std; class UF { //cnt is the number of disjoint sets. //id is an array that records distinct identity of each set,when two sets are merged ,their id will be same. //sz is an array that records the child number of each set including the set self. int *id, cnt, *sz; public: // Create an empty union find data structure with N isolated sets. UF(int N) { cnt = N; id = new int ; sz = new int ; for (int i = 0; i<N; i++) { id[i] = i; sz[i] = 1; } } ~UF() { delete[] id; delete[] sz; } // Return the id of component corresponding to object p. int find(int p) { if (p != id[p]){ id[p] = find(id[p]); } return id[p]; } // Replace sets containing x and y with their union. void merge(int x, int y) { int i = find(x); int j = find(y); if (i == j) return; // make smaller root point to larger one if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } cnt--; } // Are objects x and y in the same set? bool connected(int x, int y) { return find(x) == find(y); } // Return the number of disjoint sets. int count() { return cnt; } }; void main(){ UF test(5); test.merge(2, 3); test.merge(3, 4); cout << test.find(4); cout << test.count(); }
相关文章推荐
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- 数据结构之Treap详解
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)