标签:最小生成树
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0
#include <stdio.h> #include <string.h> #define M 105 #define INF 0x3f3f3f3f int map[M][M], low[M], n; bool vis[M]; int prim(){ int i, min, pos = 1, j; for(i = 1; i <= n; i ++){ low[i] = map[pos][i]; vis[i] = 0; } int ans = 0; vis[pos] = 1; for(i = 1; i < n; i++){ min= INF; for(j = 1; j <= n; j ++){ if(!vis[j]&&low[j] < min){ min = low[j]; pos = j; } } if(min == INF) break; vis[pos] = 1; ans += min; for(j = 0; j <= n; j ++) if(!vis[j]&&map[pos][j] < low[j]) low[j] = map[pos][j]; } return ans; } int main(){ while(scanf("%d", &n), n){ int i, a, b, c, d, j; for(i = 1; i <= n; i ++) for(j = 1; j <= n; j ++) map[i][j] = INF; for(i = 0; i < n*(n-1)/2; i++){ scanf("%d%d%d%d", &a, &b, &c, &d); if(d){ map[a][b] = map[b][a] = 0; continue; } if(map[a][b] > c) map[a][b] = map[b][a] = c; } printf("%d\n", prim()); } return 0; }
#include <stdio.h> #include <string.h> #include <algorithm> #define M 105 #define INF 0x3f3f3f3f using namespace std; struct node{ int from, to, val; }s[M*M]; int fat[M], tot, n; int f(int x){ if(fat[x] != x) fat[x] = f(fat[x]); else return x; } int cmp(node a, node b){ return a.val<b.val; } int kruskal(){ int i; for(i = 1; i <= n; i ++) fat[i] = i; int ans = 0; sort(s, s+tot, cmp); for(i = 0; i< tot; i ++){ //printf("%d%d%d..\n", s[i].from, s[i].to, s[i].val); int x = f(s[i].from); int y = f(s[i].to); //printf("%d..%d..\n", x, y); if(x != y){ ans += s[i].val; fat[y] = x; } } return ans; } int main(){ while(scanf("%d", &n), n){ tot = n*(n-1)/2; int i, a, b, c, d; for(i = 0; i < tot; i++){ scanf("%d%d%d%d", &s[i].from, &s[i].to, &s[i].val, &d); if(d) s[i].val = 0; } printf("%d\n", kruskal()); } return 0; }
标签:最小生成树
原文地址:http://blog.csdn.net/shengweisong/article/details/41014235