bzoj1601 灌水

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
 
一道最小生成树裸题
//Serene
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=300+10,maxm=100000+10;
int n,m;

long long aa;char cc;
long long read() {
	aa=0;cc=getchar();
	while(cc<'0'||cc>'9') cc=getchar();
	while(cc>='0'&&cc<='9') aa=aa*10+cc-'0',cc=getchar();
	return aa;
}

int e=0;
struct Node{
	int x,y;long long z;
}node[2*maxm];

bool cmp(const Node& a,const Node& b) {
	return a.z<b.z;
}

int fa[maxn];
int find(int x) {
	return x==fa[x]? x:fa[x]=find(fa[x]);
}

long long Kr() {
	long long rs=0,tot=0,xx,yy;
	for(int i=1;i<=n+1;++i) fa[i]=i;
	for(int i=1;i<=e&&tot!=n;++i) {
		xx=find(node[i].x);yy=find(node[i].y);
		if(xx!=yy) {
			fa[xx]=yy;
			tot++;
			rs+=node[i].z;
		}
	}
	return rs;
}

int main() {
	n=read();int x;
	for(int i=1;i<=n;++i) {
		node[++e].x=i;
		node[e].y=n+1;
		node[e].z=read();
	}
	for(int i=1;i<=n;++i) for(int j=1;j<=n;++j)if(i<j){
		node[++e].x=i;
		node[e].y=j;
		node[e].z=read();
	}
	else x=read();
	sort(node+1,node+e+1,cmp);
	printf("%lld",Kr());
	return 0;
}

  

posted @ 2017-09-13 11:29  shixinyi  阅读(236)  评论(0编辑  收藏  举报