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

#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;
      }
   }
}
posted @ 2012-11-15 01:31  ﹏Sakura  阅读(189)  评论(0编辑  收藏  举报