首页 > 代码库 > bzoj1601: [Usaco2008 Oct]灌水
bzoj1601: [Usaco2008 Oct]灌水
经典延伸最小生成树问题。。。
#include<cstdio>#include<cstring>#include<cctype>#include<algorithm>using namespace std;#define rep(i,s,t) for(int i=s;i<=t;i++)#define dwn(i,s,t) for(int i=s;i>=t;i--)#define clr(x,c) memset(x,c,sizeof(x))int read(){ int x=0;char c=getchar(); while(!isdigit(c)) c=getchar(); while(isdigit(c)) x=x*10+c-‘0‘,c=getchar(); return x;}const int nmax=305;const int maxn=100005;const int inf=0x7f7f7f7f;struct edge{ int from,to,dist; bool operator<(const edge &rhs)const{ return dist<rhs.dist;}};edge es[maxn];int fa[nmax];int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]);}int main(){ int n=read(),u,v,d,cnt=0; rep(i,1,n) { es[++cnt].from=i,es[cnt].to=n+1,es[cnt].dist=read(); } rep(i,1,n) rep(j,1,n){ u=read(); if(i!=j) es[++cnt].from=i,es[cnt].to=j,es[cnt].dist=u; } sort(es+1,es+cnt+1); int ans=0,tot=0; rep(i,1,n+1) fa[i]=i; rep(i,1,cnt){ int ta=find(es[i].from),tb=find(es[i].to); if(ta!=tb){ fa[ta]=tb;ans+=es[i].dist; if(++tot==n) break; } } printf("%d\n",ans); return 0;}
1601: [Usaco2008 Oct]灌水
Time Limit: 5 Sec Memory Limit: 162 MBSubmit: 1776 Solved: 1162
[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
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
输出详解:
Farmer John在第四块土地上建立水库,然后把其他的都连向那一个,这样就要花费3+2+2+2=9
HINT
Source
资格赛
bzoj1601: [Usaco2008 Oct]灌水
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。