codeforces/contest/797/problem/B

B. Odd sum
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.

题意:给你n个数,让你从这n个数中选出若干个,使得他们的和为奇数,而且使这个和最大。

解题思路:若干个偶数相加,得到的和一定是偶数,所以我们先把所以的正偶数加起来,然后统计所有正奇数的个数,如果个数为奇数,则把所以正奇数加起来得到的是一个奇数,所以结果是正奇数和与正偶数和之和,若个数是偶数,那么这偶数个奇数加起来的和一定是一个偶数,所以我们要把他变成一个奇数,有两种做法,一是减去一个正奇数,当然为了是最后的和更大,我们减去一个最小的正奇数,或者加上一个最大的负奇数,在上面两种做法中选取一个最优解就行。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const int inf = 1e6;
int n;
//int a[maxn];
int sum;//正偶数和
int num;//正奇数个数
int Max;//最大的负奇数
int odd[maxn];
int ans;
void init()
{
    sum = 0;
    num = 0;
    ans = 0;
    Max = -inf;
}
int main()
{
    while(~scanf("%d",&n))
    {
        init();
        int x;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d",&x);
            if(x > 0)
            {
                if(x&1)
                {
                    num++;
                    odd[num] = x;
                    ans += x;
                }
                else
                {
                    sum += x;
                }
            }
            else
            {
                if(abs(x)%2 == 1)
                {
                    if(x > Max)
                    {
                        Max = x;
                    }
                }
            }
        }
        if(num == 0) printf("%d\n",sum + Max);
        else if(num&1) printf("%d\n",ans + sum);
        else
        {
            sort(odd + 1,odd + num + 1);
            if(Max == -inf) printf("%d\n",ans + sum - odd[1]);
            else
            {
                int result = max(ans + sum - odd[1],ans + sum + Max);
                printf("%d\n",result);
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值