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

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

Code:

#include 
#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;
}

你可能感兴趣的:(题解,LuoGu,贪心,题解,LuoGu,贪心)