Educational Codeforces Round 69 (Rated for Div. 2) D Yet Another Subarray Problem

官方题解

At first let's solve this problem when m = 1 and k = 0 (it is the problem of finding subarray with maximum sum). For each position from 1 to n we want to know the value of m a x l i = max 1 j i + 1 s u m ( j , i ) , where s u m ( l , r ) = k = l k r a k , and s u m ( x + 1 , x ) = 0 .

We will calculate it the following way. m a x l i will be the maximum of two values:

  • 0 (because we can take segments of length 0 );
  • a i + m a x l i 1 .

The maximum sum of some subarray is equal to max 1 i n m a x l i .

So, now we can calculate the values of b e s t i = max 0 l e n , i l e n m 0 ( s u m ( i l e n m + 1 , i ) l e n k ) the same way.

b e s t i is the maximum of two values:

  • 0;
  • s u m ( i m + 1 , i ) k + b e s t i m .

After calculating all values b e s t i we can easily solve this problem. At first, let's iterate over the elements b e s t i . When we fix some element b e s t i , lets iterate over the value l e n = 1 , 2 , , m and update the answer with value b e s t i + s u m ( i l e n , i 1 ) k .

源代码

#include<stdio.h>
#include<algorithm>

int n,m,k;
long long a[300010];
long long dp[300010],ans;
int main()
{
    //freopen("test.in","r",stdin);
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=n;i++) scanf("%lld",a+i),a[i]+=a[i-1];
    for(int i=1;i<=n;i++)
    {
        for(int j=i;j+m>=i;j--)
            dp[i]=std::max(dp[i],a[i]-a[j]);
        dp[i]-=k;
        dp[i]=std::max(0LL,dp[i]);
        if(i>m) dp[i]=std::max(dp[i],dp[i-m]+a[i]-a[i-m]-k);
        ans=std::max(dp[i],ans);
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wawcac-blog/p/11237295.html