Different from general knapsack problems, the requirement is the K-optimal solution. First, we need to figure out how the optimal solution is obtained.
In order to find the optimal solution, we only store the optimal solution in this state for each State, ignoring other solutions, and then transfer between States, what about the k-th optimization? In fact, you only need to save the first K optimization solutions in each State, transfer the status from these K states, and deduplicate them at the same time, and save the K optimization solution of the current state.
# Include <iostream> # include <algorithm> # include <set> using namespace STD; int V [101], W [101]; int n, m, K, DP [1010] [31]; int TMP [65]; bool CMP (int A, int B) {return A> B;} int main () {int CAS; scanf ("% d", & CAS); While (CAS --) {scanf ("% d", & N, & M, & K ); for (INT I = 0; I <n; I ++) scanf ("% d", & W [I]); For (INT I = 0; I <N; I ++) scanf ("% d", & V [I]); memset (DP, 0, sizeof (DP); For (INT I = 0; I <n; I ++) {for (Int J = m; j> = V [I]; j --) {int temp = 0; fo R (int t = 0; t <K; t ++) {TMP [temp ++] = DP [J] [T]; TMP [temp ++] = DP [J-V [I] [T] + W [I];} // The TMP array stores all possible solutions for this status, then, obtain the K optimal solution sort (TMP, TMP + K * 2, CMP); temp = 1; DP [J] [0] = TMP [0]; for (int t = 1; t <K * 2 & temp <K; t ++) {If (TMP [T]! = TMP [T-1]) DP [J] [temp ++] = TMP [T] ;}} printf ("% d \ n ", DP [m] [k-1]);} return 0 ;}