AtCoder Grand Contest 008: Contiguous Repainting(思维)

Contiguous Repainting

时间限制: 2 Sec  内存限制: 256 MB
提交: 69  解决: 22
[提交][状态][讨论版][命题人:admin]

题目描述

There are N squares aligned in a row. The i-th square from the left contains an integer ai.

Initially, all the squares are white. Snuke will perform the following operation some number of times:

Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares are overwritten.
After Snuke finishes performing the operation, the score will be calculated as the sum of the integers contained in the black squares. Find the maximum possible score.

Constraints
1≤N≤105
1≤K≤N
ai is an integer.
|ai|≤109

输入

The input is given from Standard Input in the following format:

N K
a1 a2 … aN

输出

Print the maximum possible score.

样例输入

5 3

-10 10 -10 10 -10

样例输出

10

提示

Paint the following squares black: the second, third and fourth squares from the left.

来源


[题意]

    选择K 连续 涂颜色,可以重复涂,每次可以涂白或者黑,问 操作玩完后黑色快的总和最大是多少;

[思路]

    可以发现,经过nk次操作后最后一次k范围是不可以控的,K外面,是可以将负数涂成白色,只保留正数黑色;

    两次前缀和, 跑连续的k 移动, 取最大, 类似咸鱼翻身那道题

【code】

#include <iostream>
#include <bits/stdc++.h>

typedef long long ll;

const int MAXN=1e5+5;
typedef long long ll;
const int INF = 0x3f3f3f3f;
using namespace std;

ll a[MAXN];
ll sum[MAXN];
ll sum_int[MAXN];
int main()
{
    int n,k;
    cin>>n>>k;
    memset(sum,0,sizeof(sum));
    memset(sum_int,0,sizeof(sum_int));
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=sum[i-1]+a[i];
        if(a[i]>0) sum_int[i]=sum_int[i-1]+a[i];
        else sum_int[i]=sum_int[i-1];
    }
    ll ans=-INF;
    for(int i=1;i<=(n-k+1);i++)
    {
        ll res=0;
        int j=i+k-1;
        if( sum[j]-sum[i-1] >0) res+= sum[j]-sum[i-1];
        res+= sum_int[i-1]-sum[0];
        res+= sum_int[n]-sum_int[j];
        ans=max(ans,res);
    }
    cout<<ans<<endl;
	return 0;
}

123

posted @ 2018-04-18 12:38  Sizaif  阅读(233)  评论(0编辑  收藏  举报