欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

背包问题(待补充)

程序员文章站 2022-02-11 06:28:12
...

0-1背包

【动态规划】讲解

#include<iostream.h>

void main()
{
	int capacity = 10;  //容量
	int w[6] = {0,2,2,6,5,4};  //重量
	int v[6] = {0,6,3,5,4,6};  //价值
	int p[6][11];  //背包
	int i,j;
	//初始化为0
	i=0;
	for(j=0;j<11;j++)
		p[i][j] = 0;
	j=0;
	for(i=0;i<6;i++)
		p[i][j] = 0;
	//对待物品的三种情况
	for(i=1;i<6;i++)
	{
		for(j=1;j<11;j++)
		{
			int num1 = p[i-1][j-w[i]]+v[i];
			int num2 = p[i-1][j];
			if(j<w[i])  //放不下
				p[i][j] = p[i-1][j];
			else if(num1 > num2)  //放
				p[i][j] = num1;
			else  //不放
				p[i][j] = num2;
		}
	}
	cout<<"最大价值为:"<<p[5][10]<<endl;

	int flag[5] = {0,0,0,0,0};  //是否装入背包中
	int tem = capacity;
	cout<<"放到背包的号码:";
	for(int t=5;t>0;t--)
	{
		if(p[t-1][tem-w[t]]+v[t] > p[t-1][tem])
		{
			cout<<t<<"号 ";
			tem = tem-w[t];
		}
	}
	cout<<endl; 
}

【回溯法】讲解

#include<iostream>
using namespace std;
int n = 5;  //
int capacity = 10;  //
int wei[5] = {2,2,6,5,4};  //
int val[5] = {6,3,5,4,6};  //
int x[5];  //
int res[5];  //
int bestp = 0;  //

//
void bug(int i,int weight,int cp,int rp)
{
	if(i>=n)
	{
		if(bestp<cp)
		{
			bestp = cp;
			for(int j=0;j<n;j++)
				res[j] = x[j];
		}
		return;
	}
	else
	{
		//遍历左子树
		if(weight >= wei[i])
		{
			x[i] = 1;
			cp = cp+val[i];
			rp = rp-val[i];
			bug(i+1,weight-wei[i],cp,rp);
			//回溯
			cp = cp - val[i];
			rp = rp + val[i];
		}
		//遍历右子树
		if(cp+rp-val[i] > bestp)
		{
			x[i] = 0;
			rp = rp-val[i];
			bug(i+1,weight,cp,rp);
		}
		return;
	}
}

int main()
{
	int cp = 0;  //
	int rp = 24;  //

	int weight = capacity;  //
	bug(0,weight,cp,rp);
	cout<<"装入背包的是:"<<endl;
	for(int i=0;i<n;i++)
	{
		if(res[i]==1)
			cout<<i+1<<endl;
	}
	cout<<"背包内物品总价值是:"<<bestp<<endl;
	return 0;
}


上一篇: 桶排序 补充问题

下一篇: 验证码