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