poj 1258 Agri-Net
//poj 1258 Agri-Net //最小生成树(MST) #include <stdio.h> #include <string.h> #define N 105 #define INF 1<<30 int n; int map[N][N], dis[N], ans; bool vis[N]; void prim() { for(int i = 0; i < n; ++i) { dis[i] = INF; vis[i] = false; } dis[0] = 0; while(1) { int min = INF, index = -1; for(int i = 0; i < n; ++i) { if(vis[i] == false && min > dis[i]) { min = dis[i]; index = i; } } if(index == -1) return; vis[index] = true; ans += min; for(int i = 0; i < n; ++i) if(vis[i] == false && dis[i] > map[index][i]) dis[i] = map[index][i]; } } int main() { while(scanf("%d", &n) != EOF) { ans = 0; memset(map, 0, sizeof(map)); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { scanf("%d", &map[i][j]); map[j][i] = map[i][j]; } } prim(); printf("%d\n", ans); } return 0; }