链接:
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1586
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82831#problem/E
代码:
#include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> using namespace std; const int N = 1000; const int INF = 0xfffffff; int n; int J[N][N], dist[N]; bool 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; int MIN=INF; for(j=1; j<=n; j++) { if(!vis[j] && dist[j]<MIN && dist[j]) { 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 () { int t; scanf("%d", &t); while(t--) { int i, j, a, b[N]; scanf("%d", &n); memset(J, 0, sizeof(J)); memset(b, 0, sizeof(b)); for(i=1; i<=n; i++) { scanf("%d", &a); b[i] = a; } for(i=1; i<=n; i++) for(j=1; j<=n; j++) { scanf("%d", &a); J[i][j] = a; } for(i=1; i<=n; i++) { for(j=1; j<=n; j++) J[i][j] += b[i]+b[j]; } int ans=Prim(); printf("%d\n", ans); } return 0; }
时间: 2024-10-06 04:52:52