当前位置: 代码迷 >> 综合 >> USACO Oct 2008 Watering Hole
  详细解决方案

USACO Oct 2008 Watering Hole

热度:67   发布时间:2023-12-16 15:45:07.0

描述

Farmer John has decided to bring water to his N (1 <= N <= 300) pastures which are conveniently numbered 1…N. He may bring water to a pasture either by building a well in that pasture or connecting the pasture via a pipe to another pasture which already has water.

Digging a well in pasture i costs W_i (1 <= W_i <= 100,000). Connecting pastures i and j with a pipe costs P_ij (1 <= P_ij <= 100,000; P_ij = P_ji; P_ii=0).

Determine the minimum amount Farmer John will have to pay to water all of his pastures.
农夫约翰决定给他的N(1 <= N <= 300)牧场放水,这些牧场方便地编号为1…N。他可以通过在牧场上建造水井或通过管道将牧场连接到已经有水的另一个牧场来将水引入牧场。

在牧场i上挖一口井要花W_i(1 <= W_i <= 100,000)。用管道连接牧场i和j的成本为P_ij(1 <= P_ij <= 100,000; P_ij = P_ji; P_ii = 0)。

确定农民约翰必须为所有牧场浇水的最低费用。

输入

Line 1: A single integer: N
Lines 2…N + 1: Line i+1 contains a single integer: W_i
Lines N+2…2N+1: Line N+1+i contains N space-separated integers; the j-th integer is P_ij

输出

Line 1: A single line with a single integer that is the minimum cost of providing all the pastures with water.

样例输入

4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0

样例输出

9

提示

INPUT DETAILS:

There are four pastures. It costs 5 to build a well in pasture 1,4 in pastures 2 and 3, 3 in pasture 4. Pipes cost 2, 3, and 4depending on which pastures they connect.

OUTPUT DETAILS:

Farmer John may build a well in the fourth pasture and connect each pasture to the first, which costs 3 + 2 + 2 + 2 = 9.

解题思路

因为有挖井这个操作,一开始想了很久,总感觉不对。看了大佬的代码发现可以把挖井也放到树上去,让挖井是从0到那块地。然后就变成了一个最小生成树问题了。

代码

#include<bits/stdc++.h>
using namespace std;
int w[305];
struct node
{
    int a,b,m;
}v[60000];
int f[305];
void intt(int n)
{
    for(int i=0;i<=n;i++)f[i]=i;
}
bool cmp(node x,node y)
{
    return x.m<y.m;
}
int findl(int x)
{
    return f[x]==x?x:f[x]=findl(f[x]);
}
void update(int x,int y)
{
    f[x]=y;
}
int main()
{
    int n;int min1=0x3f3f3f;scanf("%d",&n);intt(n);int d=0;for(int i=1;i<=n;i++){
    scanf("%d",&v[d].m);v[d].a=0;v[d++].b=i;}for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++){
    int mm;scanf("%d",&mm);if(i<j){
    v[d].a=i;v[d].b=j;v[d++].m=mm;}}}sort(v,v+d,cmp);int sum=0;int l,r;for(int i=0;i<d;i++){
    l=findl(v[i].a);r=findl(v[i].b);if(l!=r){
    update(l,r);sum+=v[i].m;}}printf("%d\n",sum);
}
  相关解决方案