【最小生成树】P2259 Charmer--viv

我又双叒叕来水博客啦

L i n k Link Link

l u o g u   P 2259 luogu\ P2259 luogu P2259

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

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

5
1 2 3 4 5
4 3 2 1
3 4 5
2 1
5

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

7

H i n t Hint Hint

在这里插入图片描述

S o l u t i o n Solution Solution

t j h tjh tjh大佬的推荐,前来做这道题 (水博客)
结果发现这道题和 K u g l a r z Kuglarz Kuglarz的代码一毛一样,思路也一样,直接放代码吧

C o d e Code Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long

using namespace std;

int n, h, t, x, y, p, f[10001];
ll ans, z;

struct awsl
{
	int to, from;
	ll val;
}w[10000001];

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

bool cmp(awsl a, awsl b)
{return a.val < b.val;}

int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; f[i] = i, ++i)
	for (int j = i; j <= n; ++j)
	{
		scanf("%lld", &z);
		w[++t] = (awsl){i - 1, j, z};
		w[++t] = (awsl){j, i - 1, z};
	}
	sort(w + 1, w + t + 1, cmp);
	h = 1; p = 1;
	while (h <= t && p <= n) {
		x = w[h].to, y = w[h].from, z = w[h].val;
		if (find(x) != find(y)) {//还不在一个连通块
			++p;
			ans += z;//累计答案
			f[find(x)] = find(y);
		}
		++h;
	} 
	printf("%lld", ans);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值