分支限界法求解背包问题

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

分支限界法求解背包问题

/*此程序实现,分支限界法求解背包问题,分支限界法是根据上界=当前背包的价值+背包

剩余载重* (剩余物品最大价值/质量)*/

分支r 10 I 分S: 104 1.200060' 6 2.i/eeoe

#i nclude #i nclude

#include

#include

#include

#define MAXSIZE 20000

//#define BAGWEIGHT 200 int a[MAXSIZE] = {0};

int array[MAXSIZE] = {0};

int weightarray[MAXSIZE] = {0}; /* 存放各物品重量*/

int valuearray[MAXSIZE] = {0}; /* 存放各物品价值*/

int lastweight[MAXSIZE]={0}; int lastvalue[MAXSIZE]={0}; int qq=0;

/* 上面的数组,变量都是蛮力法所用到,下面的都是分支限界法所用到*/ int BAGWEIGHT; /* 背包的载重*/

int n; /* 物品的数量*/int weightarrayb[MAXSIZE] = {0}; int

valuearrayb[MAXSIZE] = {0}; float costarrayb[MAXSIZE] = {0}; int

finalb[MAXSIZE] = {0};

int finalweightb[MAXSIZE] = {0};

/* 从文件读取数据*/

void readb()

int nn = 1,ii = 1;

int i = 1;

FILE *fp;

fp = fopen("in.dat","rb");

while(!feof(fp))

{

if(fscanf(fp,"%d%d",&weightarrayb[nn],&valuearrayb[nn]) != EOF)

nn++;

i++;

else

break;

fclose(fp);

printf(" weight ");

printf("value\n");

for(ii = 1;ii < nn;ii++)

printf("no%d: %-5d%-5d",ii,weightarrayb[ii],valuearrayb[ii]);

printf("\n");

/* 把读取的数据按照性价比从大到小排序*/ void rangeb()

int i,j,k;

int tempvalue,tempweight,tempcost;

for(i = 1;i <= n;i++)

printf(" weight ");

costarrayb[i] = valuearrayb[i]/weightarrayb[i];

for(j = 1;j <= n;j++)

for(k = j;k <= n;k++)

if(costarrayb[j] < costarrayb[k+1])

tempcost = costarrayb[j];

costarrayb[j] = costarrayb[k+1];

costarrayb[k+1] = tempcost;

tempweight = weightarrayb[j];

weightarrayb[j] = weightarrayb[k+1];

weightarrayb[k+1] = tempweight;

tempvalue = valuearrayb[j];

valuearrayb[j] = valuearrayb[k+1];

valuearrayb[k+1] = tempvalue;

printf("value ");

printf("cost\n");

for(i = 1;i <= n;i++)

printf("no%d: %-5d%-5d %- f",i,weightarrayb[i],valuearrayb[i],costarrayb[i]); printf("\n");

/* 分支限界法运算*/

void branchb()

int i,k,j,u = 1;

int emptyweight = BAGWEIGHT;

int tempweight = 0;

int tempvalue = 0;

float ub;

float exub;

int extempweightb[MAXSIZE] = {0};

int extempvalueb[MAXSIZE] = {0};

int exemptyweightb[MAXSIZE] = {0};

int allweight = 0;

int allvalue = 0;

ub = tempvalue + emptyweight * costarrayb[1];

exemptyweightb[0] = BAGWEIGHT;

printf("include 0: weight=0 value=0 ub = %f\n",ub);

printf("\n");

i = 1;

while(weightarrayb[i] != 0)

tempweight = tempweight + weightarrayb[i];

tempvalue = tempvalue + valuearrayb[i];

emptyweight = BAGWEIGHT - tempweight;

if(tempweight > BAGWEIGHT)

printf("include %d: weight=%d can't\n",i,tempweight);

tempweight = extempweightb[i-1];

tempvalue = extempvalueb[i-1];

emptyweight = exemptyweightb[i-1];

ub = 0;

else

ub = tempvalue + emptyweight * costarrayb[i+1];

printf("include %d: weight=%d value=%d ub=%f\n",i,tempweight,tempvalue,ub); extempvalueb[i] = tempvalue;

extempweightb[i] = tempweight;

exemptyweightb[i] = emptyweight;

相关文档
最新文档