【Kruskal】【最小生成树】灌水

L i n k Link Link

s s l   1462 ssl\ 1462 ssl 1462

D e s c r i p t i o n Description Description

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

I n p u t Input Input

*第一行:一个数n

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

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

O u t p u t Output Output

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

S a m p l e Sample Sample I n p u t Input Input

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

S a m p l e Sample Sample O u t p u t Output Output

9

H i n t Hint Hint

T r a i n Train Train o f of of T h o u g h t Thought Thought

设一个零号点与每个点连接,权值为造水库的代价
然后跑一遍最小生成树就好了
(然而我这菜鸡还是错了)

C o d e Code Code

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

using namespace std;

int x, y, z, t, n, k,  ans;
int fa[505];

struct node
{
	int w, h, k;
}w[200005];

int find(int k)
{
	while (fa[k] != k) k = fa[k];
	return k;
}

bool nm (node i, node j)
{return i.k < j.k;}

void add (int x, int y, int z)
{w[++t] = (node){y, x, z};}

int main()
{
	scanf("%d", &n);
	fa[0] = 0;
	for (int i = 1; i <= n; ++i)
	{
		scanf("%d", &k);
		add(0, i, k);
		fa[i] = i;
	}
	
	for (int i = 1; i <= n ;++i)
		for (int j = 1; j <= n; ++j)
		{
			scanf("%d", &k);
			if (i < j) add(i, j , k);
		}
	sort(w + 1, w + t + 1, nm);
	for (int i = 1; i <= t; ++i)
	{
		x = find(w[i].w);
		y = find(w[i].h);
		if (x != y)
		{
			fa[max(x, y)] = fa[min(x, y)];
			ans += w[i].k;
		}
	}
	printf("%d",ans);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值