您的位置:首页 > 其它

小白笔记-----------------------迭代回溯

2016-05-12 19:20 197 查看
讨论装载问题:

有一批n个集装箱装入载重量为c的轮船,找出最多能装多少?

解:一般回溯法思想,这是个子集数问题,用递归比较好写,然而不用递归怎么写呢?这里用到了迭代回溯的思想。
/******************************************************
* Author       : Aaron92
* Date		   : 2016-05-12 15:41
* Filename     : Load_boat.c
* Description  :
******************************************************/

#include<stdio.h>
#include<string.h>
#include<unistd.h>

#define n 3//the number of box
#define c 90//the weight of the boat

main(int argc,char ** argv){
int w[3] = {40,40,20};//define the weight of each box
int result;
result = Maxload(w);
printf("%d\n",result);

}
Maxload(int *w){
int bestw = 0;//the best weight
int cw = 0;//current weight
int r = 0;//the left weight
int i = 0,j;//i refers to the tree lever
int x[3] = {0,0,0};
for(j = 0;j < n;j++){
r+= w[j];
}
while(1){
while(i<n && cw+w[i]<=c){
r-= w[i];
cw+= w[i];
x[i] = 1;
i++;
}
if(i >= n){
if(cw > bestw){
bestw = cw;
}
}else{
r-= w[i];
x[i] = 0;
i++;
}
while(cw + r <= bestw){
i--;
while(i>0 && !x[i]){
r+= w[i];
i--;
}
if(i == 0){
return bestw;
}
x[i] = 0;
cw-= w[i];
i++;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: