信息学 新的开始 最小生成树

一、内容

题目描述

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

二、思路

  • 由于每个发电站可以自己发电,那么就可以建立一个超级源点0号点,0号点与每个发电站连一条边,权值为在该点建发电站的花费。
  • 问题就转化为在这个新图上求最小生成树。

三、代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 305;
int n, v, d[N], g[N][N];
bool vis[N];
int prime() {
	int ans = 0;
	memset(d, 0x3f, sizeof(d));
	for (int i = 0; i <= n; i++) {
		int t = -1;
		for (int j = 0; j <= n; j++) {
			if (!vis[j] && (t == -1 || d[t] > d[j])) t = j;
		}
		if (i) ans += d[t]; //代表不是第一个点
		vis[t] = true; //加入集合
		//更新其他点到集合的距离 
		for (int j = 0; j <= n; j++) d[j] = min(d[j], g[t][j]); 
	}
	return ans;
} 
int main() {
	scanf("%d", &n);
	//添加0点为超级源点 
	for (int i = 1; i <= n; i++) scanf("%d", &g[0][i]); 
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			scanf("%d", &g[i][j]);
		}
	}
	printf("%d", prime());
	return 0;
}
发布了414 篇原创文章 · 获赞 380 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/104219257