图论-最小生成树-Kruskal
2016-05-11 17:18
274 查看
利用并查集来实现判断,方便快捷。
#include <iostream> #include <algorithm> using namespace std; // 使用并查集来判断是否构成回路 const int MAX_N = 100; const int MAX_E = 100; int par[MAX_N]; //父亲 int ranks[MAX_N]; // 树的高度 //初始化n个元素 void init(int n) { for (int i = 0; i < n; i++) { par[i] = i; ranks[i] = 0; } } //查询树的根 int find(int x) { if (par[x] == x) { return x; } else return (par[x] = find(par[x])); //优化 } //合并x和y所属的集合 void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (ranks[x] < ranks[y]) { par[x] = y; } else { par[y] = x; if (ranks[x] == ranks[y]) ranks[x]++; } } //判断x和y是否属于同一个集合 bool same(int x, int y) { return find(x) == find(y); } // struct edge{int u, v, cost;}; bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; } edge es[MAX_E]; int V,E; int kruskal() { sort(es, es+E, comp); init(V); int res = 0; for (int i = 0; i < E; i++) { edge e = es[i]; if (!same(e.u, e.v)) { unite(e.u, e.v); res += e.cost; } } return res; } int main() { return 0; }
相关文章推荐
- 嵌入式文件系统链接
- android launcher folder功能详解
- Recaman's Sequence
- hdu1536S-Nim
- Java读取txt文件编码格式
- 简单的查看函数时间运行类
- Android Audio回声消除学习笔记
- 自定义的PagerSlidingTabStrip
- ArcGIS格网化shp数据
- Python logging模块详解
- java常用的编辑器之kindeditor
- 【C语言】动态内存分配alloca
- 算法提高 身份证号码升级 JAVA
- Android 应用开发 之通过AsyncTask与ThreadPool【转】
- SQL Server 存储过程
- 【BZOJ3671】[Noi2014]随机数生成器【模拟】【贪心】【卡空间】
- 有参考或学习价值的项目
- sql server 查询DB replication 信息
- Sublime Text 3 使用技巧
- linux常用命令之redhat