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

讨论装载问题:

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

解:一般回溯法思想,这是个子集数问题,用递归比较好写,然而不用递归怎么写呢?这里用到了迭代回溯的思想。

/******************************************************
* Author       : Aaron92
* Date		   : 2016-05-12 15:41
* Filename     : Load_boat.c
* Description  : 
******************************************************/

#include
#include
#include

#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){
			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++;
		}
	}
}

你可能感兴趣的:(linux-c,算法设计)