package Sjfx;
import java.util.Arrays;
import java.util.Scanner;
public class Beibao {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("物品数:");
int n = sc.nextInt();
float[] w = new float[n];
float[] v = new float[n];
float[] x = new float[n];
System.out.println("背包容量:");
float c = sc.nextFloat();
System.out.println("每个物品重量:");
for (int i = 0; i < n; i++) {
w[i] = sc.nextFloat();
}
System.out.println("每个物品价值:");
for (int i = 0; i < n; i++) {
v[i] = sc.nextFloat();
}
float opt = knapsack(c, w, v, x);
System.out.println("最大价值:" + opt);
}
public static float knapsack(float c, float[] w, float[] v, float[] x) {
int n = v.length;
Element[] d = new Element[n]; // 物品数组
for (int i = 0; i < n; i++) // 数组初始化
d[i] = new Element(w[i], v[i], i);
Arrays.sort(d); // 物品按照单位价值排序
int i;
float opt = 0; // 当前装入背包的价值
for (i = 0; i < n; i++)
x[i] = 0;
for (i = 0; i < n; i++) { // 扫描物品
if (d[i].w > c) // d[i].w表示扫描到第i个物品时取出其重量
break; // 物品i装不下时跳出
x[d[i].i] = 1; // 物品i装入背包
opt += d[i].v;
c -= d[i].w; // 背包当前容量
}
if (i < n) { // 背包未装满还有剩余物品时
x[d[i].i] = c / d[i].w; // 装入部分物品i
opt += x[d[i].i] * d[i].v;
}
System.out.print("此时包中装了");
for (int j = 0; j < n; j++) {
if (x[j] != 0) {
System.out.print("第" + (j + 1) + "件和" + x[j] + "的");
}
}
System.out.println("");
return opt;
}
public static class Element implements Comparable<Beibao.Element> {
float v;
float w;
int i;
public Element(float w, float v, int i) {
this.w = w;
this.v=v;
this.i = i;
}
@Override
public int compareTo(Beibao.Element o) {
if (this.w < o.w)
return -1;
else if (this.w == o.w)
return 0;
else
return 1;
}
}
}