nyoj--38 布线问题(最小生成树)
2016-03-10 14:36
253 查看
nyoj 38
Kruskal算法如下:
题解
计算最小生成树的权重,然后加上花费最小的那个顶点的值。Kruskal算法如下:
#include <iostream> #include <cstdio> #include <vector> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int maxn = 500 + 10; int n, e; struct Edge{ int u, v, c; Edge(int u, int v, int c):u(u), v(v), c(c){} }; vector<Edge> edges; int p[maxn]; int find(int x) { return x == p[x] ? x : p[x] = find(p[x]); } int cmp(const Edge& e1, const Edge& e2) { return e1.c < e2.c; } int solve() { for(int i = 0; i <= n; ++i) p[i] = i; sort(edges.begin(), edges.end(), cmp); int ans = 0; for(int i = 0; i < e; ++i) { int u = edges[i].u, v = edges[i].v, c = edges[i].c; u = find(u), v = find(v); if(u != v){ p[u] = v; ans += c; } } return ans; } int main() { //freopen("data.in", "r", stdin); int t; for(cin >> t; t--; ) { edges.clear(); int a, b, c; cin >> n >> e; for(int i = 0; i < e; ++i){ scanf("%d %d %d", &a, &b, &c); edges.push_back(Edge(a, b, c)); } int maxcost = 1 << 30, tmp; for(int i = 0; i < n; ++i){ scanf("%d", &tmp); maxcost = min(maxcost, tmp); } cout << solve() + maxcost << endl; } return 0; }
相关文章推荐
- RM格式压缩电影软件 Easy RealMedia Producer Full V1.94 下载
- 在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
- 比较简单的jquery教程 Easy Ajax with jQuery 中文版全集第1/3页
- Easy RM RMVB to DVD Burner v1.3.8 汉化版 下载 附注册码
- 详解图的应用(最小生成树、拓扑排序、关键路径、最短路径)
- 最小生成树算法之Prim算法
- 使用C语言实现最小生成树求解的简单方法
- Expandable "Detail" Table Rows
- linux下安装easy_install的方法
- 最小生成树算法——Prim和Kruskal算法的实现
- 归纳整理文件Easy Duplicate Finder2.24 破解版
- DM*** and Easy *** Server with ISAKMP Profiles
- easy ***
- cisco packet tracer 5.3 实现基于3A的easy ***
- [Leetcode题目]19. Remove Nth Node From End of List
- [Leetcode题目]21. Merge Two Sorted Lists
- [Leetcode题目]83. Remove Duplicates from Sorted List
- [Leetcode题目]160. Intersection of Two Linked Lists
- [Leetcode题目]203. Remove Linked List Elements
- [Leetcode题目]206. Reverse Linked List