公式

D - Robot Customize 解説 by en_translator


Let \(S\) be the sum of weights of all the parts.

Consider first attaching all the parts to the body, and then moving some of them to the head.

Then it is sufficient to solve the following problem:

The weight and value of the \(i\)-th item is \(W _ i\) and \(V_ i=H _ i-B _ i\), respectively. Find the maximum possible total values of items whose weights sum to \(\left\lfloor\dfrac S2\right\rfloor\) or less.

This is a typical Knapsack problem, which can be solved in \(O(NS)\) time with Dynamic Programming (DP).

The following is sample code.

#include <iostream>
#include <vector>
#include <algorithm>
#include <ranges>

int main() {
    using namespace std;
    int N;
    cin >> N;
    vector<long> dp{0}, prev;
    for (int n = 0; n < N; ++n) {
        int w, h, b;
        cin >> w >> h >> b;
        swap(dp, prev);
        const auto M = size(prev);
        dp.resize(M + w);
        for (int i = 0; i < M; ++i) {
            dp[i] = max(dp[i], prev[i] + h); // Attach to head
            dp[i + w] = max(dp[i + w], prev[i] + b); // Attach to body
        }
    }
    cout << ranges::max(dp | views::drop(size(dp) / 2)) << endl;
    return 0;
}

投稿日時:
最終更新: