Python3 代码

n = int(input())
snacks = list(map(int, input().split()))

total = sum(snacks)
if total % 2 == 1:
    print(-1)
else:
    target = total // 2
    count = 0
    for snack in snacks:
        if snack > target:
            print(-1)
            break
        elif snack == target:
            count += 1
        else:
            count += 2
    else:
        print((count - n) // 2)

C++ 代码

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> snacks(n);
    int total = 0;
    for (int i = 0; i < n; i++) {
        cin >> snacks[i];
        total += snacks[i];
    }
    if (total % 2 == 1) {
        cout << -1 << endl;
    } else {
        int target = total / 2;
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (snacks[i] > target) {
                cout << -1 << endl;
                return 0;
            } else if (snacks[i] == target) {
                count++;
            } else {
                count += 2;
            }
        }
        cout << (count - n) / 2 << endl;
    }
    return 0;
}
``

原文地址: https://www.cveoy.top/t/topic/fblo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录