Idea: if there is no restriction equivalent to 01 knapsack with increased dimension, dp[i][j][k][t] represents the maximum value obtained by the first I objects loaded into the knapsack with v1=j, v2=k, v3=t, and can be transferred directly. Now there i s a limitation of S, that is, when we take the goods with s[i]=1, we cannot transfer dp[i-1][j][k][t] to dp[i][j][k][t]. This question card memory, the first dimension can be scrolling array. However, it is more interesting to directly omit the first dimension of writing, and can't solve the problem of constraints according to the above methods (those who have written about space optimization backpacks should be able to feel it). The method I use here i s to make dp[j][k][t]=-INF when s[i]=1. This step can avoid the operation of not taking this item. See code:
#include <bits/stdc++.h> #define INF 1111111111 using namespace std ; int dp[505][55][2],p[305],h[305],s[305]; int main() { int x,y,n,cas=0; while(scanf("%d%d%d",&x,&y,&n)&&x&&y&&n) { cas++; memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) scanf("%d%d%d",&p[i],&h[i],&s[i]); for(int i=1;i<=n;i++) { for(int j=x;j>=0;j--) { for(int k=y;k>=0;k--) { for(int t=1;t>=0;t--) { if(s[i]==1) dp[j][k][t]=-INF; if(j>=p[i]) dp[j][k][t]=max(dp[j][k][t],dp[j-p[i]][k][t]+h[i]); if(k>=p[i]) dp[j][k][t]=max(dp[j][k][t],dp[j][k-p[i]][t]+h[i]); if(t==1) dp[j][k][t]=max(dp[j][k][t],dp[j][k][0]+h[i]); } } } } printf("Case %d: ",cas); if(dp[x][y][0]<0&&dp[x][y][1]<0) printf("-1\n\n"); else printf("%d\n\n",max(dp[x][y][0],dp[x][y][1])); } return 0; }