简单的模板题:prim算法适合浓密图:
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 110 4 #define INF 100000000 5 6 int n, v[MAXN], low[MAXN], w[MAXN][MAXN]; 7 8 void solve() 9 { 10 int ans = 0; 11 memset(v,0,sizeof(v)); 12 v[0] = 1; 13 for(int i = 1; i < n; i ++) low[i] = w[0][i]; 14 for(int i = 0; i < n-1; i ++) 15 { 16 int min = INF, p; 17 for(int j = 0; j < n; j ++) 18 if(!v[j] && low[j] < min) min = low[j], p = j; 19 v[p] = 1; 20 ans += min; 21 for(int j = 0; j < n; j ++) 22 if(!v[j] && low[j] > w[p][j]) low[j] = w[p][j]; 23 } 24 printf("%d\n",ans); 25 } 26 27 int main() 28 { 29 while(~scanf("%d",&n)) 30 { 31 for(int i = 0; i < n; i ++) 32 for(int j = 0; j < n; j ++) 33 { 34 int a; 35 scanf("%d",&a); 36 w[i][j] = a; 37 } 38 solve(); 39 } 40 return 0; 41 }