Knapsack01
Wed Nov 06 2024 16:31:57 GMT+0000 (Coordinated Universal Time)
Saved by @signin
import java.util.Scanner; public class Knapsack01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the number of items System.out.print("Enter the number of items: "); int n = scanner.nextInt(); // Input weights and values of items int[] weights = new int[n]; int[] values = new int[n]; System.out.println("Enter the weights of the items:"); for (int i = 0; i < n; i++) { weights[i] = scanner.nextInt(); } System.out.println("Enter the values of the items:"); for (int i = 0; i < n; i++) { values[i] = scanner.nextInt(); } // Input the capacity of the knapsack System.out.print("Enter the capacity of the knapsack: "); int capacity = scanner.nextInt(); // Solve the 0/1 Knapsack problem int maxProfit = knapsack(weights, values, capacity, n); System.out.println("Maximum profit: " + maxProfit); scanner.close(); } public static int knapsack(int[] weights, int[] values, int capacity, int n) { int[][] dp = new int[n + 1][capacity + 1]; // Fill the DP table for (int i = 1; i <= n; i++) { for (int w = 1; w <= capacity; w++) { if (weights[i - 1] <= w) { // Include the item and maximize the profit dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]); } else { // Exclude the item dp[i][w] = dp[i - 1][w]; } } } // Backtrack to find the items that are included int[] solution = new int[n]; int w = capacity; for (int i = n; i > 0 && w > 0; i--) { // If the item is included in the optimal solution if (dp[i][w] != dp[i - 1][w]) { solution[i - 1] = 1; // Mark as included w -= weights[i - 1]; } else { solution[i - 1] = 0; // Mark as not included } } // Print the solution array System.out.print("Solution array (1 means included, 0 means not included): "); for (int i = 0; i < n; i++) { System.out.print(solution[i] + " "); } System.out.println(); return dp[n][capacity]; } }
Comments