天天看點

Luogu P1550 打井Watering HoleP1550 [USACO08OCT]打井Watering Hole

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<br>
           

  

說明

John等着用水,你隻有1s時間!!!

好吧,原諒我太弱了,我也是看的題解,直接被泥萌的腦洞給吓着了。

$$%%%$$

居然是把打井的點看做是與農夫山泉農夫三拳連起來,就是和0号節點連邊,然後直接就是最小生成樹的模闆題了。

腦洞腦洞

上代碼

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int n, xxx, cnt, ans, tot, f[307];

bool vis[307][307];

struct edge{int u, v, w;}ed[301*301];

int find(int x) {
	if(f[x] == x) return x;
	else return f[x] = find(f[x]);
}

bool cmp(edge a, edge b) {
	return a.w < b.w;
}

int main() {
	scanf("%d", &n);
	for(int i=1; i<=n; i++) {scanf("%d", &ed[++cnt].w); ed[cnt].u = 0, ed[cnt].v = i;}
	for(int i=1; i<=n; i++) f[i] = i;
	for(int i=1; i<=n; i++) {
		for(int j=1; j<=n; j++) {
			scanf("%d", &xxx);
			if(i != j&&!vis[i][j]&&!vis[j][i]) {
				ed[++cnt].u = i, ed[cnt].v = j, ed[cnt].w = xxx;
				vis[i][j] = 1, vis[j][i] = 1;
			}
		}
	}
	sort(ed+1, ed+1+cnt, cmp);
	for(int i=1; i<=cnt; i++) {
		int x = find(ed[i].u), y = find(ed[i].v);
		if(x != y) {
			f[x] = find(y);
			ans += ed[i].w;
			tot++;
		}
		if(tot == n) break;
	}
	printf("%d", ans);
	return 0;
}
           

  

轉載于:https://www.cnblogs.com/bljfy/p/8946750.html