P1858 multiplayer backpack
Description
Evaluate the value and
Requires Filling
Debug log: initialization is not assigned to DP [0]
Solution
First, add a knowledge point. The initial assigned \ (-INF \) is required for a full backpack and the boundary is \ (DP [0] = 0 \)
01 backpack for \ (k \) Optimization
Use \ (DP [J] [k] \) to represent the \ (k \) optimization solution of a backpack with a capacity of \ (J \)
UsedMerge SortingIdea
For the \ (I \) item, the capacity is \ (J \), we have two options:
- Select the \ (I \) item
- No \ (I \) item is selected
For every solution in \ (1-k \), we can get the \ (2 k \) answer.
Because the answers are divided into two sides (selected or not selected) in an internal order, merge them to get the \ (k \) before optimization.
Complexity \ (O (nmk )\)
Code
#include<iostream>#include<cstdio>#include<queue>#include<cstring>#include<algorithm>#include<climits>#define LL long long#define REP(i, x, y) for(int i = (x);i <= (y);i++)using namespace std;int RD(){ int out = 0,flag = 1;char c = getchar(); while(c < '0' || c >'9'){if(c == '-')flag = -1;c = getchar();} while(c >= '0' && c <= '9'){out = out * 10 + c - '0';c = getchar();} return flag * out; }const int maxn = 10019;int K, V, num;int w[maxn], v[maxn];int temp[maxn];int dp[maxn][119];int main(){ K = RD(), V = RD(), num = RD(); REP(i, 1, num)w[i] = RD(), v[i] = RD(); REP(i, 0, V)REP(k, 1, K)dp[i][k] = -1e9; dp[0][1] = 0; REP(i, 1, num){ for(int j = V;j >= w[i];j--){ int p1 = 1, p2 = 1, cnt = 0; while(cnt <= K){ if(dp[j][p1] > dp[j - w[i]][p2] + v[i])temp[++cnt] = dp[j][p1++]; else temp[++cnt] = dp[j - w[i]][p2++] + v[i]; } REP(k, 1, K)dp[j][k] = temp[k]; } } int ans = 0; REP(i, 1, K)ans += dp[V][i]; printf("%d\n", ans); return 0; }
P1858 multiplayer backpack