题目链接:http://poj.org/problem?id=1287
Sample Input 1 0 2 3 1 2 37 2 1 17 1 2 68 3 7 1 2 19 2 3 11 3 1 7 1 3 5 2 3 89 3 1 91 1 2 32 5 7 1 2 5 2 3 7 2 4 8 4 5 11 3 5 10 1 5 6 4 2 12 0 Sample Output 0 17 16 26
分析:最小生成树纯模板
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cmath> 5 using namespace std; 6 #define N 110 7 #define met(a, b) memset(a, b, sizeof(a)) 8 #define INF 0x3f3f3f3f 9 10 11 int n, m, dist[N], Maps[N][N], vis[N]; 12 13 int Prim(int s) 14 { 15 vis[s] = 1; 16 for(int i=1; i<=n; i++) 17 { 18 dist[i] = Maps[s][i]; 19 } 20 int sum = 0; 21 for(int i=1; i<n; i++) 22 { 23 int Min = INF, Index = -1; 24 for(int j=1; j<=n; j++) 25 { 26 if(!vis[j] && Min>dist[j]) 27 { 28 Min = dist[j]; 29 Index = j; 30 31 } 32 } 33 sum += Min; 34 vis[Index] = 1; 35 for(int j=1; j<=n; j++) 36 { 37 if(!vis[j] && dist[j]>Maps[Index][j]) 38 { 39 dist[j] = Maps[Index][j]; 40 } 41 } 42 43 } 44 return sum; 45 } 46 47 void Init() 48 { 49 for(int i=0; i<=n; i++) 50 { 51 for(int j=0; j<=n; j++) 52 Maps[i][j] = (i==j)?0:INF; 53 dist[i] = INF; 54 vis[i] = 0; 55 } 56 } 57 58 int main() 59 { 60 while(scanf("%d", &n), n) 61 { 62 int u, v, w; 63 Init(); 64 scanf("%d", &m); 65 for(int i=1; i<=m; i++) 66 { 67 scanf("%d %d %d", &u, &v, &w); 68 Maps[u][v] = Maps[v][u] = min(Maps[u][v], w); 69 } 70 int ans = Prim(1); 71 72 printf("%d\n", ans); 73 } 74 return 0; 75 }