Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.5 kB
1
Indexable
Never
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

std::pair<int ,int> splitInBackpacks(const std::vector<int> &items) {

    using Table = std::vector<std::vector<int>>;
    using Row = std::vector<int>;

    Table table;

    int totalWeight = std::accumulate(items.begin(), items.end(), 0);
    int oneBackpackWeight = totalWeight / 2;

    table.push_back(std::vector<int>(oneBackpackWeight, 0));

    Row tableRow{};
    for(size_t i = 0; i < items.size(); ++i) {
        int weight = 0;
        while(weight < items[i] - 1) {
            tableRow.push_back(table[i][weight]);
            weight++;
        }
        while(weight < oneBackpackWeight) {
            int maxWeight = std::max(table[i][weight], table[i][weight - items[i]] + items[i]);
            tableRow.push_back(maxWeight);
            weight++;
        }
        table.push_back(tableRow);
        tableRow.clear();
    }

    int result = table.back().back();

    return std::minmax(result, totalWeight - result);
}

int main()
{

    using std::cin;
    using std::cout;

    std::vector<int> items;
    while(1) {
        int itemsCount;
        cin >> itemsCount;
        if(!itemsCount)
            break;
        while(cin.peek() != '\n') {
            int weight;
            cin >> weight;
            items.push_back(weight);
        }
        auto backpackWeights = splitInBackpacks(items);
        cout << backpackWeights.second << " " << backpackWeights.first << std::endl;
        items.clear();
    }
    return 0;
}