简述:
一个背包,总载重量限定
提供各种质量及相应价值的物品, 提供一个价值最优的装包选择
参考: http://www.importnew.com/13072.html
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script type = "text/javascript">
var total = 10;
var OBJ_NUM = 4;
var weights = [];
var values = [];
var matrix = [];
/**** init weights ****/
weights.push(0); // defualt 0
weights.push(5);
weights.push(4);
weights.push(6);
weights.push(3);
/**** init values ****/
values.push(0); // default 0
values.push(10);
values.push(40);
values.push(30);
values.push(50);
/** init row 0 value as ZERO **/
for(var i=0; i<(OBJ_NUM+1)*(total+1); i++)
matrix.push(0);
var X_WIDTH = total + 1;
/**** calculate ****/
for(var y=1; y<=OBJ_NUM; y++){
for(var x=1; x<=total; x++){
if(x >= weights[y]){
// 添加了当前物品的价值
var addedValue = matrix[(y - 1) * X_WIDTH + (x - weights[y])] + values[y];
matrix[y*X_WIDTH + x] = Math.max(addedValue,
matrix[(y - 1) * X_WIDTH + x]);
}else{
matrix[y*X_WIDTH + x] = matrix[(y-1) * X_WIDTH + x];
}
}
}
for(var y=1; y<=OBJ_NUM; y++){
for(var x=1; x<=total; x++){
document.write(matrix[y*X_WIDTH + x] + "\t");
}
document.write("</br>");
}
document.write("最优解(背包的总value值最大)为: " + matrix[(OBJ_NUM+1)*X_WIDTH - 1]);
</script>
</head>
</html>
输出:
下面是Java的实现
package com.anialy.test.packnage;
/**
* Package: com.anialy.test.packnage
* 参考: http://www.importnew.com/13072.html
*
*/
public class PackageProblem {
// 物品数量
private static final int NUM = 4;
// 物品质量, 0为占位符
private static int wt[] = new int[]{0, 5, 4, 6, 3};
// 物品价值, 0为占位符
private static int val[] = new int[]{0, 10, 40, 30, 50};
// 背包容量
private static final int TOTAL = 10;
private static final int X_WIDTH = TOTAL + 1;
private static int process(){
int calc[] = new int[X_WIDTH * (NUM + 1)];
for(int y=0; y<=NUM; y++)
for(int x=0; x<=TOTAL; x++)
calc[y*X_WIDTH + x] = 0;
for(int y=1; y<=NUM; y++){
for(int x=1; x<=TOTAL; x++){
if(x >= wt[y]){
calc[y*X_WIDTH + x] = Math.max(
val[y] + calc[(y-1)*X_WIDTH + (x-wt[y])]
, calc[(y-1)*X_WIDTH + x]);
}else{
calc[y*X_WIDTH + x] = calc[(y-1)*X_WIDTH + x];
}
}
}
for(int y=1; y<=NUM; y++){
for(int x=1; x<=TOTAL; x++){
System.out.format("%3d ", calc[y*X_WIDTH + x]);
}
System.out.printf("\n");
}
// 返回最后一个
return calc[(NUM+1)*X_WIDTH - 1];
}
public static void main(String[] args) {
System.out.printf("\n optimum value: %d", process());
}
}