【模拟赛】【最小生成树】2021.8.10.B

题目描述

最小生成树模板
即使不只派出一个通讯员,也可以全部点连向0号点处理

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long 
using namespace std;

struct wh_
{
	ll w, h, k;
}wh[1000250];

ll t, n, k, tot, l, sum;
ll Fa[2005];

void hw(ll x, ll y, ll z)
{wh[++t] = (wh_) {x, y, z};}

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

ll find(ll k)
{
	if(k != Fa[k])return Fa[k] = find(Fa[k]);
	else return k;
}

ll read()
{
	ll x = 0, r = 1; char c = getchar();
	while(c < '0' || c > '9'){if(c == '-')r = -1;c = getchar();}
	while('0' <= c && c <= '9')x = x * 10 + c - 48, c = getchar();
	return x * r;
}


int main()
{
	n = read();
	for(ll i = 1; i <= n; ++i)
		for(ll j = 1; j <= n; ++j)
		{
			k = read();
			if(i > j)hw(i, j, k);
		}
	for(ll i = 1; i <= n; ++i)
	{
		k = read();
		hw(0, i, k), Fa[i] = i;
	}
	tot = 0, l = 0;
	sort(wh + 1, wh + t + 1, nm);
	while(tot < n && ++l)
	{
		ll x = wh[l].w, y = wh[l].h;
		ll xx = find(x);
		ll yy = find(y);
		if(xx == yy)continue;
		Fa[max(xx, yy)] = min(xx, yy);
		tot++, sum += wh[l].k;
	}
	printf("%lld", sum);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值