洛谷 P1792 [國家集訓隊]種樹

題目傳送門

另一道題差不多,本題只需把鏈變成環即可.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>

using namespace std;

long long n,m,l[200001],r[200001],ans,c[200001];
bool vis[200001];
struct kkk {
	long long id,v;
	bool operator <(const kkk &a) const {
		return v < a.v;
	}
};
priority_queue<kkk> q;

inline long long mx() {
	long long s = 0,w = 1;
	char ch = getchar();
	while(ch < '0' || ch > '9') {
		if(ch == '-') w = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9') {
		s = s * 10 + (ch - '0');
		ch = getchar();
	}
	return s * w;
}

int main() {
	n = mx();
	m = mx();
	if(m * 2 > n) {
		printf("Error!");
		return 0;
	}
	for(int i = 1;i <= n; i++) {
		kkk e;
		c[i] = mx();
		e.v = c[i];
		e.id = i;
		l[i] = i - 1;
		r[i] = i + 1;
		if(i == 1) l[i] = n;
		if(i == n) r[i] = 1;
		q.push(e);
	}
	for(int i = 1;i <= m; i++) {
		kkk o = q.top();
		q.pop();
		if(vis[o.id]) {
			i--;
			continue;
		}
		ans += o.v;
		vis[l[o.id]] = vis[r[o.id]] = 1;
		c[o.id] = c[l[o.id]] + c[r[o.id]] - c[o.id];
		o.v = c[o.id];
		l[o.id] = l[l[o.id]];
		r[o.id] = r[r[o.id]];
		l[r[o.id]] = o.id;
		r[l[o.id]] = o.id;
		q.push(o);
	}
	printf("%lld",ans);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章