题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1601
解:完全最小生成树,先找一个最便宜的牧场挖口井,然后开始的距离都为打井的费用,然后用运输的费用去更新。
程序:
#include<iostream> #include<cstdio> #include<cmath> #define INF 2100000000 using namespace std; int n,m,w[2000],ans,dis[2000],f[2000][2000]; bool vis[2000]; void prim() { for (int i=1;i<=n;i++) { dis[i]=w[i]; vis[i]=false; } for (;;) { int ch=0,minx=INF; for (int i=1;i<=n;i++) if ((!vis[i])&&(dis[i]<minx)) { minx=dis[i]; ch=i; } if (ch==0) break; vis[ch]=true; ans+=dis[ch]; for (int i=1;i<=n;i++) dis[i]=min(dis[i],f[ch][i]); } } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&w[i]); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf("%d",&f[i][j]); prim(); printf("%d ",ans); return 0; }