Week6 HomeWork C 掌握魔法の东东I 最小生成树

题目描述

东东在老家农村无聊,想种田。农田有 n 块,编号从 1~n。种田要灌氵
众所周知东东是一个魔法师,他可以消耗一定的 MP 在一块田上施展魔法,使得黄河之水天上来。他也可以消耗一定的 MP 在两块田的渠上建立传送门,使得这块田引用那块有水的田的水。 (1<=n<=3e2)
黄河之水天上来的消耗是 Wi,i 是农田编号 (1<=Wi<=1e5)
建立传送门的消耗是 Pij,i、j 是农田编号 (1<= Pij <=1e5, Pij = Pji, Pii =0)
东东为所有的田灌氵的最小消耗

Input

第1行:一个数n
第2行到第n+1行:数wi
第n+2行到第2n+1行:矩阵即pij矩阵

Output

东东最小消耗的MP值

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

算法/思路分析

本题要求灌溉所有田的最小消耗,如果将天、每一块田都记为点,则本题可建立一个有向图模型,问题就转化为以“天上”为起点的最小生成树问题。

最小生成树这里使用熟知的Kruskal算法:每次贪心地尝试将图中最小的非树边标记为树边,非法则跳过。

按上述算法生成的路径中消耗相加即为最小消耗。

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath> 
using namespace std;
const int maxn = 3e2+10;
const int maxm = 1e6+10;
#define ll long long
int W[maxn],P[maxn][maxn];
int n;
struct edge
{
	int u,v,w;
	bool operator<(const edge &p)const
	{
		return w < p.w;
	}
}e[maxm];
int par[maxm],rnk[maxm];
void init()
{
	for(int i = 0; i <= n; i++)
	{
		par[i] = i;
		rnk[i] = 1;
	}
}
int find(int x)
{
	return par[x] == x ? x : par[x] = find(par[x]);
}
bool unite(int x,int y)
{
	x = find(x); y = find(y);
	if(x == y) return false;
	if(rnk[x] < rnk[y])
	{
		par[x] = y; 
		rnk[y] += rnk[x];
	}
	else
	{
		par[y] = x;
		rnk[x] += rnk[y];
	}

	return true;
}

int main()
{
	ll k = 0;
	scanf("%d",&n);
	init();
	for(int i = 1; i <= n; i++)
	{
		int skywater;
		scanf("%d",&skywater);
		e[k].u = 0;
		e[k].v = i;
		e[k].w = skywater;
		k++;
	}
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++)
		{
			int cost;
			scanf("%d",&cost);
			if(cost == 0) continue;
			e[k].u = i;
			e[k].v = j;
			e[k].w = cost;
			k++;
		}
	sort(e,e+k);
	ll ans = 0;
	for(int i = 0; i < k; i++)
	{
		int u = e[i].u;
		int v = e[i].v;
		int w = e[i].w;
		if(unite(u,v))
			ans += w;
	}
	printf("%lld",ans);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值