1. 程式人生 > >題解——洛谷P1550 [USACO08OCT]打井Watering Hole(最小生成樹,建圖)

題解——洛谷P1550 [USACO08OCT]打井Watering Hole(最小生成樹,建圖)

mount scan -o another 決定 clas con pan 通過

題面

題目背景

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;
}

題解——洛谷P1550 [USACO08OCT]打井Watering Hole(最小生成樹,建圖)