Olympiad in Informatics

The Top-k Solutions Problem for 0/1 Knapsack

Overview

I've recently been getting ready to start reviewing knapsack problems, and right before reading Nine Lectures on Knapsack I happened to land on this problem at random, so here's a simple summary.

Principle

First, recall the DP recurrence for the 0/1 knapsack:

\[ dp[j] = \max\{ dp[j], dp[j - weight_i] + value_i \} \]

We can try adding a dimension that records the \(x\)-th best solution: \(dp[x][j]\). The hard part of this problem is how to merge the earlier, better solutions into the next-best ones. First, we notice that for each \(j\), \(\{ dp[1][j], dp[2][j], dp[3][j], \dots \}\) is monotonically decreasing. So if we want to merge them into a new monotonically decreasing sequence, we can use the merge step of merge sort: except that it is not done on two sequences but is a choice between two decisions. We can treat the answers that take item \(i\) and the ones that don't as two virtual sequences of length \(k\), and then merge them the way merge sort does.

Code

// P1858.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 5050;

int dp[55][MAX_N], k, m, n, wi[MAX_N], vi[MAX_N], tmp[MAX_N];

int main()
{
    scanf("%d%d%d", &k, &m, &n);
    for (int i = 1; i <= n; i++)
        scanf("%d%d", &wi[i], &vi[i]);
    memset(dp, 128, sizeof(dp));
    dp[1][0] = 0;
    for (int i = 1; i <= n; i++)
        for (int j = m; j >= wi[i]; j--)
        {
            int ptr1 = 1, ptr2 = 1, ptr = 0;
            while (ptr <= k)
                if (dp[ptr1][j] > dp[ptr2][j - wi[i]] + vi[i])
                    tmp[++ptr] = dp[ptr1++][j];
                else
                    tmp[++ptr] = dp[ptr2++][j - wi[i]] + vi[i];
            for (int pt = 1; pt <= k; pt++)
                dp[pt][j] = tmp[pt];
        }
    int ans = 0;
    for (int i = 1; i <= k; i++)
        ans += dp[i][m];
    printf("%d", ans);
    return 0;
}