练习四 1004

来源:互联网 发布:mmd改模软件 编辑:程序博客网 时间:2024/04/30 11:42

概述:给你一些镇子,和镇子之间的距离,现在要修一条路,把所有镇子连起来,求路的最短距离。

思路:最小生成树问题,我采用的还是KRUSKAL是第一题的简化版,详情请看第一题。

感想:刷了第一题,再看这个题,感觉好简单。

#include <iostream>#include <fstream>#include <algorithm>using namespace std;const int N = 105;int father[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;while (cin >> n&&n){for (int i = 0; i <= n; ++i)father[i] = i;n = n*(n - 1) / 2;for (int i = 0; i<n; i++)cin>>e[i].x>>e[i].y>>e[i].v;sort(e, e + n, cmp);int ans = 0;for (int i = 0; i < n; ++i){int x = find(e[i].x);int y = find(e[i].y);if (x != y){ans += e[i].v;father[x] = y;}}cout << ans << endl;}return 0;}


0 0
原创粉丝点击