zoukankan      html  css  js  c++  java
  • codeforces 797B

    B. Odd sum

    time limit per test
    1 second
    memory limit per test
    256 megabytes
    input
    standard input
    output
    standard output

    You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.

    Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

    You should write a program which finds sum of the best subsequence.

    Input

    The first line contains integer number n (1 ≤ n ≤ 105).

    The second line contains n integer numbers a1, a2, ..., an ( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence with odd sum.

    Output

    Print sum of resulting subseqeuence.

    Examples
    input
    4
    -2 2 -3 1
    output
    3
    input
    3
    2 -5 -3
    output
    -1
    Note

    In the first example sum of the second and the fourth elements is 3.

     解题思路:

    题意为求最大的和为奇数的子序列

    那么先将所有正数加起来,如果和是奇数那就是最大的奇数和,如果是偶数的话,就要把它变为奇数

    有两种情况:

    1.减去最小的正奇数

    2.加上最大的负奇数

    最后判断一下两种情况的大小,取较大值

    实现代码:

    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        int m,a[100005],b[100005],c[100005];
        int i;
        cin>>m;
        int k = 0,l= 0;
        for(i=0;i<m;i++)
        {
            cin>>a[i];
            if(a[i]>0)
                b[k++] = a[i];
            else
                c[l++] = a[i];
        }
        sort(b,b+k);
        int sum = 0;
        for(i=k-1;i>=0;i--)
        {
            sum += b[i];
        }
        if(sum%2==0)
        {
            int sum1=sum,sum2=sum;
            sum = -99999999;
            for(i=0;i<k;i++)
            {
                if(b[i]%2==1)
                sum1-=b[i];
                if(abs(sum1)%2==1){
                    sum = sum1;
                    break;
                }
                   }
                //cout<<"sum1:"<<sum1<<endl;
            sort(c,c+l);
            for(i=l-1;i>=0;i--){
                if(abs(c[i])%2==1)
                    sum2+=c[i];
                if(abs(sum2)%2==1){
                    sum = max(sum,sum2);
                }
            }
             //cout<<"sum2:"<<sum2<<endl;
        }
        cout<<sum<<endl;
    }
  • 相关阅读:
    thinkPHP5.0 获取域名
    tp5 composer在packagist引入验证码
    使用build.php快速搭建前后台
    __construct()和__initialize()
    mysql 如何给SQL添加索引
    mysql如何查看SQL语句的执行时间
    thinkPHP自带的图片批量打包扩展ZipArchive
    sizeof和strlen
    Uboot中汇编指令
    Uboot代码分析
  • 原文地址:https://www.cnblogs.com/kls123/p/6817299.html
Copyright © 2011-2022 走看看