练习四 1001
来源:互联网 发布:mfc access数据库 编辑:程序博客网 时间:2024/04/30 13:00
概述:给你一些城镇,以及各个镇之间的距离,现在要修建道路,把这些镇子穿起来,已知一些镇子之间已经有了道路(即不用再修了),现在求施工的最短路径。
思路:这是最小生成树问题,我采用的是kruskal算法。
感想:“一些镇子之间已经有了道路”这个条件比较难缠,想了一会才明白,只要另这些镇子的距离为0就可以,这样就不会影响结果。
#include <iostream>#include <fstream>#include <algorithm>using namespace std;const int N = 105;int father[N];int map[N][N];int find(int x) {if (x != father[x])father[x] = find(father[x]);return father[x];}struct edge{int x, y, v;}e[N*(N - 1) / 2];int cmp(edge e1, edge e2) {return e1.v<e2.v;}int main(){//ifstream cin("aaa.txt");int n;cin >> n;int ansa = n;for (int i = 0; i <= n; ++i)father[i] = i;for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j)cin >> map[i][j];int q;cin >> q;int temp1, temp2;for (int i = 0; i < q; ++i){cin >> temp1 >> temp2;map[temp1 - 1][temp2 - 1] = 0;}int cnt = 0;for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j){e[cnt].x = i;e[cnt].y = j;e[cnt].v = map[i][j];++cnt;}int ans = 0;sort(e, e + cnt, cmp);for (int i = 0; i < cnt; ++i){int x = find(e[i].x);int y = find(e[i].y);if (x != y){ans += e[i].v;father[x] = y;--ansa;if(ansa==1){cout << ans << endl;return 0;}}}}
0 0
- 练习四1001
- 练习四 1001
- 练习四 1001
- 练习四1001畅通工程
- 练习四
- 2016sdau课程练习专题四 1001
- 数据库练习四
- 查询练习(四)
- Scala练习(四)
- 听课练习(四)
- 笔试练习四
- 笔试练习四
- 练习四 1004
- 练习四 1003
- 练习四 1002
- 练习四 1005
- 练习四 1002
- 练习四 1003
- 最小连通网络
- Xcode cannot run using the selected device Xcode无法连接真机,进行真机调试
- Python小白研究之交互环境使用
- 读研心路历程,写给在读的师弟师妹和即将读研的同学-思想汇报
- 第十六周项目-文件保存学生名单
- 练习四 1001
- macOS 下使用 Android Studio 获取开发版和发布版SHA1证书
- 设计一个算法,给一个字符串进行二进制编码,使得编码后的字符串长度最短
- android中xml tools属性详解
- libpcap/tcpdump filter 语法
- Newtonsoft.dll JSON序列化与反序列化
- opencv-ios开发笔记8 从沙盒中找到训练生成的特征文件
- 队列实现
- 无损压缩算法发展