背包问题求解-递归

//大小、重量均为整型  完成输入连续按两次回车
#include<iostream>
using namespace std;

struct item
{
	int weight;
	int size;
	item* next;
	item* last;
};

int PackSize;
int PreventSize=0;
item* head = (item*)malloc(sizeof(item));
item* pItem;
int ItemNum = 0;
int Weight = 0;

int GetMaxWeight(int num)
{
	int w1,w2;
	bool NotCounted;
	if (num == ItemNum)
		pItem = head;
	else
		pItem = pItem->next;

	if (num == 1)
	{
		PreventSize += pItem->size;
		if (PreventSize > PackSize)
		{
			PreventSize -= pItem->size;
			pItem = pItem->last;
			return 0;
		}
		else
		{
			pItem = pItem->last;
			return pItem->weight;
		}
	}

	PreventSize += pItem->size;
	if (PreventSize > PackSize)
	{
		PreventSize -= pItem->size;
		NotCounted = true;
		w1 = GetMaxWeight(num - 1);
	}
	else
	{
		NotCounted = false;
		w1 = pItem->weight + GetMaxWeight(num - 1);
	}

	if(!NotCounted)
		PreventSize -= pItem->size;
	w2 = GetMaxWeight(num - 1);
	if (w2 > w1)
	{
		pItem = pItem->last;
		return w2;
	}
	else
	{
		pItem = pItem->last;
		return w1;
	}

}

int main()
{
	cout << "请输入背包大小:";
	cin >> PackSize;
	cout << "请依次输入物品的大小、重量,用空格分开" << endl;
	item* p=head,*q,*r;
	while (true)
	{
		r = p;
		cin >> p->size >> p->weight;
		ItemNum++;
		cin.get();
		if (cin.peek() == '\n')
		{
			p->next = NULL;
			break;
		}
		q= (item*)malloc(sizeof(item));
		p->next = q;
		p = p->next;
		p->last = r;
	}

	cout <<"背包能装的最大重量:"<< GetMaxWeight(ItemNum)<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值