---
id: 1777
lang: en
translation_of: index.md
source_sha256: 0262d150c4ac1464044e75d3624737cfc70b3eefa69dcfadc73cad508d59144c
title: "The Top-k Solutions Problem for 0/1 Knapsack"
description: "Add a dimension for the x-th best answer and merge the take and skip candidates like merge sort to get the k best 0/1 knapsack answers."
tags: ["OI","DP","Knapsack"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "01背包 rendered with the standard English name “0/1 knapsack”."
---

## Overview

I've recently been getting ready to start reviewing knapsack problems, and right before reading *<span class="slang" data-zh="背包九讲" data-gloss="Bēibāo Jiǔ Jiǎng, “Nine Lectures on Knapsack”. A classic Chinese tutorial on knapsack-problem DP.">Nine Lectures on Knapsack</span>* 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

```cpp
// 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;
}
```
