题解——洛谷P1550 [USACO08OCT]打井Watering Hole(最小生成树,建图)

题面

题目背景

John的农场缺水了!!!

题目描述

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.

POINTS: 400

农民John 决定将水引入到他的n(1<=n<=300)个牧场。他准备通过挖若

干井,并在各块田中修筑水道来连通各块田地以供水。在第i 号田中挖一口井需要花费W_i(1<=W_i<=100,000)元。连接i 号田与j 号田需要P_ij (1 <= P_ij <= 100,000 , P_ji=P_ij)元。

请求出农民John 需要为连通整个牧场的每一块田地所需要的钱数。

输入输出格式

输入格式:

第1 行为一个整数n。

第2 到n+1 行每行一个整数,从上到下分别为W_1 到W_n。

第n+2 到2n+1 行为一个矩阵,表示需要的经费(P_ij)。

输出格式:

只有一行,为一个整数,表示所需要的钱数。

输入输出样例

输入样例#1:  复制
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
输出样例#1:  复制
9

说明

John等着用水,你只有1s时间!!!

题解

 神奇的建图方式,看到条件,首先想到最小生成树

然后发现每个点都有自己的点权(就是打井)

而且最后图还不连通

最小生成树需要联通图,我们要考虑怎么建立图,使其在不丢失信息的前提下使图联通

答案就产生了

设一个超级源,将所有点向它连边,权值为在每个点打井的权值

然后把点与点之间的\( n^{2} \)条边暴力建出,然后就跑一边kruskal

done!

贴代码

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 10000;
const int MAXM = 101000;
struct E{
    int u,v,w;
}edges[MAXM];
int cnt=0,first[MAXN],nxt[MAXM],n;
void addedge(int ux,int vx,int wx){
    cnt++;
    edges[cnt].u=ux;
    edges[cnt].v=vx;
    edges[cnt].w=wx;
    nxt[cnt]=first[ux];
    first[ux]=cnt;
}
bool cmp(E a,E b){
    if(a.w<b.w)
        return true;
    else
        return false;
}
int fa[MAXN],ans=0;
int find(int x){
    if(fa[x]==x)
        return x;
    else
        return fa[x]=find(fa[x]);
}
void kruskal(void){
    int inq=0;
    sort(edges+1,edges+cnt+1,cmp);
    for(int i=1;i<=cnt;i++){
        int um=edges[i].u;
        int vm=edges[i].v;
        int x=find(um);
        int y=find(vm);
        if(x==y)
            continue;
        else{
            fa[x]=y;
            ans+=edges[i].w;
            inq++;
        }
        if(inq==n)
            return;
    }
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        addedge(i,n+10,x);
        addedge(n+10,i,x);
    }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
            int x;
            scanf("%d",&x);
            if(i==j)
                continue;
            addedge(i,j,x);
        }
    for(int i=0;i<=n+100;i++)
        fa[i]=i;
    kruskal();
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/dreagonm/p/9484075.html