题目背景
John的农场缺水了!!!
题目描述
Farmer John has decided to bring water to his N (1 <= N <= 300) pastures which are conveniently numbered 1…N. He may bring water to a pasture either by building a well in that pasture or connecting the pasture via a pipe to another pasture which already has water.
Digging a well in pasture i costs W_i (1 <= W_i <= 100,000).
Connecting pastures i and j with a pipe costs P_ij (1 <= P_ij <= 100,000; P_ij = P_ji; P_ii=0).
Determine the minimum amount Farmer John will have to pay to water all of his pastures.
POINTS: 400
农民John 决定将水引入到他的n(1<=n<=300)个牧场。他准备通过挖若
干井,并在各块田中修筑水道来连通各块田地以供水。在第i 号田中挖一口井需要花费W_i(1<=W_i<=100,000)元。连接i 号田与j 号田需要P_ij (1 <= P_ij <= 100,000 , P_ji=P_ij)元。
请求出农民John 需要为使所有农场都与有水的农场相连或拥有水井所需要的钱数。
注意是最少的钱数,这点题目没讲清
输入输出格式
输入格式:
第1 行为一个整数n。
第2 到n+1 行每行一个整数,从上到下分别为W_1 到W_n。
第n+2 到2n+1 行为一个矩阵,表示需要的经费(P_ij)。
输出格式:
只有一行,为一个整数,表示所需要的钱数。
输入输出样例
输入样例#1:
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
输出样例#1:
9
注意:本题比起求最小生成树多了一个要判断直接打井的情况。但是这个情况如果我们把它思考一下认为是从源点“地下水”处打的水,就是0到i,花费是w[i]。那么这道题就是一个套用kruskal的算法。
贴个代码如下:
#include<stdio.h>
#include<algorithm>
using namespace std;
int n,m;//n个牧场,m条边
int w[305];//挖第i号田中的一口井需要的花费
int p[305][305];//连接i号和j号田需要的花费
int a[305];
struct Edge
{
int from,to,dis;//从田from到田to需要dis元
}e[100005];
bool cmp(Edge x,Edge y)
{
return x.dis<y.dis;
}
int father(int x)
{
if(a[x]==x)
return x;
a[x]=father(a[x]);
return father(a[x]);
}
bool check(int x,int y)
{
if(father(x)==father(y))
return true;
else return false;
}
void merge(int x,int y)
{
if(check(x,y)==false)
a[father(x)]=father(y);
}
int kruskal()
{
int sum=0;//记录少的钱
int cnt=0;//记录已经选择了多少条边
for(int i=1;i<=m;i++)
{
if(check(e[i].from,e[i].to)==false)
{
merge(e[i].from,e[i].to);
sum=sum+e[i].dis;
cnt++;
}
if(cnt==n)//因为要加上“地下水”,所以一共是n+1个节点,要有n条边
break;
}
return sum;
}
int main()
{
int i,j;
while(scanf("%d",&n)!=EOF)
{
m=1;
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
e[m].from=0; //将打井与"地下水"连接
e[m].to=i;
e[m].dis=w[i];
m++;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&p[i][j]);
if(i<j)
{
e[m].from=i;
e[m].to=j;
e[m].dis=p[i][j];//将二维数组保存的边用结构体保存起来
m++;
}
}
m--;
for(i=0;i<=n;i++)//祖宗初始化
a[i]=i;
sort(e+1,e+m+1,cmp);
printf("%d\n",kruskal());
}
}