poj1287最小生成树水

来源:互联网 发布:免费翻墙安卓软件 编辑:程序博客网 时间:2024/05/16 23:56
已知有n个点,m条边,求最小生成树。
Sample Input
1 0
2 3
1 2 37
2 1 17
1 2 68
3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32
5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12
0

Sample Output
0
17
16
26

#include <cstdio>#include <cstring>#include <algorithm>#define N 100005using namespace std;typedef struct note {int u, v, w;}edge;edge e[N];int n, m;int sum, cnt;int f[N];int cmp(edge a, edge b){return a.w < b.w;}void init(){sum = 0; cnt = 0;for (int i = 1; i <= n; i++)f[i] = i;}int find(int x){return x == f[x] ? x : f[x] = find(f[x]);}int merge(int x, int y){int t1 = find(x), t2 = find(y);if (t1 != t2){f[t2] = t1;return 1;}return 0;}int kruscal(){init();for (int i = 0; i < m; i++){if (merge(e[i].u, e[i].v)){cnt++;sum += e[i].w;}if (cnt == n - 1)break;}if (cnt < n - 1)return -1;else return sum;}int main(){while (~scanf("%d", &n) && n){scanf("%d", &m);int t1, t2, t3, ans;for (int i = 0; i < m; i++)scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);sort(e, e + m, cmp);//对权值贪心无须考虑重边问题ans = kruscal();printf("%d\n", ans);}return 0;}

0 0
原创粉丝点击