2017 江苏省赛 Partial Sum

来源:互联网 发布:淘宝店铺旺铺专业版 编辑:程序博客网 时间:2024/03/28 17:27

题目描述

Bobo has a integer sequence a1,a2,…,an of length n. Each time, he selects two ends 0≤l < r≤n and add into a counter which is zero initially. He repeats the selection for at most m times.

If each end can be selected at most once (either as left or right), find out the maximum sum Bobo may have.

输入

The input contains zero or more test cases and is terminated by end-of-file. For each test case:
The first line contains three integers n, m, C. The second line contains n integers a1,a2,…,an.
2≤n≤105,1≤2m≤n+1,|ai|,C≤104
The sum of n does not exceed 106.

输出

For each test cases, output an integer which denotes the maximum.

样例输入

4 1 1
-1 2 2 -1
4 2 1
-1 2 2 -1
4 2 2
-1 2 2 -1
4 2 10
-1 2 2 -1

样例输出

3
4
2
0


题意

就是说,给一个序列,长度为n,可以从序列中最多取m次,每次取一个线段,每次选择一个起始位置l,终止位置r,没跟线段的区间是[l+1,r]但是每个点只能被选择一次(不论是作为起点还是作为终点)。每次将线段的和的绝对值减去C以后存到答案ans中,ans的初值是0。
问:最终可以得到的ans的最大值是多少。


思路

存到数组里,求出这个序列的前缀和,然后按照前缀和从小到大的顺序排序。
(这样可以有效避免把一个点取多次作为起点或者重点的情况。)
(例如:当n=3时前缀和有四个值,因为区间是从l+1开始的所以第一个0也在前缀和的范围内。)
再从最大减去最小,如果大于零就存到ans中,如果小于等于零可以直接break出循环,因为当前的值是取完比它大的所有的值,如果当前值小于等于零,那么它以后的值都小于等于零。所以这样可以在时间上对代码进行优化。(该题时间限制是5000ms所以就算不加这个优化也可以过。)
最最最最最最最最最最最坑的是这个体看上去数据范围不会超过int的范围,但实际上,你要是这么天真那你就错了,这个就是我贡献了7发WA的原因。当着道题过了的时候,我的内心是绝望的。
下面上代码。


代码

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <math.h>#define mem(a) memset(a,0,sizeof(a))#define L(u) (u<<1)#define R(u) (u<<1|1)using namespace std;int main (){    long long  a[100005];    int n,m,c;    long long ans;    while(cin>>n>>m>>c)    {        ans=0;        mem(a);        for(int i=1; i<=n; ++i)            cin>>a[i];        for(int i=2; i<=n; ++i)            a[i]+=a[i-1];        sort(a,a+n+1);        for(int i=0; i<(n+1)/2; ++i)        {            ans+=max(0ll,abs(-1*a[i]+a[n-i])-c);            if(abs(-1*a[i]+a[n-i])-c>0)                m--;            else                 break;            if(!m)                break;        }        //这个for循环的限制条件一定要写(n+1)/2而且不带等号。或者加个if语句判断break也可以。        //题目数据,当n=5时,m最大可以取到3,但是实际上并不能取三次,所以在这里也要限制一下。        cout<<ans<<endl;    }    return 0;}