D. Yet Another Subarray Problem

添加链接描述

D. Yet Another Subarray Problem
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a1,a2,…,ana1,a2,…,an and two integers mm and kk.

You can choose some subarray al,al+1,…,ar−1,aral,al+1,…,ar−1,ar.

The cost of subarray al,al+1,…,ar−1,aral,al+1,…,ar−1,ar is equal to ∑i=lrai−k⌈r−l+1m⌉∑i=lrai−k⌈r−l+1m⌉, where ⌈x⌉⌈x⌉ is the least integer greater than or equal to xx.

The cost of empty subarray is equal to zero.

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

a3…a3:15−k⌈13⌉=15−10=5a3…a3:15−k⌈13⌉=15−10=5;
a3…a4:(15−3)−k⌈23⌉=12−10=2a3…a4:(15−3)−k⌈23⌉=12−10=2;
a3…a5:(15−3+4)−k⌈33⌉=16−10=6a3…a5:(15−3+4)−k⌈33⌉=16−10=6;
a3…a6:(15−3+4+8)−k⌈43⌉=24−20=4a3…a6:(15−3+4+8)−k⌈43⌉=24−20=4;
a3…a7:(15−3+4+8+3)−k⌈53⌉=27−20=7a3…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 aa.

Input
The first line contains three integers nn, mm, and kk (1≤n≤3⋅105,1≤m≤10,1≤k≤1091≤n≤3⋅105,1≤m≤10,1≤k≤109).

The second line contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109).

Output
Print the maximum cost of some subarray of array aa.

Examples
inputCopy
7 3 10
2 -4 15 -3 4 8 3
outputCopy
7
inputCopy
5 2 1000
-13 -4 -9 -20 -11
outputCopy
0

首先只会暴力,毫无疑问超时了。
然后发现用了dp,思路很巧,,反正渣渣一知半解QAQ
对于dp[i][j],表示以i为右端点,长度为%m=j的区间最大值。
每个元素下标%m一共m种情况,所以以i为右端点的区间长度一共m种状态。
i 相同时,区间长度%m相等的区间的归为一种状态。

状态转移方程:j==1时,dp[i][j]=max(dp[i-1][m]+a[i]-k,a[i]-k);
else dp[i][j]=dp[i-1][j-1]+a[i];

/**/
#include
#include
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
const int N=3e5+5;
ll dp[N][20];
ll a[N];
int main()
{
    int i,n,m,j;
    ll k,ans;
    cin>>n>>m>>k;
    for(i=1;i<=m;i++)
    {
        dp[0][i]=-inf;
    }
    ans=0;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
        for(j=1;j<=m;j++)
        {
            if(j==1)
            {
                dp[i][j]=max(a[i]-k,dp[i-1][m]+a[i]-k);//j==1时,以i为右端点,有可能区间长度为1,则dp[i][j]=a[i]-k;
                也有可能区间长度为m+1,dp[i][j]=dp[i-1][m]+a[i]-k。
            }
            else
                dp[i][j]=dp[i-1][j-1]+a[i];//从dp[4][1]开始有两种状态,到dp[5][2]=dp[4][1]+a[5],dp[5][2]也有了两种状态
            ans=max(ans,dp[i][j]);
        }
    }
    cout<

你可能感兴趣的:(动归)