01 backpack dynamic programming

Dynamic programming principle, the value of the recursive repetition of this operation, a two-dimensional array to store
int a [x] [y] ; x represents the number of goods, y represents the maximum carrying capacity.

Use to iterate constantly updated to select the maximum two-dimensional array
depends not vote in the election.

#include <iostream>
#include<iomanip>
using namespace std;
int max(int a, int b)
{
	return a > b ? a : b;
}
int main()
{	
	int n,w;//设置背包n为物体数量,w为背包的重量
	int wei[1001] = {0}, val[1001] = {0};//设置重量于价值
	cin >> w >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> wei[i] >> val[i];
	}
	int a[500][500] = {0};//利用二维数组来表示[x][y],x为商品的编号,y为背包所能承受最大的重量
	for(int i=1;i<=n;i++)//利用循环遍历商品的编号
		for (int j = 1; j <= w; j++)//利用循环遍历你想要的最大值
		{
			if (wei[i] > j) a[i][j] = a[i - 1][j];//如果当前商品大于所给定商品的重量,则把i-1个商品的质量赋给i;
			else
			{
				int temp1 = a[i - 1][j];//假如不大于的话,有不选第i件商品的值,则把i-1个商品的值付给temp1;
				int temp2 = a[i - 1][j - wei[i]] + val[i];//假如选的话,把a[i - 1][j - wei[i]] + val[i]赋给temp2,这个代表了选了a[i]的价值。
				a[i][j] = max(temp1, temp2);//最后比较选了i与没有选i的最大值,把值赋给[i][j] 即有几个商品与最大的质量
			}
		}
		
	cout << a[n][w];
}

One-dimensional array optimization

#include <iostream>
#include<iomanip>
using namespace std;
int max(int a, int b)
{
	return a > b ? a : b;
}
int main()
{	
	int n,w;//设置背包n为物体数量,w为背包的重量
	int wei[1001] = {0}, val[1001] = {0};//设置重量于价值
	cin >> w >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> wei[i] >> val[i];
	}
	int a[1001] = {0};//利用一维数组储存最大价值
	for(int i=1;i<=n;i++)//利用循环遍历商品的编号
		for (int j = w; j >=0; j--)//利用循环遍历你想要的最大值
		{	
			if (wei[i] > j) break;
			a[j] = max(a[j],a[j - wei[i]] + val[i]);//遍历更新,倒叙进行,假如不进行倒叙会重覆叠加。  回去前面查找并对比出最大值,再返回入aj。
		}
		
	cout << a[w];
}

https://www.bilibili.com/video/av16544031/?spm_id_from=333.788.videocard.1

Published 17 original articles · won praise 1 · views 3435

Guess you like

Origin blog.csdn.net/weixin_43983570/article/details/90383957