使用java语言解决基于回溯法的0-1背包问题,记录物品选择结果、程序运行时间、访问节点数
时间: 2023-07-15 13:10:53 浏览: 96
以下是基于回溯法的0-1背包问题的Java代码,其中记录了物品选择结果、程序运行时间和访问节点数:
```java
import java.util.*;
public class KnapsackProblemBacktracking {
private static int capacity;
private static int[] weights;
private static int[] values;
private static boolean[] solution;
private static int maxProfit;
private static int nodeCount;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the capacity of the knapsack: ");
capacity = scanner.nextInt();
System.out.print("Enter the number of items: ");
int n = scanner.nextInt();
weights = new int[n];
values = new int[n];
solution = new boolean[n];
System.out.println("Enter the weight and value of each item:");
for (int i = 0; i < n; i++) {
weights[i] = scanner.nextInt();
values[i] = scanner.nextInt();
}
long startTime = System.currentTimeMillis();
nodeCount = 0;
knapsack(0, 0, 0);
long endTime = System.currentTimeMillis();
System.out.println("\nMaximum profit: " + maxProfit);
System.out.println("Selected items (1 if selected, 0 otherwise):");
for (int i = 0; i < n; i++) {
System.out.print((solution[i] ? 1 : 0) + " ");
}
System.out.println("\nTotal time taken: " + (endTime - startTime) + "ms");
System.out.println("Total nodes visited: " + nodeCount);
scanner.close();
}
private static void knapsack(int i, int profit, int weight) {
nodeCount++;
if (weight <= capacity && profit > maxProfit) {
maxProfit = profit;
for (int j = 0; j < solution.length; j++) {
solution[j] = (j == i) || solution[j];
}
}
if (i == weights.length || weight >= capacity) {
return;
}
knapsack(i + 1, profit + values[i], weight + weights[i]);
knapsack(i + 1, profit, weight);
}
}
```
在此代码中,`knapsack` 方法实现了回溯算法。其中,`i` 表示当前考虑到的物品编号,`profit` 表示当前背包中物品的总价值,`weight` 表示当前背包中物品的总重量。`nodeCount` 记录访问的节点数,`maxProfit` 记录当前最大价值,`solution` 记录选中的物品。
程序输入背包容量、物品个数、每个物品的重量和价值,然后计算最大价值、选中的物品、程序运行时间和访问节点数。
阅读全文