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

讨论装载问题:

        有一批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++;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值