#include <iostream>
using namespace std;
struct good
{
string name;
int weight;
int value;
good(string n,int w,int v)
{
name=n;
weight=w;
value=v;
}
good()
{
name = "0";
weight = 0;
}
};
struct bag
{
good *plan;
int put_count;
bag *next;
bag(good *p,int pc,bag *nextnode)
{
plan=p;
put_count=pc;
next=nextnode;
}
};
void printfResult(bag *head)
{
if(head->next==NULL)
{
return;
}
bag *p=head->next;
while(p!=NULL)
{
for(int i=0;i<p->put_count;i++)
{
cout<<p->plan[i].name<<":重量为:"<<p->plan[i].weight<<"价值为:"<<p->plan[i].value<<endl;
}
p=p->next;
cout<<"-----------------------------"<<endl;
}
}
void deleteResult(bag *head)
{
if(head->next==NULL)
{
return;
}
bag *p=head->next;
while(p!=NULL)
{
bag *p1=p;
p=p->next;
delete p1;
}
}
bag* createResult(good *goods,int count,int *resultselect)
{
good *p=new good[count]();
int count1=0;
for(int i=0;i<count;i++)
{
if(resultselect[i]==1)
{
p[count1].name=goods[i].name;
p[count1].weight=goods[i].weight;
p[count1].value=goods[i].value;
count1++;
}
}
return new bag(p,count1,NULL);
}
void Result(int weightcount,int &maxvalue,good *goods,int count,int select_count,int put_weight,int put_value,bag *head,int *resultselect)
{
if(select_count==count)
{
if(put_value>maxvalue)
{
maxvalue=put_value;
deleteResult(head);
head->next = createResult(goods, count, resultselect);
}
else if(put_value==maxvalue)
{
bag *p=createResult(goods, count, resultselect);
p->next=head->next;
head->next=p;
}
return;
}
good *put=&goods[select_count];
resultselect[select_count]=0;
Result(weightcount,maxvalue,goods,count,select_count+1,put_weight,put_value,head,resultselect);
if(put_weight+put->weight<=weightcount)
{
resultselect[select_count]=1;
Result(weightcount,maxvalue,goods,count,select_count+1,put_weight+put->weight,put_value+put->value,head,resultselect);
}
}
int main()
{
good goods[] = {
good("A", 6, 5),
good("B", 5, 3),
good("C", 4, 5),
good("D", 2, 3),
good("E", 1, 2),
};
int *resultselect=new int [3]();
bag head(NULL,0,NULL);
int maxvalue=0;
Result(10,maxvalue,goods,5,0,0,0,&head,resultselect);
cout << "Max value is " << maxvalue << endl;
printfResult(&head);
}