CodeForces 1197D Yet Another Subarray Problem

Time limit 2000 ms

Memory limit 262144 kB

Source Educational Codeforces Round 69 (Rated for Div. 2)

Tags dp greedy math *1900

Editorial Announcement (en) Tutorial #1 (en) Tutorial #2 (en) Tutorial #3 (ru)

官方题解

At first let's solve this problem when m=1m=1 and k=0k=0 (it is the problem of finding subarray with maximum sum). For each position from 11 to nn we want to know the value of maxli=max1ji+1sum(j,i)maxli=max1≤j≤i+1sum(j,i), where sum(l,r)=k=lkraksum(l,r)=∑k=lk≤rak, and sum(x+1,x)=0sum(x+1,x)=0.

We will calculate it the following way. maxlimaxli will be the maximum of two values:

  • 00 (because we can take segments of length 00);
  • ai+maxli1ai+maxli−1.

The maximum sum of some subarray is equal to max1inmaxlimax1≤i≤nmaxli.

So, now we can calculate the values of besti=max0len,ilenm0(sum(ilenm+1,i)lenk)besti=max0≤len,i−len⋅m≥0(sum(i−len⋅m+1,i)−len∗k) the same way.

bestibesti is the maximum of two values:

  • 0;
  • sum(im+1,i)k+bestimsum(i−m+1,i)−k+besti−m.

After calculating all values bestibesti we can easily solve this problem. At first, let's iterate over the elements bestibesti. When we fix some element bestibesti, lets iterate over the value len=1,2,,mlen=1,2,…,m and update the answer with value besti+sum(ilen,i1)kbesti+sum(i−len,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;
}

转载于:https://www.cnblogs.com/wawcac-blog/p/11237295.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值