POJ2377-Bad Cowtractors
来源:互联网 发布:dede免费源码站 编辑:程序博客网 时间:2024/06/04 21:16
最小生成树的变形题,最大生成树。
这道题显然用Kruskal算法可以直接计算最小生成树的值,但是题目需要判断最小生成树是否存在,因此我们引入变量node_num表示树中的节点数。
比较树中的节点树与总节点树即可。
ps.为什么是单向边?
#include <cstdio>#include <algorithm>using namespace std;const int maxn = 1000 + 10;const int maxm = 2*20000 + 10;int par[maxn];int rk[maxn];struct edge { int from; int to; int cost;};edge es[maxm];int node_num;void init(int n) { for (int i = 0; i < n; i++) { par[i] = i; rk[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 (rk[x] < rk[y]) { par[x] = y; } else { par[y] = x; if (rk[x] == rk[y]) { rk[x]++; } }}bool same(int x, int y) { return find(x) == find(y);}bool comp(const edge& e1, const edge& e2) { return e1.cost > e2.cost;}int kruskal(int n, int m) { sort(es, es + m, comp); init(n); int res = 0; node_num = 1; for (int i = 0; i < m; i++) { edge e = es[i]; if (!same(e.from, e.to)) { unite(e.from, e.to); res += e.cost; node_num++; } } return res;}int main(int argc, char const *argv[]) { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d%d%d", &es[i].from, &es[i].to, &es[i].cost); es[i].from--; es[i].to--; } int ans = kruskal(n, m); if (node_num < n) { puts("-1"); } else { printf("%d\n", ans); } return 0;}
0 0
- poj2377 - Bad Cowtractors
- POJ2377--Bad Cowtractors
- POJ2377 Bad Cowtractors
- POJ2377-Bad Cowtractors
- POJ2377 Bad Cowtractors
- POJ2377 Bad Cowtractors 最小生成树
- POJ2377 Bad Cowtractors 【最大生成树】
- poj2377 Bad Cowtractors(最小生成树)
- POJ2377 Bad Cowtractors(最大生成树)
- poj2377 Bad Cowtractors (最大生成树)
- [POJ2377]Bad Cowtractors牛的报复
- poj2377 -- Bad Cowtractors(最大生成树)
- 【poj2377】Bad Cowtractors 【USACO 2004 December Silver】
- POJ2377 Bad Cowtractors【Kruskal】【求最大生成树】
- poj2377 Bad Cowtractors(最大生成树的Prim和Kruskal做法)
- Bad Cowtractors
- Bad Cowtractors
- Bad Cowtractors
- Asp.net Core + EF Core + Bootstrap搭建的MVC后台通用管理系统模板(跨平台版本)
- Android应用开发SharedPreferences存储数据的使用方法
- AngularJS 指令
- 文章标题
- HDU 5735 Born Slippy
- POJ2377-Bad Cowtractors
- [172] Factorial Trailing Zeroes
- 【几何】平面线段交
- HDU 5742 It's All In The Mind(思维水)
- C++ pure virtual function call
- Unity全面的面试题(包含答案)
- 1074. Reversing Linked List (25)
- 国内一线互联网公司面试题库
- 机器学习之k近邻法