1601: [Usaco2008 Oct]灌水
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
【分析】:
新建一个虚拟N+1,它与每块农田连边,边权值就是在那个农场建水库的价钱,然后用这个图跑一遍最小生成树即可,我的程序中用的是Kruskal
【评测信息】:
Time:112 ms,Memory:2444 kb
【代码】:
/**************************************************************
Problem: 1601
Language: C++
Result: Accepted
Time:112 ms
Memory:2444 kb
****************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define MAX 310
#define MAXE 100001
int N,tot=0,fa[MAX],now=0,ans=0;
struct EDGE{int f,t,v;};
EDGE a[MAXE];
bool cmp(EDGE x,EDGE y){return x.v<y.v;}
int get(int x){return fa[x]==x ? x : (fa[x]=get(fa[x]));}
void add(int x,int y,int value)
{
a[++tot].t=y;
a[tot].f=x;
a[tot].v=value;
}
int main()
{
//freopen("input.in","r",stdin);
//freopen("output.out","w",stdout);
scanf("%d",&N);
for(int i=1;i<=N;i++)
{
int A;
scanf("%d",&A);
add(i,N+1,A);
}
for(int i=1;i<=N;i++)
for(int j=1;j<=N;j++)
{
int A;
scanf("%d",&A);
if(i!=j) add(i,j,A);
}
sort(a+1,a+1+tot,cmp);
for(int i=1;i<=N+1;i++)
fa[i]=i;
for(int i=1;i<=tot;i++)
{
if(get(a[i].f)!=get(a[i].t))
{
fa[get(a[i].f)]=get(a[i].t);
ans+=a[i].v;
now++;
}
}
printf("%d\n",ans);
//system("pause");
return 0;
}
转载注明出处:http://blog.youkuaiyun.com/u011400953