【题解】LuoGu1484:种树

原题传送门
如果是 O ( n 2 ) D P O(n^2)DP O(n2)DP,直接 d p i , j = m a x ( d p i − 1 , j , d p i − 2 , j − 1 + a i ) dp_{i,j}=max(dp_{i-1,j},dp_{i-2,j-1}+a_i) dpi,j=max(dpi1,j,dpi2,j1+ai)
但是不行,所以可以反悔贪心
所以跟这道题目差不多

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();
	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[0].val = a[n + 1].val = -1e9;
	LL ans = 0, sum = 0;
	while (m--){
		while (vis[q.top().num]) q.pop();
		heap tmp = q.top(); q.pop();
		ans = max(ans, sum += tmp.val);
		int x = tmp.num;
		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,贪心)