【算法复习】01背包问题

第一个自己写的代码

不是ctrl+c, ctrl+v了

#include "pch.h"
#include <iostream>

int w[5] = { 800, 400, 300, 400, 200 };
int v[5] = { 2, 5, 5, 3, 2 };
int choose[5] = { 0,0,0,0,0 };
int limit = 1000;
int happy = 0;
void search(int m);
int checkmax();
int main()
{
	//readdata();
	search(0);
	std::cout << happy << std::endl;
}
void search(int m) //回溯法,深度优先
{
	if (m > 5 || m == 5) 
	{
		int temp_sum = 0;
		int i;
		for (i = 0; i < 5; i++) {
			if (choose[i] == 1)temp_sum += w[i] * v[i];
		}
		if (temp_sum > happy)happy = temp_sum;
		return ;
	}
	else
	{
		choose[m] = 1;
		if (checkmax()) {
			search(m + 1);
		}
		choose[m] = 0;
		search(m + 1);

	}
}
int checkmax()//不得超过最大重量限制,左剪枝
{
	int i;
	int sumweight = 0;
	for (i = 0; i < 5; i++)
	{
		if (choose[i] == 1)
		{
			sumweight += w[i];
		}
	}
	if (sumweight > 1000)return 0;
	else return 1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值