0-1背包问题
来源:互联网 发布:java工程师证书有用吗 编辑:程序博客网 时间:2024/05/17 01:03
0-1背包问题
时限:1000ms 内存限制:10000K 总时限:3000ms
描述
需对容量为c 的背包进行装载。从n 个物品中选取装入背包的物品,每件物品i 的重量为wi ,价值为pi 。对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。
输入
多个测例,每个测例的输入占三行。第一行两个整数:n(n<=10)和c,第二行n个整数分别是w1到wn,第三行n个整数分别是p1到pn。
n 和 c 都等于零标志输入结束。
n 和 c 都等于零标志输入结束。
输出
每个测例的输出占一行,输出一个整数,即最佳装载的总价值。
输入样例
1 2
1
1
2 3
2 2
3 4
0 0
1
1
2 3
2 2
3 4
0 0
输出样例
1
4
4
#include <iostream>#include <algorithm>using namespace std;double c; //背包容量int n; //物品数double cw; //当前重量double cp; //当前价值int bestp; //当前最优价值typedef struct Item{ double w; //物品的重量 double p; //物品的价值}Item;Item item[100];bool cmp(Item a, Item b){ return a.p/a.w > b.p/b.w;}double bound(int i){ double cleft = c - cw; //剩余容量 double b = cp; //能装载容量的最大上界 //将剩余物品装入背包,直至装不下为止 while(i <= n && item[i].w <= cleft) { cleft -= item[i].w; b += item[i].p; } //将最后一件装不下的物品拆解,让背包装满 //计算能装载容量的最大上界 if(i <= n) b += item[i].p/item[i].w*cleft; return b;}void Backtrack(int i){ //叶子节点 if(i > n) { if(cp > bestp) //上界不一定取到 bestp = (int)cp; return; } //搜索子树 if(cw + item[i].w <= c) { cw += item[i].w; cp += item[i].p; Backtrack(i+1); cw -= item[i].w; cp -= item[i].p; } if(bound(i+1) > bestp) Backtrack(i+1);}int main(){ while(cin >> n >> c && (n || c)) { bestp = 0; //每组样例初始化 for(int i = 1; i <= n; i ++) //i从1开始 cin >> item[i].w; for(int i = 1; i <= n; i ++) cin >> item[i].p; sort(item+1, item+n+1, cmp); //从1开始,wa了好多次 Backtrack(1); //从1开始递归 printf("%d\n", bestp); } return 0;}
0 0
- 背包问题(0-1背包、完全背包、多重背包)详解
- 背包问题和0-1背包问题
- 背包问题和0-1背包问题
- 背包问题系列--"0-1背包问题"
- 背包笔记-含0/1背包问题、完全背包问题、多重背包问题、二维背包问题、分组背包问题
- 【背包问题】背包问题之0-1背包、完全背包、多重背包
- 0-1背包问题
- 0/1背包问题
- 0,1背包问题
- 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- // 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- 0-1背包问题
- 0-1背包问题
- 0/1背包问题
- 使用Eclipse构建Maven项目(一)
- 百度云通话记录自动删除脚本
- Atitit 颜色平均值cloor grb hsv模式的区别对比
- java内部类详解
- Codeforces 492C Vanya and Exams【贪心】
- 0-1背包问题
- qt4 to qt5
- HTTP协议(复习)
- IntelliJ IDEA 12创建Maven管理的Java Web项目(图解)
- java数据结构与算法 第2章 数组
- java中关于时间日期操作的常用函数
- 装载问题
- 【C语言】 链表 单链的建立,节点增加 删除 顺序插入
- 8皇后问题(c++)