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;
    }
  • 相关阅读:
    MySQL 一致性读 深入研究
    Operating System Error Codes
    5分钟了解MySQL5.7的Online DDL雷区
    pt-osc原理、限制、及与原生online-ddl比较
    学习笔记:Rick's RoTs -- Rules of Thumb for MySQL
    学习笔记:The Best of MySQL Forum
    学习笔记:Analyze MySQL Performance及慢日志的开启
    MySQL: Building the best INDEX for a given SELECT
    学习笔记:ALTERing a Huge MySQL Table
    Google common_schema 2.2 documentation
  • 原文地址:https://www.cnblogs.com/kls123/p/6817299.html
Copyright © 2011-2022 走看看