Codeforces 59B 题解

题意:

在一个序列里找最大的奇数和,和我上一篇博客题解里的B题有点挺像,只不过后者是一定存在答案,而且这题都是正数,这题如果有最大奇数和就打印,否则就输出0。

思路:

先对1个数的时候进行特判,如果是偶数就输出0,否则就打印这个数,接下来是多个数的情况,先对所有数求和记为sum,如果sum是奇数就直接打印,否则就进行如下操作:

对所有奇数累加求和并存进 odd[ ] 数组里,再升序排序,并记录奇数个数p,再求出所有偶数和sum0,这样处理的目的是,所有偶数的和必为偶数,所以说我只要给它加上一个最大奇数和即为所求,如果奇数个数为偶数,偶数个奇数的和必为奇数,所以把它累加到sum0上即为所求,如果奇数个数为偶数,那么先累加上去再减去最小奇数,即减去odd[1]即可。

本人AC代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 105;
map <int, int> mp;
queue <int> qua;
set <int> st;
int n;
int a[maxn];
int odd[maxn];

int main() {
    cin >> n;
    int ans;
    for(int i = 1; i <= n; i++) cin >> a[i];
    if(n == 1) {
        if(a[1] & 1) ans = a[1];
        else ans = 0;
    }
    else {
        int sum = 0;
        for(int i = 1; i <= n; i++) sum += a[i];
        if(sum & 1) ans = sum;
        else {
            int sum0 = 0;
            int p = 0;
            for(int i = 1; i <= n; i++) {
                if(a[i] & 1) {
                    p++;
                    odd[p] = a[i];
                }
                else sum0 += a[i];
            }
            if(p == 0) ans = 0;
            else {
                ans = sum0;
                sort(odd + 1, odd + p + 1);
                for(int i = 1; i <= p; i++) ans += odd[i];
                if(!(p & 1)) ans -= odd[1];
            }
        }
    }
    cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/ericgipsy/article/details/80600821