package dp_bag;
/**
* 有编号分别为a,b,c,d,e的五件物品,它们的重量分别是2,2,6,5,4,
* 它们的价值分别是6,3,5,4,6,现在给你个承重为10的背包,
* 如何让背包里装入的物品具有最大的价值总和?
*
* 01背包的状态转换方程 f[i,j] = Max{ f[i-1,j-Wi]+Pi( j >= Wi ), f[i-1,j] }
* @author Administrator
*
*/
public class Bag {
private static char [] bags = {'e','d','c','b','a'};
private static int [] checked_bags = new int[5];
private static int [] volume = {4,5,6,2,2};
private static int [] price = {6,4,5,3,6};
private static int capacity = 10;
public static void main(String[] args) {
// TODO Auto-generated method stub
int k = f(4, capacity);
System.out.println(k);
print_bags();
// print_value();
}
public static int f(int i, int j) {
if(i<0)
return 0;
if(j<=0)
return 0;
//不装入
int a = f(i-1,j);
//装入
int b;
if(j-volume[i]>=0)//装得下
b = f(i-1,j-volume[i]) + price[i];
else//装不下
b = 0;
//记录选择了哪些背包
if(a>b)
checked_bags[i] = 0;
else
checked_bags[i] = 1;
return a>b?a:b;
}
public static void print_value(){
for(int i=0; i<5; i++){
for(int j=1; j<11; j++){
System.out.print(f(i,j) + " ");
}
System.out.println();
}
}
public static void print_bags(){
for(int i=0; i<5; i++){
if(checked_bags[i]==1){
System.out.print(bags[i]+" ");
}
}
}
}
很简洁的代码,教程可参考
点击打开链接