背包问题start...:0-1背包
来源:互联网 发布:网络带来的好处 编辑:程序博客网 时间:2024/05/21 18:45
0-1背包
状态转移方程:f[i][v]=max{ f[i-1][v],f[i-1][v-c[i]]+w[i] }
题目:
需对容量为c的背包进行装载。从n个物品中选取装入背包的物品,每件物品i的重量为wi ,价值为pi 。对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。
Input
多个测例,每个测例的输入占三行。第一行两个整数:n(n<=10)和c,第二行n个整数分别是w1到wn,第三行n个整数分别是p1到pn。
n 和 c 都等于零标志输入结束。
Output
每个测例的输出占一行,输出一个整数,即最佳装载的总价值。
Sample Input
1 2
1
1
2 3
2 2
3 4
0 0
Sample Output
1
4
#include <iostream>using namespace std;#define MIN 0x80000000;int max_value;#define autor&&coder liyangguang1988 int maxValue(int *w,int *p,int n,int c){int *f=new int[c+1]; // f[i]是当前i容量的最大值f[0]=0;for(int i=1;i<=c;++i){//f[i]=MIN; //要求背包容量恰好用完时用这个f[i]=0; //不要求容量用完}for(int i=1;i<=n;++i)for(int j=c;j>=w[i];--j){f[j]=(f[j] >= (f[j-w[i]]+p[i]))?f[j]:(f[j-w[i]]+p[i]);//cout<<"f["<<i<<"]"<<"["<<j<<"] = "<<f[j]<<endl;}max_value = f[c];delete []f;return max_value;}int main(int argc,char *argv[]){ int n,c; while(cin>>n>>c) { if(n==0 && c==0) break; int w[11]={0}; int p[11]={0}; for(int i=1;i<=n;++i) cin>>w[i]; for(int i=1;i<=n;++i) cin>>p[i]; cout<<maxValue(w,p,n,c)<<endl; } return 0;}
图解:
彻底解决。
进一步:
0/1 bag problem should sound familiar to everybody. Every earth man knows it well. Here is a mutant: given the capacity of a bag, that is to say, the number of goods the bag can carry (has nothing to do with the volume of the goods), and the weight it can carry. Given the weight of all goods, write a program that can output, under the limit in the above statements, the highest weight.
INPUT:
OUTPUT:
Sample Input:
Sample Input:
99
- 背包问题start...: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背包和完全背包问题
- windows bat
- Burp Suite Walkthrough
- Tempter of the bone
- EAS 如何设置快捷键 弹出窗口
- JMX-Notification的使用(三)
- 背包问题start...:0-1背包
- 无法在web服务器上启动调试。调试失败,因为没有启用集成windows身份验证
- HashMap和Hashtable的区别
- Google七夕情人节Doodle背后技术揭秘
- linux物理地址扩展PAE
- Windows XP 搭建PPPoE服务器&使用
- c# 怎么动态修改webservice的地址和端口 动态修改配置文 静态修改方式
- NJUST1712(形成三角形面积为整数的个数)
- PHP远程连接oracle