HDU 1102Constructing Roads
来源:互联网 发布:大数据特征 编辑:程序博客网 时间:2024/06/07 07:32
用的kruskal算法,主要就是把已经连接的路标记连接上,然后再求最小生成树就行了。
#include <cstdio>#include <algorithm>using namespace std;const int MAX = 1e4 + 5;struct EDGE{ int from, to , cost;}edge[MAX];int n, q;int fa[105], r[105];int comp(EDGE a, EDGE b){ return a.cost < b.cost;}void init(int n){ for (int i = 1; i <= n; ++i) { fa[i] = i; r[i] = 1; }}int find(int x){ return fa[x] == x ? x : fa[x] = find(fa[x]);}void unite(int a, int b){ a = find(a); b = find(b); if (a == b) return ; if (r[a] < r[b]) { fa[a] = b; } else { fa[b] = a; if (r[a] == r[b]) r[a]++; }}int main(){ while (scanf("%d", &n) != EOF) { int cnt_e = 0; int tmp; init(n); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { scanf("%d", &tmp); if (i != j) { ++cnt_e; edge[cnt_e].from = i; edge[cnt_e].to = j; edge[cnt_e].cost = tmp; } } } // printf("cnt_e = %d\n", cnt_e); sort(edge + 1, edge + 1 + cnt_e, comp); // printf("min_sum = %d\n", min_sum); scanf("%d", &q); int tmp_f, tmp_t; for (int i = 1; i <= q; ++i) { scanf("%d%d", &tmp_f, &tmp_t); //min_sum -= g[tmp_f][tmp_t]; unite(tmp_f, tmp_t); } int min_sum = 0; for (int i = 1; i <= cnt_e; ++i) { if (find(edge[i].from) != find(edge[i].to)) { min_sum += edge[i].cost; unite(edge[i].from, edge[i].to); } } printf("%d\n", min_sum); } return 0;}
0 0
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- Hdu-1102 Constructing Roads
- Hdu-1102 Constructing Roads
- hdu 1102 Constructing Roads
- HDU 1102 Constructing Roads
- hdu 1102 Constructing Roads
- hdu 1102 Constructing Roads
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- hdu 1102 Constructing Roads
- Hdu 1102 - Constructing Roads
- hdu 1102 Constructing Roads
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- HDU 1102 Constructing Roads
- 线程(java编程思想摘录和代码实验)
- __attribute__ directives in Objective-C
- ListView 加载数据 Holder 数据项重复 , 乱序
- 程序编写和调试的思考
- 面向接口编程
- HDU 1102Constructing Roads
- Android开发60条技术经验总结
- BMOB--QQ第三方登陆
- 终于明白了虚函数、纯虚函数和接口的实用方法和意义
- 计算矩阵行列式时奇排列与偶排列的判定
- Scala学习5之scala与java的不同之总结1
- node学习 express + mysql + ejs实现注册登录
- 新手笔记:JVM 基础知识
- sqlserver"重新启动计算机失败"的解决办法