【题解】LuoGu1792:[国家集训队]种树

本文探讨了在一个环形结构中应用贪心算法解决特定问题的实现细节。通过定义节点和堆结构,利用优先队列进行操作,实现了对环形链表的高效处理。在每次迭代中选择当前价值最大的节点进行合并,直至达到预定的合并次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题传送门
在这道题的基础上变成了一个环

Code:

#include <bits/stdc++.h>
#define maxn 500010
#define LL long long
using namespace std;
struct heap{
	int num;
	LL val;
	bool operator < (const heap &x) const{return x.val > val;}
};
priority_queue <heap> q;
struct node{
	int l, r;
	LL val;
}a[maxn];
int n, m, vis[maxn];

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

int main(){
	n = read(), m = read();
	if (m > (n >> 1)) return puts("Error!"), 0;
	for (int i = 1; i <= n; ++i){
		a[i].val = read(), a[i].l = i - 1, a[i].r = i + 1;
		q.push((heap){i, a[i].val});
	}
	a[1].l = n, a[n].r = 1;
	LL ans = 0;
	while (!q.empty()){
		heap tmp = q.top(); q.pop();
		int x = tmp.num;
		if (vis[x]) continue;
		ans += tmp.val, --m;
		if (!m) break;
		a[x].val = a[a[x].l].val + a[a[x].r].val -  a[x].val;
		vis[a[x].l] = vis[a[x].r] = 1;
		q.push((heap){x, a[x].val});
		a[x].l = a[a[x].l].l, a[x].r = a[a[x].r].r;
		a[a[x].l].r = x, a[a[x].r].l = x;
	}
	printf("%lld\n", ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值