【codeforces - 1197D】- Yet Another Subarray Problem (dp)

题目链接 

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 \sum_{i = l}^{r}a_{i} - k\left \lceil \frac{r - l +1}{m} \right \rceil, 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⌈1/3⌉=15−10=5;
  • a3…a4:(15−3)−k⌈2/3⌉=12−10=2;
  • a3…a5:(15−3+4)−k⌈3/3⌉=16−10=6;
  • a3…a6:(15−3+4+8)−k⌈4/3⌉=24−20=4;
  • a3…a7:(15−3+4+8+3)−k⌈5/3⌉=27−20=7.

Your task is to find the maximum cost of some subarray (possibly empty) of array aa.

Input

The first line contains three integers n, m, and k (1≤n≤3\cdot 10^5,1≤m≤10,1≤k≤10^9).

The second line contains n integers a1,a2,…,an (-10^9\leqslant a_{i} \leqslant 10^9).

Output

Print the maximum cost of some subarray of array a.

Examples

input

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

output

7

input

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

output

0

题目大意:

给一个大小为n的数组,给定m, k,计算子序列的\sum_{i = l}^{r}a_{i} - k\left \lceil \frac{r - l +1}{m} \right \rceil的最大值。

官方题解

题目分析:

这题我一开始想要通过修改最大子列和的在线处理算法来写这题,样例都过但是第三个测试数据wa了,我原来觉得这样写肯定没错的,后来补题时发现想法是错的,因为在线处理是把没用的一段直接丢掉,但是这题里的r - l + 1会对结果产生影响,可能只丢掉一小段,结果会更大,直接打表前缀和暴力枚举亲测超时,由于子序列的长度会对值产生影响,所以我们用dp来枚举每种情况,对于每个元素都有m种状态,当前元素在不同状态对后面的影响是不同的,所以我们可以开一个n* m大小的dp数组dp[i][j],代表第i个元素,在长度对m取模后的j位置时的最大值。

状态转移方程为

(j == 1)dp[i][j] = max(a[i] - k, dp[i - 1][m] + a[i] - k);

(j > 1)dp[i][j] = dp[i - 1][j - 1] + a[i];

AC代码:

#include 
#include 
using namespace std;
typedef long long ll;
const int N = 3e5 + 5;
ll a[N];
//ll sum[N];
ll dp[N][20];
int main()
{
    int n, m, k;
    cin >> n >> m >> k;
    a[0] = 0;
    for (int i = 1; i <= m; i ++)dp[0][i] = -1e10;
    ll ans = 0;
    for (int i = 1; i <= n; i ++){
        scanf("%lld", &a[i]);
        for (int j = 1; j <= m; j ++){
            if (j == 1)dp[i][j] = max(a[i] - k, dp[i - 1][m] + a[i] - k);
            else dp[i][j] = dp[i - 1][j - 1] + a[i];
            ans = max(ans, dp[i][j]);
        }
    }
    printf("%lld\n", ans);
 
    return 0;
}

 

你可能感兴趣的:(【codeforces - 1197D】- Yet Another Subarray Problem (dp))