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

D. Yet Another Subarray Problem

传送门

You are given an array a1,a2,…,an and two integers m and k.
You can choose some subarray al,al+1,…,ar−1,ar.

The cost of subarray al,al+1,…,ar−1,ar is equal to ∑ i = l r \sum_{i=l}^r i=lr a i a_i ai−k⌈ r + l − 1 m \frac{r+l-1}{m} mr+l1⌉, where ⌈x⌉ is the least integer greater than or equal to x.

The cost of empty subarray is equal to zero.

For example, if m=3, k=10 and a=[2,−4,15,−3,4,8,3], then the cost of some subarrays are:

a3…a3:15−k⌈13⌉=15−10=5;
a3…a4:(15−3)−k⌈23⌉=12−10=2;
a3…a5:(15−3+4)−k⌈33⌉=16−10=6;
a3…a6:(15−3+4+8)−k⌈43⌉=24−20=4;
a3…a7:(15−3+4+8+3)−k⌈53⌉=27−20=7.
Your task is to find the maximum cost of some subarray (possibly empty) of array a.

Input

The first line contains three integers n, m, and k ( 1 ≤ n ≤ 3 ⋅ 1 0 5 , 1 ≤ m ≤ 10 , 1 ≤ k ≤ 1 0 9 ) (1≤n≤3⋅10^5,1≤m≤10,1≤k≤10^9) (1n3105,1m10,1k109).

The second line contains n integers a1,a2,…,an ( − 1 0 9 ≤ a i ≤ 1 0 9 −10^9≤ai≤10^9 109ai109).

Output

Print the maximum cost of some subarray of array a.

Examples
input

7 3 10
2 -4 15 -3 4 8 3

outpu

7

input

5 2 1000
-13 -4 -9 -20 -11

output

0

题目大意:

在数组里找到连续的序列使得 ∑ i = l r \sum_{i=l}^r i=lr a i a_i ai−k⌈ r + l − 1 m \frac{r+l-1}{m} mr+l1⌉取得最大值。

思路:

仔细看公式,发现是区间的宽度/m(向上取整)
说明每m个宽度,k就要加一。ans就要减多一个k。

由于m*n不大,可以考虑二维dp。
这道题一共就两种状态
到达这个点时在选中序列里恰好第m个,和不是第m个。
所以我们可以建一个二维数组:
dp[i][j] dp第一个是第几个数,第二个是构成m中第几个

状态转移方程:

当j==0时:

  • 有可能是从j=m-1过来的,dp[i][j]=dp[i-1][m-1]+a[i]-k
  • 有可能是第一个开始的,dp[i][j]=a[i]-k
    (因为是同种状态,所以上面两个应取最大值。)

当j!=0时:

  • 一定时从从j=m-1过来的,dp[i][j]=dp[i-1][j-1]+a[i];

最大值可能在中间任意一步,所以每到一个数计算一次最大值即是结果。

代码:
#include <bits/stdc++.h>
using namespace std;
 
long long n,m,k,ans,a[300005],dp[300005][12]; //DP第一个是第几个数,第二个是构成m中第几个
 
int main() {
	cin>>n>>m>>k;
	for (int i=1;i<=n;i++){
		cin>>a[i];
		for(int j=0;j<m && i-j>0;j++) {   //i-j>0是因为i一定要大于j
			if (j==0) dp[i][j]=max(a[i]-k,dp[i-1][m-1]+a[i]-k); //当j为0时,可能是之前的累加,或者自己重新开始
			else dp[i][j]=dp[i-1][j-1]+a[i]; //当j不为0时,只能是之前的累加
			ans=max(ans,dp[i][j]);    //每次计算一下最大值
		}
	}
	cout<<ans<<endl;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值