P2627 mowing grass (monotone queue optimization DP)

Topic Link

Solution

70 Very simple DP, the complexity O (NK).
Equation is as follows:
\ [F [I] [. 1] = max (F [J] [0] + SUM [I] -sum [J]) \] \ [F [I] [0] = max (F [I -1] [1], f [
i-1] [0]) \] then you must consider optimization, it is clear that the queue can be used to optimize the monotonous.
Maintain current \ (I \) before \ (K \) th point \ (f [j] [0 ] \) a \ (max \) values can be transferred.
Complexity of O (N).

Code

#include<bits/stdc++.h>
#define N 100008
#define ll long long
using namespace std;

ll n,k,c[N];
ll f[N][2],sum[N];
int main()
{
    scanf("%lld%lld",&n,&k);
    for(int i=1;i<=n;i++)
        scanf("%lld",&c[i]),sum[i]=sum[i-1]+c[i];
    ll head=1,tail=1,a[N];
    a[1]=0;
    for(int i=1;i<=n;i++)
    {
        f[i][1]=f[a[head]][0]+sum[i]-sum[a[head]];
        f[i][0]=max(f[i-1][1],f[i-1][0]);
        while(1)
            if(f[i][0]>=f[a[tail]][0]+sum[i]-sum[a[tail]]&&tail>=head)
                {tail--;}
            else break;
        a[++tail]=i;
        while(1)
            if(a[head]<i+1-k)head++;
            else break;
        if(tail<head)tail=head;
    }cout<<max(f[n][0],f[n][1])<<endl;
}
/*
7 2
1 7 8 4 5 9 10
Ans: 34
*/

Guess you like

Origin www.cnblogs.com/Kv-Stalin/p/11210770.html