回溯法求解背包个数问题
2016-07-03 19:38
471 查看
华电北风吹
天津大学认知计算与应用重点实验室
2016-07-03
每个背包最大容量20,有N个物品,问至少需要多少个背包才能装完所有的物品?
输入描述:
第一行物品个数N,第二行N个整数,表示各个物品重量。物品个数小于等于10,物品重量小于等于10.
解题思路:
回溯法求解。不知道有没有更好的思路。。。
天津大学认知计算与应用重点实验室
2016-07-03
每个背包最大容量20,有N个物品,问至少需要多少个背包才能装完所有的物品?
输入描述:
第一行物品个数N,第二行N个整数,表示各个物品重量。物品个数小于等于10,物品重量小于等于10.
解题思路:
回溯法求解。不知道有没有更好的思路。。。
#include <iostream> #include <fstream> using namespace std; #define LENGTH 11 #define LIMITE 20 int stoneWeight[LENGTH]; int rounState[5]; bool func(int stoneIndex, const int& SumRoundNum, const int& N) { if (stoneIndex == N) return true; int weight = stoneWeight[stoneIndex]; for (int i = 0; i < SumRoundNum; i++) { if (rounState[i] + weight <= LIMITE) { rounState[i] += weight; if (func(stoneIndex + 1, SumRoundNum, N)) return true; else rounState[i] -= weight; } } return false; } int main() { ifstream in(".\\input.txt"); cin.rdbuf(in.rdbuf()); int N, sum = 0; cin >> N; for (int i = 0; i < N; i++) { cin >> stoneWeight[i]; sum += stoneWeight[i]; } int count = sum / LIMITE; while (true) { memset(rounState, 0, sizeof(rounState)); if (func(0, count, N)) { cout << count << endl; break; } else { count++; } } return 0; }
相关文章推荐
- CoreAnimation编程指南(一)核心动画基础
- 最新unity3d中关键概念全解(坐标系,脚本的执行顺序等)
- 实现tab切换的功能
- 自定义 UISwitch
- ViewPaper与ViewFliper的选择
- 指派问题与匈牙利解法
- MarkWord - 可发布到博客园的Markdown编辑器(支持图片同步)
- Activity启动方式的总结(2)
- HashTable源码
- 使用jquery实现AJAX技术的几种方法
- python出现过的问题总结
- Eclipse中xml配置文件报错原因总结
- InnoTop
- 折腾树莓派的一些总结
- hive在hadoop中的一个demo运行过程总结
- OSPF NBMA实验(单播、广播)
- Java语法的主要特性
- 爬取新浪微博主站大法
- spark sql例子
- nginx负载均衡一些好的文章