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;
}

發佈了84 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章