#100-【最小生成森林(最小生成树变种)】灌水

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82729314

#100祭!

Description

Farmer John已经决定把水灌到他的n(1<=n<=300)块农田,农田被数字1到n标记。把一块土地进行灌水有两种方法,从其他农田饮水,或者这块土地建造水库。 建造一个水库需要花费wi(1<=wi<=100000),连接两块土地需要花费Pij(1<=pij<=100000,pij=pji,pii=0). 计算Farmer John所需的最少代价。

Input

第一行:一个数n

第二行到第n+1行:第i+1行含有一个数wi

第n+2行到第2n+1行:第n+1+i行有n个被空格分开的数,第j个数代表pij。

Output

第一行:一个单独的数代表最小代价.

Sample Input

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

Sample Output

9

HINT

 

【输出详解】

Farmer John在第四块土地上建立水库,然后把其他的都连向那一个,这样就要花费3+2+2+2=9

先是0(超级源点)到i连边长度wi,随后正常建图即可。

#include <iostream>
#include <vector>
#include <algorithm>

#define SIZE 310

using namespace std;

struct edge
{
	int from, to, dis;
};

vector<edge> graph;
int pre[SIZE];

bool comp(edge a, edge b)
{
	return a.dis < b.dis;
}

int find(int x) // 找祖先(并查集操作)
{
	return (pre[x]) ? pre[x] = find(pre[x]) : x; // 顺便状态压缩
}

int main(int argc, char** argv)
{
	int n, i, j, x, res = 0, c = 0, u, v, w, prex, prey;
	
	scanf("%d", &n);
	for (i = 1; i <= n; ++i)
	{
		scanf("%d", &x);
		graph.push_back({0, i, x}); // 连0点(最小生成森林建图)
	}
	for (i = 1; i <= n; ++i) // 正常建图
	{
		for (j = 1; j <= n; ++j)
		{
			scanf("%d", &x);
			if (i <= j)
			{
				graph.push_back({i, j, x});
			}
		}
	}
	
	sort(graph.begin(), graph.end(), comp); // 注意vector类型要用vector::begin()和vector::end()函数作为开头和结尾
	for (i = 0; i < graph.size(); ++i) // K算法求最小生成树
	{
		u = graph[i].from;
		v = graph[i].to;
		w = graph[i].dis;
		prex = find(u); // 看建这条边是否有必要(并查集操作)
		prey = find(v);
		if (prex ^ prey) // ^是位运算异或符,这里是不等于(!=)的意思
		{
			res += w;
			if (++c == n) // 连了n(= n + 1 - 1)条边,直接退出
			{
				break;
			}
			pre[prex] = prey;
		}
	}
	
	printf("%d", res);
	
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/82729314
今日推荐