问题描述:给定一个载重为n的背包,现有m颗宝石,宝石具有重量和价值,现在往背包放宝石,让其价值最大!
分析:假设背包重量为11,有5颗石头,重量和价值分别为(2,10),(3,7),(2,10),(6,12),(3,8)。设f(11,5)为背包载重为11,有5颗石头时的最大价值!现在把(2,10)这颗石头拿出来分析,如果此石头加入到背包中则f(11,5)=f(11-2,4)+10,因为此石头一旦加入,背包载重变为11-2,石头数量变为4,此时产生价值10;如果此石头不加入背包,f(11,5)=f(11,4)。以此递归,从而得到解。
#include "alcomm.h"
//石头包含重量和价值
typedef struct stone
{
int weight;
int value;
}stone;
//bgwit表示背包载重,s是数组,count是数组元素个数
int bag(int bgwit,stone *s,int count)
{
assert(s!=NULL);
//当只有一颗石头是,如果包不能容纳,返回0
if(count==1&&s[0].weight>bgwit)return 0;
//如果能容纳,返回石头价值
else if(count==1&&s[0].weight<=bgwit)return s[0].value;
//next保存剩余的石头(剔除元数组中第一颗石头)
stone next[count-1];
int i=0;
for(i=1;i<count;i++)
{
next[i-1]=s[i];
}
//如果第一颗石头不加入背包的情况
int noadd=bag(bgwit,next,count-1);
int add=0;
//如果第一颗石头加入背包的情况
if(bgwit>=s[0].weight)
add=s[0].value+bag(bgwit-s[0].weight,next,count-1);
//两者取其大
return add>noadd?add:noadd;
}
int main()
{
int tweight,stonenum,i;
printf("input the bag weight:");
scanf("%d",&tweight);
printf("input the stone number:");
scanf("%d",&stonenum);
stone s[stonenum];
printf("input the stone weight:");
for(i=0;i<stonenum;i++)
{
scanf("%d",&s[i].weight);
}
printf("input the stone value:");
for(i=0;i<stonenum;i++)
{
scanf("%d",&s[i].value);
}
int maxValue=bag(tweight,s,stonenum);
printf("The max value is:%d\n",maxValue);
return 0;
}
alcomm.h头文件
#ifndef _ALCOMM_H
#define _ALCOMM_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#endif