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;
}
标签:1087,修剪,const,int,sum,maxn,include,dp 来源: https://blog.csdn.net/weixin_45714726/article/details/115586376