Description
Farmer John已经决定把水灌到他的n(1<=n<=300)块农田,农田被数字1到n标记。把一块土地进行灌水有两种方法,从其他农田饮水,或者这块土地建造水库。 建造一个水库需要花费wi(1<=wi<=100000),连接两块土地需要花费Pij(1<=pij<=100000,pij=pji,pii=0). 计算Farmer John所需的最少代价。
Input
*第一行:一个数n
*第二行到第n+1行:第i+1行含有一个数wi
*第n+2行到第2n+1行:第n+1+i行有n个被空格分开的数,第j个数代表pij。
Output
*第一行:一个单独的数代表最小代价.
Sample Input
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
Sample Output
9
输出详解:
Farmer John在第四块土地上建立水库,然后把其他的都连向那一个,这样就要花费3+2+2+2=9
题解:
由题分析可知,其实这是一个无向带权图,要求的只是一个MST而已,同时鉴于有w[i]这个东西,我选择多建立一个点0,w[i]就成了p[0][i]。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define MAXN 305
#define INF 0x3f3f3f3f
using namespace std;
int n;
typedef struct edge{
long long int w;
int s,t;
}Edge;
Edge E[100000];
long long int father[MAXN];
long long int w[MAXN];
long long int out,total;
int f(int now)
{
while(father[now]!=now) now=father[now];
return now;
}
bool c(const Edge a,const Edge b)
{
return a.w<b.w;
}
int main()
{
cin >> n;
out=0,total=0;
father[0]=0;
for(int i=1;i<=n;i++)
{
father[i]=i;
scanf("%lld",&E[total].w);
E[total].s=0;
E[total++].t=i;
}
long long int tmp;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%lld",&tmp);
if(i==j)
continue;
E[total].s=i;
E[total].t=j;
E[total++].w=tmp;
}
sort(E+0,E+total,c);
for(long long int i=0;i<total;i++)
{
int fa=f(E[i].s),fb=f(E[i].t);
if(fa==fb)
continue;
father[fa]=fb;
out+=E[i].w;
}
cout << out << endl;
return 0;
}