Educational Codeforces Round 69 (Rated for Div. 2) D. Yet Another Subarray Problem 背包dp
Posted qscqesze
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Educational Codeforces Round 69 (Rated for Div. 2) D. Yet Another Subarray Problem 背包dp相关的知识,希望对你有一定的参考价值。
D. Yet Another Subarray Problem
You are given an array \(a_1, a_2, \dots , a_n\) and two integers \(m\) and \(k\).
You can choose some subarray \(a_l, a_l+1, \dots, a_r-1, a_r\).
The cost of subarray \(a_l, a_l+1, \dots, a_r-1, a_r\) is equal to \(\sum\limits_i=l^r a_i - k \lceil \fracr - l + 1m \rceil\), where \(\lceil x \rceil\) 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:
\(a_3 \dots a_3: 15 - k \lceil \frac13 \rceil = 15 - 10 = 5\);
\(a_3 \dots a_4: (15 - 3) - k \lceil \frac23 \rceil = 12 - 10 = 2\);
\(a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac33 \rceil = 16 - 10 = 6\);
\(a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac43 \rceil = 24 - 20 = 4\);
\(a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac53 \rceil = 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 \le n \le 3 \cdot 10^5, 1 \le m \le 10, 1 \le k \le 10^9\)).
The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 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的序列,然后你需要找到一个代价最大的子序列。子序列的代价是该序列的\(\sum\limits_i=l^r a_i - k \lceil \fracr - l + 1m \rceil\)
题解
实际上就是背包dp,dp[i][j]表示装第i个物品的时候,此时物品的数量%m的余数为j的最大值。背包dp转移就可以。
代码
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
const int maxn = 3*100000+7;
long long dp[maxn][11];
int a[maxn];
int main()
long long ans = 0;
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<=n;i++)
for(int j=0;j<=m;j++)
dp[i][j]=-1e9;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
dp[i][1%m]=a[i]-k;
ans=max(ans,dp[i][1%m]);
for(int i=1;i<=n;i++)
for(int j=0;j<=m;j++)
int pre = (j-1+m)%m;
if (pre == 0)
dp[i][j]=max(dp[i][j],dp[i-1][pre]+a[i]-k);
else
dp[i][j]=max(dp[i][j],dp[i-1][pre]+a[i]);
ans=max(ans,dp[i][j]);
printf("%lld\n",ans);
以上是关于Educational Codeforces Round 69 (Rated for Div. 2) D. Yet Another Subarray Problem 背包dp的主要内容,如果未能解决你的问题,请参考以下文章
Educational Codeforces Round 7 A
Educational Codeforces Round 7
Educational Codeforces Round 90
Educational Codeforces Round 33