2017-5-14 湘潭市賽 Partial Sum 給n個數,每次操作選擇一個L,一個R,表示區間左右端點,該操作產生的貢獻為[L+1,R]的和的絕對值-C。 0<=L


Partial Sum
Accepted : 30           Submit : 119
Time Limit : 3000 MS           Memory Limit : 65536 KB

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


Source
XTU OnlineJudge 

/**
題目:Partial Sum
鏈接:http://202.197.224.59/OnlineJudge2/index.php/Problem/read/id/1264
題意:給n個數,每次操作選擇一個L,一個R,表示區間左右端點,該操作產生的貢獻為[L+1,R]的和的絕對值-C。
0<=L<R<=n; 如果選過L,R這兩個位置,那么以后選擇的L,R都不可以再選擇這兩個位置。最多操作m次,求可以獲得的
最大貢獻和。
思路:腦洞。原公式可以轉化為|sum[r]-sum[l]|-c,sum[i]表示前i項的前綴和。
由於絕對值的影響,所以對前綴和排序,然后l從左邊開始遞增枚舉,r從右邊開始遞減枚舉,每次組成一對(sum[l],sum[r])作為貢獻計算。


*/

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
const int maxn = 1e5+100;
int a[maxn], sum[maxn];
int main()
{
    int n, m, c;
    while(scanf("%d%d%d",&n,&m,&c)!=EOF)
    {
        //cout<<"yes"<<endl;
        for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
        sum[0] = 0;
        for(int i = 1; i <= n; i++){
            sum[i] = a[i]+sum[i-1];
        }
        sort(sum,sum+1+n);
        int l = 0, r = n;
        LL ans = 0;
        while(m--){
            int value = abs(sum[r]-sum[l]);
            if(value<=c) break;
            ans += value-c;
            l++, r--;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM