洛谷 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;
} 
posted @ 2020-11-05 23:04  Mr^Simon  阅读(80)  评论(0编辑  收藏  举报