0-1 Backpack The essence of the problem is that each item in a sequence has a selection and no two cases
For example, to select several items from a pile of objects to meet certain nature problems
Initialization needs to be noted that at the beginning, the DP array needs to be set to a solution that is not possible relative to the positive solution , which may be 0 or negative infinity, positive infinity, and specific analysis.
Stage: Before processing finished I item
Additional status: What is the current backpack volume?
Different state transfer equations of different problems
The code is as follows:
#include <bits/stdc++.h>using namespace std;const int maxn=1010;int t,m,cost[101],val[101];//m种物品,重量不超过tint dp[maxn];void read_and_parse(){ scanf("%d%d",&t,&m); for(int i=1;i<=m;i++)scanf("%d%d",&cost[i],&val[i]); memset(dp,0xcf,sizeof(dp)); dp[0]=0;}void solve(){ for(int i=1;i<=m;i++) for(int j=t;j>=cost[i];j--) dp[j]=max(dp[j],dp[j-cost[i]]+val[i]); int ans=0; for(int i=0;i<=t;i++)ans=max(ans,dp[i]); printf("%d\n",ans);}int main(){ read_and_parse(); solve(); return 0;}
"Template" 0-1 backpack