bzoj1601[Usaco2008 Oct]灌水*

bzoj1601[Usaco2008 Oct]灌水

题意:

n块土地,要让它们全部都灌到水。使一个土地灌到水需要在这块土地上建水库或使它直接或间接与有水库的土地相连。给出在每块土地上建水库的费用和土地间两两连边的费用,求最小费用。n≤300

题解:

建一个超级源,让它们和所有土地连边,费用为在这块土地上建水库的费用。然后就是求最小生成树了。

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <cmath>
 5 #define maxn 400
 6 #define inc(i,j,k) for(int i=j;i<=k;i++)
 7 #define ll long long
 8 using namespace std;
 9 
10 inline int read(){
11     char ch=getchar(); int f=1,x=0;
12     while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
13     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
14     return f*x;
15 }
16 int n,fa[maxn],cnt,ans;
17 int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
18 struct e{int f,t,len;}; e es[maxn*maxn+maxn]; int ess;
19 bool cmp(e a,e b){return a.len<b.len;}
20 inline bool merge(int _x,int _y){int x=find(_x),y=find(_y); if(x==y)return 0; fa[x]=y; return 1;}
21 int main(){
22     n=read(); inc(i,1,n){int a=read(); es[++ess]=(e){0,i,a}; fa[i]=i;}
23     inc(i,1,n)inc(j,1,n){int a=read(); if(i<j)es[++ess]=(e){i,j,a};}
24     sort(es+1,es+ess+1,cmp); cnt=0;
25     inc(i,1,ess){if(merge(es[i].f,es[i].t))ans+=es[i].len,cnt++; if(cnt==n)break;}
26     printf("%d",ans); return 0;
27 }

 

20160729

posted @ 2016-07-30 23:03  YuanZiming  阅读(421)  评论(0编辑  收藏  举报