AcWing 1087. 修剪草坪 (单调队列优化dp)

2021-03-04 10:20:31 浏览数 (1)

思路:

代码:

代码语言:javascript复制
#include<bits/stdc  .h>
using namespace std;
#define int long long
const int N=1e5 10;
int n,k,a[N],f[N];
int get(int x){
    if(x==0)return 0;
    return f[x-1]-a[x];
}
signed main(){
    cin>>n>>k;
    for(int i=1;i<=n;i  )cin>>a[i],a[i] =a[i-1];
    deque<int>q;
    q.push_front(0);

    for(int i=1;i<=n;i  ){
        if(!q.empty()&&i-q.front()>k)q.pop_front();
        f[i]=max(f[i-1],a[i] get(q.front()));
        while(!q.empty()&&get(q.back())<=get(i))q.pop_back();        
        q.push_back(i);
    }
    cout<<f[n]<<endl;
}
dp

0 人点赞