//大小、重量均为整型 完成输入连续按两次回车
#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;
}
背包问题求解-递归
最新推荐文章于 2022-06-13 11:21:34 发布