[Dynamic classification] 01 backpack with accessories: Jinmin's procurement plan

Assuming that the i-th main component is reached, there are currently 5 choices:

(1) Buy nothing (2) Buy only the main part (3) Buy the main part and attachment 1 (4) Buy the main part and the attachment 2 (5) Buy the main part, the attachment 1, and the attachment 2

Design of the data structure:

Use two-dimensional arrays v[i][0], v[i][1], v[i][2] to represent the value of the i-th main piece, the value of the first accessory of the i-th main piece, and the value of the first accessory of the i-th main piece. The value of the main part and the second accessory of the i part.

Use two-dimensional arrays w[i][0], w[i][1], w[i][2] to represent the importance of the i-th main component and the importance of the first accessory of the i-th main component , the importance of the second accessory of the i-th main component.

dp[i][j]: Represents the maximum value of the first i main components in the case of j

dp[i][j]=max( dp[i-1][j],

dp[i-1][j-v[i][0]]+v[i][0]*w[i][0],

dp[i-1][j-v[i][0]-v[i][1]]+v[i][0]*w[i][0]+v[i][1]*w[i][1],

dp[i-1][j-v[i][0]-v[i][2]]+v[i][0]*w[i][0]+v[i][2]*w[i][2],

dp[i-1][j-v[i][0]-v[i][1]-v[i][2]]+v[i][0]*w[i][0]+v[i][1]*w[i][1]+v[i][2]*w[i][2])

#include<iostream>
using namespace std;
int dp[32001];
int v0[61];
int p0[61];
int v1[61];
int p1[61];
int v2[61];
int p2[61];
int n,m;
int main(){
	cin>>n>>m;
	int v,p,q;
	int cnt=1;
	for(int i=1;i<=m;i++){
		cin>>v>>p>>q;
		if(q==0){
			v0[i]=v;
			p0[i]=p;
		}
		else if(v1[q]==-1)
			{
			v1[q]=v;
			p1[q]=p;
		}
		else{
			v2[q]=v;
			p2[q]=p;
		}
	}
	for(int i=1;i<=m;i++){
		for(int j=n;j>=v0[i]&&v0[i]!=0;j--){
			if(j>=v0[i]){
				dp[j]=max(dp[j],dp[j-v0[i]]+v0[i]*p0[i]);}
			else if(j>=v0[i]+v1[i]){
				dp[j]=max(dp[j],dp[j-v0[i]-v1[i]]+v0[i]*p0[i]+v1[i]*p1[i]);}
			else if(j>=v0[i]+v2[i]){
				dp[j]=max(dp[j],dp[j-v0[i]-v2[i]]+v0[i]*p0[i]+v2[i]*p2[i]);
			}
			else if(j>=v0[i]+v1[i]+v2[i]){
				dp[j]=max(dp[j], dp[j - v1[i]- v0[i]- v2[i]]+v0[i]*p0[i]+v1[i]*p1[i]+v2[i]*p2[i]);
			}
			}			
		}
	cout<<dp[n];
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123977029