zoj(1586)最小生成树

题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1586

#include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <string> #include <iostream> using namespace std ; const int maxn = 1005; const int inf = 0xffffff; int edge[maxn][maxn]; int lowcost[maxn]; int used[maxn]; int adpter[maxn]; int n; void prim(){ int sum = 0; for(int i = 1;i < n;i++){ lowcost[i] = edge[0][i]; used[i] = 0; } lowcost[0] = 0; for(int i = 1;i < n;i++){ int k = -1; for(int j = 1;j < n;j++){ if(used[j] != -1&&(k == -1||lowcost[j]<lowcost[k])) k = j; } //printf("%d %d %d\n",used[k],k,lowcost[k]); sum += lowcost[k]; used[k] = -1; for(int j = 1;j < n;j++){ if(used[j] != -1 && edge[k][j] < lowcost[j]){ lowcost[j] = edge[k][j]; used[j] = k; } } } printf("%d\n",sum); } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i = 0;i < n;i++) scanf("%d",adpter+i); for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ scanf("%d",&edge[i][j]); if(i == j) edge[i][j] = inf; else edge[i][j] += (adpter[i] + adpter[j]); } } prim(); } return 0 ; }
原文地址:https://www.cnblogs.com/Roly/p/3024893.html