一个背包可以放入总质量为Total的物品。现有n件物品,质量分为:w[0],w[1],w[2]...w[n-1],并且从w[n-1],w[n-2],w[n-3]...到w[0],物品质量从重到轻。问:是否能够选出一组质量尽可能大的物品,并把它们放入背包,使得放入的质量之和正好是Total?
1.单链表来实现
#include
#include
#include
#include
typedef struct NODE{
int n;
struct NODE* next;
}NODE;
void Create(NODE* head, int n) {
//尾插法创建单链表
NODE* q = head;
for (; n > 0; n--) {
NODE* p = (NODE*)malloc(sizeof(NODE));
if (p) {
int s;
scanf("%d",&s);
p->n = s;
q->next = p;
q = p;
}
}
q->next = NULL;
}
void Output(NODE* head) {
//输出单链表中的数据
NODE* p = head->next;
while (p) {
printf("%d ", p->n);
p = p->next;
}
}
void Function(NODE* head,int TotalWeight){
int surplus=TotalWeight;
NODE* q=head->next;
while(q){
if(surplus-(q->n)>0){
printf("放%d(kg),剩余%d(kg)\n",q->n,surplus-(q->n));
surplus=surplus-(q->n);
q=q->next;
}
//如果当前物品放入后,背包还有剩余空间,那么把当前物品放入。
else if(surplus-(q->n)==0){
printf("放%d(kg),背包已装好啦!\n",q->n,surplus-(q->n));
surplus=surplus-(q->n);
q=q->next;
break;
}
//如果当前物品放入后,背包剩余空间恰好为零,那么把当前物品放入,然后退出循环。
else if(surplus-(q->n)<0){
q=q->next;
}
//如果当前物品放入后,背包装不下,那么不装入当前物品,直接看下一个。
}
if(surplus==0){
printf("Yes,the solution is effective!");
}
//背包中所有物品都试完之后,如果剩余空间恰为0,则方案可行。
else{
printf("No,the solution is ineffective...");
}
}
int main()
{
NODE* head=(NODE*)malloc(sizeof(NODE));
head->next=NULL;
int n,TotalWeight;
scanf("%d%d",&TotalWeight,&n);
Create(head,n);
Function(head,TotalWeight);
return 0;
}
1000 10
1024 512 256 128 64 32 16 8 4 2
放512(kg),剩余488(kg)
放256(kg),剩余232(kg)
放128(kg),剩余104(kg)
放64(kg),剩余40(kg)
放32(kg),剩余8(kg)
放8(kg),背包已装好啦!
Yes,the solution is effective!--------------------------------
Process exited after 16.31 seconds with return value 0
请按任意键继续. . .
2.递归解法实现
#include
#include
#include
#include
//下面这是个很复杂的递归,但是用Excel表格能更好地分析出来
int Function(int Surplus,int n,int* a){
if(Surplus==0){
return 1;
}
else if(Surplus<0){
return 0;
}
else if((Surplus>0)&&(n==0)){
return 0;
}
else if(Function(Surplus-a[n-1],n-1,a)==1){
printf("放%d千克,它是a[%d]\n",a[n-1],n-1);
return 1;
}
else{
return Function(Surplus,n-1,a);
}
}
int main(){
int TotalWeight;
scanf("%d",&TotalWeight);
int a[10]={0};
for(int i=9;i>=0;i--){
scanf("%d",&a[i]);
}
//依次确定10件物品各自的质量a[9],a[8],a[7]...a[0]
int Surplus=TotalWeight;
int flag=Function(Surplus,10,a);
if(flag==1){
printf("背包已经装好啦!\n");
}
//通过Function的递归,实现装物品的过程。
return 0;
}
1000
1024 512 256 128 64 32 16 8 4 2
放8千克,它是a[2]
放32千克,它是a[4]
放64千克,它是a[5]
放128千克,它是a[6]
放256千克,它是a[7]
放512千克,它是a[8]
背包已经装好啦!--------------------------------
Process exited after 21.01 seconds with return value 0
请按任意键继续. . .