Java实现的01背包问题动态规划算法由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“动态规划算法背包问题”。
import java.util.Scanner;
public cla Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int Num = sc.nextInt();//物品的个数(编号从0开始),不超过100
int Col = sc.nextInt();//背包容量,不超过1000
int[] d = new int[Col+1];//表示前i个(会不断更新)物品装到剩余容量为j的背包中的最大重量,当然不包括编号为i的物品
int Ver = 0;
int Weight = 0;
while(sc.hasNext()){
for(int i=0;i
//不需要用数组存储体积和价值了,边读入边处理数据即可
if(i >0){
Ver = sc.nextInt();
Weight = sc.nextInt();
}
for(int j=Col;j>=0;j--){
if(i>0 && j>=Ver)
}
} }
d[j] =(d[j] > d[j-Ver]+Weight)? d[j] : d[j-Ver]+Weight;
} } System.out.println(d[Col]);break;