[java]
public static void main(String[] args)
{
System.out.println("物品重量:" + Arrays.toString(weight));
System.out.println("物品价值:" + Arrays.toString(value));
/**
* 按单位重量价值valueOfWeight[i]=value[i]/weight[i]降序排列
*/
// 单位重量价值
double[] valueOfWeight = new double[number];
// 索引
int[] index = new int[number];
DecimalFormat decimalFormat = new DecimalFormat("####.##");
for (int i = 0; i < number; i++)
{
valueOfWeight[i] = Double.valueOf(decimalFormat.format((double) value[i] / (double) weight[i]));
}
for (int i = 0; i < number; i++)
{
index[i] = i;
}
System.out.println("排序前单位重量价值:" + Arrays.toString(valueOfWeight));
System.out.println("排序前索引:" + Arrays.toString(index));
double temp = 0;
int x = 0;
for (int i = 0; i < number - 1; i++)
{
for (int j = i + 1; j < number; j++)
{
if (valueOfWeight[i] < valueOfWeight[j])
{
temp = valueOfWeight[i];
valueOfWeight[i] = valueOfWeight[j];
valueOfWeight[j] = temp;
x = index[i];
index[i] = index[j];
index[j] = x;
}
}
}
System.out.println("-------------------");
System.out.println("排序后单位重量价值:" + Arrays.toString(valueOfWeight));
System.out.println("排序后索引:" + Arrays.toString(index));
for (int i = 0; i < number; i++)
{
weightSort[i] = weight[index[i]];
valueSort[i] = value[index[i]];
}
System.out.println("排序后物品重量:" + Arrays.toString(weightSort));
System.out.println("排序后物品价值:" + Arrays.toString(valueSort));
setGoods(totle, 0);
System.out.println("--------结果-------");
System.out.println("物品重量:" + Arrays.toString(weightSort));
System.out.println("物品价值:" + Arrays.toString(valueSort));
System.out.println("物品数量:" + Arrays.toString(counter));
int result = 0;// 背包物品总价值
for (int i = 0; i < number; i++)
{
if (counter[i] != 0)
{
result = result + valueSort[i] * counter[i];
}
}
System.out.println("背包中物品总价值:" + result);
}