题目链接:传送门
Partial Sum
Bobo has a integer sequence a1,a2,…,an of length n . Each time, he selects two ends 0≤l<r≤n and add |∑rj=l+1aj|−C 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.
Input
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 .
Output
For each test cases, output an integer which denotes the maximum.
Sample Input
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
Sample Output
3 4 2 0
解题思路:前缀和排序
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <set>
#include <string>
#include <stack>
#include <algorithm>
#include <map>
using namespace std;
typedef __int64 ll;
const int N = 100100;
const int M = 20;
const int mod = 1e9+7;
const int INF = 0x3fffffff;
ll sum[N];
int main()
{
int n,m; ll c,a;
while( ~scanf("%d%d%I64d",&n,&m,&c) ){
memset( sum , 0 , sizeof(sum) );
sum[0] = 0;
for( int i = 1 ; i <= n ; ++i ){
scanf("%I64d",&a);
sum[i] += sum[i-1]+a;
}
sort( sum , sum+n+1 );
ll ans = 0;
for( int i = 0 ; i < m ; ++i ){
if( (sum[n-i]-sum[i]) <= c ) break;
ans += (sum[n-i]-sum[i])-c;
}
printf("%I64d\n",ans);
}
return 0;
}