链接:
http://poj.org/problem?id=1258
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82831#problem/I
代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 110; const int INF = 0xfffffff; int n, J[N][N], dist[N], vis[N]; int Prim() { int i, j, ans=0; dist[1]=0; memset(vis, 0, sizeof(vis)); vis[1]=1; for(i=1; i<=n; i++) dist[i]=J[1][i]; for(i=1; i<n; i++) { int index=1, MIN=INF; for(j=1; j<=n; j++) { if(!vis[j] && dist[j]<MIN) { index=j; MIN=dist[j]; } } vis[index]=1; ans += MIN; for(j=1; j<=n; j++) { if(!vis[j] && dist[j]>J[index][j]) dist[j]=J[index][j]; } } return ans; } int main () { while(scanf("%d", &n)!=EOF) { int i, j; memset(J, 0, sizeof(J)); for(i=1; i<=n; i++) for(j=1; j<=n; j++) scanf("%d", &J[i][j]); int ans=Prim(); printf("%d\n", ans); } return 0; }
时间: 2024-10-25 21:13:14