天天看點

1087. 修剪草坪(單調隊列優化dp)

傳送門

dp[i]表示以i為結尾的合法方案的最大值

不如i不選,那麼最大就是dp[i-1].

如果選,那麼就是i-k到i中選一個最大的j (不選 j 的最大值),然後再答案就是dp[j-1]+sum[i]-sum[j]

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
#include<bitset>
#include<unordered_map>
using namespace std;
#define LL long long
#define eps (1e-9)
typedef unsigned long long ull;

const int maxn = 3e5 + 10;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
const int bas = 131;
const LL mod = 1e6 + 3;

LL a[maxn];
LL sum[maxn], q[maxn], dp[maxn];
LL f(int x)
{
	if (x == 0)return 0;
	return dp[x - 1] - sum[x];
}
int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
	{
		scanf("%lld", &a[i]);
		sum[i] = sum[i - 1] + a[i];
	}

	int hh = 0, tt = 0;
	for (int i = 1; i <= n; i++)
	{
		if(i - q[hh] > m)hh++;
		dp[i] = max(dp[i-1], f(q[hh]) + sum[i]);
		while (hh <= tt && f(q[tt]) <= f(i))tt--;
		q[++tt] = i;
	}

	printf("%lld", dp[n]);
	return 0;
}