prim水题:
#include <cstdio>
#include <cstring>
#define LEN 101
#define MMAX 9999999
int map[LEN][LEN];
int prime(int s, int city) {
int dist[LEN], used[LEN];
int i, j;
int res = 0;
memset(used, 0, sizeof(used));
for(i = 1; i <= city; i++) {
dist[i] = map[1][i];
}
used[1] = 1;
for(i = 1; i < city; i++) {
int imin, min;
min = MMAX;
for(j = 1; j <= city; j++) {
if(min > dist[j] && used[j] == 0) {
min = dist[j];
imin = j;
}
}
used[imin] = 1;
if(min == MMAX) {
return -1;
}
res += min;
for(j = 1; j <= city; j++) {
if(dist[j] > map[imin][j] && used[j] == 0) {
dist[j] = map[imin][j];
}
}
}
return res;
}
int main() {
int n;
int s, e, len, tmp, res;
while(scanf("%d", &n), n != 0) {
int i, j;
for(i = 0; i < LEN; i++) {
for(j = 0; j < LEN; j++) {
map[i][j] = MMAX;
}
}
tmp = n*(n-1)/2;
for(i = 0; i < tmp; i++) {
scanf("%d%d%d", &s, &e, &len);
map[s][e] = map[e][s] = len;
}
res = prime(1, n);
printf("%d\n", res);
}
return 0;
}