标签:
题目:http://poj.org/problem?id=1287
题目不多说, 最小生成树模版题。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; struct NoThing { int from, to, val; } edge[10001]; bool cMp(NoThing from, NoThing to) { return from.val < to.val; } int n, m, father[51]; void init() { for(int i = 1; i <= n; i++) father[i] = i; } int Find(int a) { if(a == father[a]) return a; else return father[a] = Find(father[a]); } bool Mercy(int a, int b) { int Q = Find(a); int P = Find(b); if(Q != P) { father[Q] = P; return true; } return false; } int main() { while(~scanf("%d", &n), n) { init(); scanf("%d", &m); for(int i = 0; i < m; i++) scanf("%d%d%d", &edge[i].from, &edge[i].to, &edge[i].val); sort(edge, edge+m, cMp); int sum = 0; for(int i = 0; i < m; i++) if(Mercy(edge[i].from, edge[i].to)) sum += edge[i].val; printf("%d\n", sum); } return 0; }
#include <cstdio> #include <cstring> #include <iostream> #define M 51 using namespace std; const int INF = 0x3f3f3f3f; int n, m, vis[M], dis[M], map[M][M]; void Prime() { int sum = 0; memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; i++) dis[i] = map[1][i]; vis[1] = 1; for(int i = 1; i < n; i++) { int temp = 1, min = INF; for(int j = 1; j <= n; j++) { if(!vis[j] && dis[j] < min) { temp = j; min = dis[j]; } } if(min == INF) return; vis[temp] = 1; sum += min; for(int j = 1; j <= n; j++) if(!vis[j] && dis[j] > map[temp][j]) dis[j] = map[temp][j]; } printf("%d\n", sum); } int main() { while(~scanf("%d", &n), n) { scanf("%d", &m); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { if(i == j) map[i][j] = 0; else map[i][j] = INF; } for(int i = 0; i < m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); if(map[a][b] > c) map[a][b] = map[b][a] = c; } Prime(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4837793.html