bzoj 1601: [Usaco2008 Oct]灌水

1601: [Usaco2008 Oct]灌水

Time Limit: 5 Sec   Memory Limit: 162 MB
Submit: 1839   Solved: 1201
[ Submit][ Status][ Discuss]

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

HINT

Source

资格赛




心情不好来刷水

虚构一个源点,向n个点建权值为wi的边,对这n+1个点做最小生成树


水。。。。。



附代码:

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<climits>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define N 310
#define M N*N<<1
using namespace std;
int n,tot,w[N],p[N][N],ans,f[N];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
struct edge{int u,v,c;}e[M];
bool operator < (edge a,edge b){return a.c<b.c;}
void kruscal()
{
	for(int i=1;i<=n+1;i++)f[i]=i;
	sort(e+1,e+1+tot);
	for(int i=1;i<=tot;i++)
	{
		int x=e[i].u,y=e[i].v;
		int fx=find(x),fy=find(y);
		if(fx==fy)continue;
		if(fx>fy)swap(fx,fy);
		f[fy]=fx;ans+=e[i].c;
	}
}
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",&p[i][j]);
	for(int i=1;i<=n;i++)
		for(int j=i+1;j<=n;j++)
			e[++tot].u=i,e[tot].v=j,e[tot].c=p[i][j];
	for(int i=1;i<=n;i++)
		e[++tot].u=n+1,e[tot].v=i,e[tot].c=w[i];
	kruscal();printf("%d\n",ans);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值