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 and (it is the problem of finding subarray with maximum sum). For each position from to we want to know the value of , where , and .
We will calculate it the following way. will be the maximum of two values:
- (because we can take segments of length );
- .
The maximum sum of some subarray is equal to .
So, now we can calculate the values of the same way.
is the maximum of two values:
- 0;
- .
After calculating all values we can easily solve this problem. At first, let's iterate over the elements . When we fix some element , lets iterate over the value and update the answer with value .
源代码
#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;
}