Partial Sum
Partial Sum |
||
Accepted : 80 | Submit : 353 | |
Time Limit : 3000 MS | Memory Limit : 65536 KB |
Partial SumBobo 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. InputThe 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 .
OutputFor each test cases, output an integer which denotes the maximum. Sample Input4 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 Output3 4 2 0 |
//题意,最多选 m 次区间的和的绝对值 - c 的值,要求和最大,且所有点最多选一次作为端点
//贪心题,只要把前缀和排序,每次选最大的,最小的,直到选出值为负数,或等于m次,即停止
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 using namespace std; 6 #define MX 100005 7 #define LL long long 8 9 int n,m,c; 10 int num[MX]; 11 LL sum[MX]; 12 13 int main() 14 { 15 while(~scanf("%d%d%d",&n,&m,&c)) 16 { 17 sum[0]=0; 18 for (int i=1;i<=n;i++) 19 { 20 scanf("%d",&num[i]); 21 sum[i]=sum[i-1]+num[i]; 22 } 23 sort(sum,sum+1+n); 24 int l = 0 ,r = n; 25 LL ans = 0; 26 27 while (l<m&&sum[r]-sum[l]>c) 28 { 29 ans+=abs(sum[r]-sum[l])-c; 30 l++,r--; 31 } 32 printf("%I64d\n",ans); 33 } 34 return 0; 35 }