public class KP_01 { static class Item implements Comparable<Item> { int weight; int value; double density; public Item(int weight, int value) { this.weight = weight; this.value = value; density = (double) value / weight; } @Override public int compareTo(Item o) { return Double.compare(o.density, density); } } public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("knapPI_1_500_1000_1")); //该文件放在Java的包中 int n = scanner.nextInt(); int capacity = scanner.nextInt(); Item[] items = new Item[n]; for (int i = 0; i < n; i++) { items[i] = new Item(scanner.nextInt(), scanner.nextInt()); } Arrays.sort(items); int value = 0; int weight = 0; for (int i = 0; i < n && weight < capacity; i++) { int remainingCapacity = capacity - weight; int selectedWeight = Math.min(items[i].weight, remainingCapacity); value += selectedWeight * items[i].density; weight += selectedWeight; } System.out.printf("Total value: %d\n", value); } }这段代码是用贪心法求解01背包问题,请将其改成用动态规划方法解决01背包问题
时间: 2024-01-11 15:03:31 浏览: 138
以下是使用动态规划方法解决01背包问题的Java代码,可以参考:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class KP_01_DP {
static class Item {
int weight;
int value;
public Item(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("knapPI_1_500_1000_1"));
int n = scanner.nextInt();
int capacity = scanner.nextInt();
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item(scanner.nextInt(), scanner.nextInt());
}
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= capacity; j++) {
if (items[i - 1].weight > j) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - items[i - 1].weight] + items[i - 1].value);
}
}
}
System.out.printf("Total value: %d\n", dp[n][capacity]);
}
}
```
该程序假设文件“knapPI_1_500_1000_1”包含以下格式的数据:
```
物品数量 背包容量
物品1重量 物品1价值
物品2重量 物品2价值
...
```
程序读取数据并计算01背包问题的最大价值,然后输出该值。
阅读全文