分支限界法求解背包问题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
分支限界法求解背包问题
/*此程序实现,分支限界法求解背包问题,分支限界法是根据上界=当前背包的价值 + 背包
剩余载重 * (剩余物品最大价值/质量)*/
下面是运算过程截图
#include
#include
#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++)
{
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(" weight ");
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;
exemptyweightb[0] = BAGWEIGHT;
ub = tempvalue + emptyweight * costarrayb[1];
printf("include 0: weight=0 value=0 ub = %f\n",ub);