您的位置:首页 > 其它

01 背包问题 --- 待续 - -

2012-11-15 01:31 176 查看
#include <stdio.h>
#define MAX 100  //最多种类数
int current[MAX];
int opt[MAX];
int t;
double totalV;
double totalW;
double MaxValue;
struct{
double value;
double weight;
}goods[MAX];
void checkout(int i,double tw,int totalValue);
void main(){

int i;
double value,weight;
printf("请输入类别个数");
scanf("%d",&t);
printf("请输入商品的价格和重量:");
for(i =0;i<t;i++){
scanf("%lf %lf",&value,&weight);
goods[i].value = value;
goods[i].weight = weight;
totalV += value;
}
printf("请输入限制重量");
scanf("%lf",&totalW);

MaxValue = 0.0;
for(i=0; i<t;++i)
current[i] = 0;
checkout(0,0.0,totalV);
for(i=0;i<t;++i)
if(opt[i])
printf("%d\t",i+1);
printf("总价值为:%d",MaxValue);

}
void checkout(int i,double tw,int totalValue){
int k;
if(tw + goods[i].weight <=totalW){
current[i] = 1;
if(i<t-1){
checkout(i+1,tw,totalValue);
}else{

for(k=0;k<t;++k){
opt[k]=current[k];
}
MaxValue = totalValue;
}
}
current[i] = 0;
if(totalValue - goods[i].value > MaxValue){

if(i<t-1){
checkout(i+1,tw,totalValue-goods[i].value);
}else{

for(k=0;k<t;++k){
opt[k]=current[k];
}
MaxValue = totalValue-goods[i].value;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: