• Poj 2479 Maximum sum


    Maximum sum
    Time Limit: 1000MS Memory Limit: 65536K
    Total Submissions: 39500 Accepted: 12340
    Description
    Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:
    Your task is to calculate d(A).
    Input
    The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
    Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, …, an. (|ai| <= 10000).There is an empty line after each case.
    Output
    Print exactly one line for each test case. The line should contain the integer d(A).
    Sample Input
    1
    10
    1 -1 2 2 3 -3 4 -4 5 -5
    Sample Output
    13
    Hint
    In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
    Huge input,scanf is recommended.
    Source
    POJ Contest,Author:Mathematica@ZSU

    /*
    题意:给一段序列,将这个序列分成两部分,使两部分的最大子段和的和最大.
    o(n)维护最大前缀/后缀和.
    枚举断点将两端和加起来即可.
    正确性显然.
    */
    #include<iostream>
    #include<cstdio>
    #define MAXN 50001
    using namespace std;
    int f[MAXN],n,s[MAXN],w[MAXN],w2[MAXN],ans;
    int read()
    {
        int x=0,f=1;char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
        return x*f;
    }
    void slove()
    {
        f[1]=s[1];w[1]=s[1];
        for(int i=2;i<=n;i++)
        {
            if(f[i-1]>=0) f[i]=f[i-1]+s[i];
            else f[i]=s[i];
            w[i]=max(w[i-1],f[i]);
        }
        f[n]=s[n];w2[n]=s[n];
        for(int i=n-1;i>=1;i--)
        {
            if(f[i+1]>=0) f[i]=f[i+1]+s[i];
            else f[i]=s[i];
            w2[i]=max(w2[i+1],f[i]);
        }
        for(int i=1;i<=n-1;i++)
          ans=max(ans,w[i]+w2[i+1]);
        printf("%d
    ",ans);
        return ;
    }
    int main()
    {
        int t;
        t=read();
        while(t--)
        {
            n=read();ans=-1e9;
            for(int i=1;i<=n;i++)
              s[i]=read();
            slove();
        }
        return 0;
    }
  • 相关阅读:
    CCF CSP 201709-1 打酱油 (贪心)
    CCF CSP 201712-1 最小差值
    CCF CSP 201612-1 中间数
    CCF CSP 201609-1 最大波动
    CCF CSP 201604-1 折点计数
    CCF CSP 201512-1 数位之和
    CCF CSP 201509-1 数列分段
    CCF CSP 201503-1 图像旋转 (降维)
    CCF CSP 201412-1 门禁系统
    CCF CSP 201409-1 相邻数对
  • 原文地址:https://www.cnblogs.com/nancheng58/p/10068175.html
Copyright © 2020-2023  润新知