hdu 1233
赤裸裸的最小生成树
/*
* hdu1233/linux.c
* Created on: 2011-8-2
* Author : ben
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAXN 105
int map[105][105];
int N, M;
/**
* 普里姆求最小生成树,返回最小生成树的权值,返回-1表示图不连通
*/
int MST_Prim() {
int lowcost[MAXN];
int i, j, k, minc, ret = 0;
for (k = 1; k < N; k++) {
lowcost[k] = map[0][k];
}
lowcost[0] = 0;
for(i = 1; i < N; i++) {
minc = 0x7fffffff;
for(j = 0; j < N; j++) {
if(lowcost[j] > 0 && lowcost[j] < minc) {
minc = lowcost[j];
k = j;
}
}
if(minc == 0x7fffffff) {
return -1;
}
ret += minc;
lowcost[k] = 0;
for(j = 0; j < N; j++) {
if(lowcost[j] > map[k][j]) {
lowcost[j] = map[k][j];
}
}
}
return ret;
}
void buildmap() {
int i, j, k;
for (k = 0; k < M; k++) {
scanf("%d%d", &i, &j);
scanf("%d", &map[i - 1][j - 1]);
map[j - 1][i - 1] = map[i - 1][j - 1];
}
}
void work() {
while (scanf("%d", &N) == 1 && N > 0) {
M = N * (N - 1) / 2;
buildmap();
printf("%d\n", MST_Prim());
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
work();
return 0;
}