Common knapsack problem summary (DP)

Common knapsack problem summary and optimized code (DP)

1.01 Backpack

Note optimization: The second layer is a cycle in reverse order , the reasons not described here, the reader to find.
On the following core code.

	for(int i=1;i<=n;i++)///n物品数,m背包容量
		for(int j=m;j>=w[i];j--)//w[i]物品i的重量,v[i]物品i的价值
			f[j]=max(f[j],f[j-w[i]]+v[i]);

2. Fully backpack (the number of times each of the 01 articles unlimited backpack)

Backpack with 01 different unique optimized point is: the second layer is a loop sequence , the reason not described here, the reader to find.
On the following core code.

for(int i=1;i<=n;i++)
	 	for(int j=w[i];j<=m;j++) 
		 	f[j]=max(f[j],f[j-w[i]]+v[i]);

3. multiple backpacks (01 backpack upgraded version, the number of items each finite)

01 is an extension of the multi backpack backpack, the backpack 01 may be seen as the number of each article is a multi-pack.
On the following core code.

for(int i=1;i<=n;i++)
	for(int j=1;j<=p[i];j++)
		for(int k=m;k>=w[i];k--)
			f[k]=max(f[k],f[k-w[i]]+v[i]);

4. Backpack packet (each selected from only one article 01 backpack variant)

When optimizing triple cycle, Note that the loop has the layer sequence.
Here the core code.

vector<int>p[N];//二维数组p[i][j]表示第i组的第j个物品的序号数,方便查找w[i],v[i] 
int w[N],v[N],f[N],pos;//pos表示物品在那个组。 
	for(int i=1;i<=n;i++){
		cin>>w[i]>>v[i]>>pos;
		p[pos].push_back(i);
		}
	for(int i=1;i<=t;i++)
		for(int j=v;j>=0;j--)
			for(int k=0;k<p[i].size();k++)
				{
					int x=p[i][k];//第i组第k个物品的序号数 
					if(w[x]<=j) f[j]=max(f[j],f[j-w[x]]+v[x]);
				}

5. Mix Backpack (complete multiple backpacks and backpack body)

Multiple backpack and is to complete the merger at the code, if a judge just fine.
Here the core code.

for(int i=1;i<=n;i++)
			cin>>w[i]>>v[i]>>p[i];
		for(int i=1;i<=n;i++){
			if(!p[i]){//完全背包 
				for(int j=w[i];j<=m;j++)
					f[j]=max(f[j],f[j-w[i]]+v[i]);
			}else{ //多重背包与01背包. 
				for(int j=1;j<=p[i];j++)
					for(int k=m;k>=w[i];k--)
					f[k]=max(f[k],f[k-w[i]]+v[i]);
			}

6. Double-conditions 01 backpack in (01 backpack optimization based on a multi-dimensional)

for(int i=1;i<=n;i++)
		for(int j=w1;j>=w1[i];j--)
			for(int k=w2;k>=w2[i];k--)
				dp[j][k]=max(dp[j][k],dp[j-w1[i]][k-w2[i]]+v[i]); 

Summary: 01 backpack, multiple backpack, backpack grouping reverse order .
Backpack completely sequential , backpacks triple loop packets ( multi-layer article is to traverse each group, the order of layers is: the number of groups - capacity - the number of items in each group ), a mixture of multiple mixing backpack backpacks and complete backpack ( IF determination )
--------------- -------------------------------- To be continued ------------------

Published 18 original articles · won praise 14 · views 363

Guess you like

Origin blog.csdn.net/weixin_45750972/article/details/104268226