小白笔记-----------------------迭代回溯
2016-05-12 19:20
197 查看
讨论装载问题:
有一批n个集装箱装入载重量为c的轮船,找出最多能装多少?
解:一般回溯法思想,这是个子集数问题,用递归比较好写,然而不用递归怎么写呢?这里用到了迭代回溯的思想。
有一批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++; } } }
相关文章推荐
- linux find命令
- 心急的C小加
- Understanding C/C++ Strict Aliasing
- Ubuntu14.04下手动安装Firefox的Flash插件--转
- 学习github超详细资料
- Android之Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:扫描指定文件
- 加一
- http转https
- 顺序表应用4:元素位置互换之逆置算法
- spingmvc简单上传文件笔记
- L2-2. 链表去重
- angularJS的工具方法
- ListView 异步加载图片机制
- python 缺少 setuptools
- Linux 右键菜单(添加新建文件选项)
- 修改Linux图标
- web前台环境配置
- 心急的C小加
- 页面新宠图片格式WebP
- 获取项目地址的方式