思路:最小生成树 + prime
代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; #define MAXN 110 #define INF 0XFFFFFFF int n; int vis[MAXN]; int lowcost[MAXN]; int G[MAXN][MAXN]; void init(){ memset(vis , 0 , sizeof(vis)); memset(lowcost , 0 , sizeof(lowcost)); for(int i = 1 ; i <= n ; i++){ for(int j = 1 ; j <= n ; j++) G[i][j] = INF; } } void prime(){ int pos , ans; ans = 0; vis[1] = 1; for(int i = 1 ; i <= n ; i++) lowcost[i] = G[1][i]; for(int i = 1 ; i <= n ; i++){ pos = -1; for(int j = 1 ; j <= n ; j++){ if(!vis[j] && (pos == -1 || lowcost[j] < lowcost[pos])) pos = j; } if(pos == -1) break; ans += lowcost[pos]; vis[pos] = 1; for(int j = 1 ; j <= n ; j++){ if(!vis[j] && lowcost[j] > G[j][pos]) lowcost[j] = G[j][pos]; } } printf("%d\n" , ans); } int main(){ int tmp; while(scanf("%d" , &n) != EOF){ init(); for(int i = 1 ; i <= n ; i++){ for(int j = 1 ; j <= n ; j++){ scanf("%d" , &tmp); if(G[i][j] > tmp) G[i][j] = tmp; } } prime(); } return 0; }