From 00c236bc8a1c2baf6dc626117b4d06c01865cfe9 Mon Sep 17 00:00:00 2001 From: real-lin-zhu Date: Sat, 10 May 2025 17:09:52 +0100 Subject: [PATCH 1/4] Create 9.6.md --- hw1/LinZhu/9.6.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 hw1/LinZhu/9.6.md diff --git a/hw1/LinZhu/9.6.md b/hw1/LinZhu/9.6.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/hw1/LinZhu/9.6.md @@ -0,0 +1 @@ + From 3c051534afbde112f7430fcd43a4ac5f14b33207 Mon Sep 17 00:00:00 2001 From: real-lin-zhu Date: Sat, 10 May 2025 17:10:25 +0100 Subject: [PATCH 2/4] Rename 9.6.md to 9.6 --- hw1/LinZhu/{9.6.md => 9.6} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename hw1/LinZhu/{9.6.md => 9.6} (100%) diff --git a/hw1/LinZhu/9.6.md b/hw1/LinZhu/9.6 similarity index 100% rename from hw1/LinZhu/9.6.md rename to hw1/LinZhu/9.6 From 50c34a4d154cd132f1bb8aafdf51f86d903aa12e Mon Sep 17 00:00:00 2001 From: real-lin-zhu Date: Sat, 10 May 2025 17:59:00 +0100 Subject: [PATCH 3/4] Add files via upload --- hw1/LinZhu/knapsack 9.6.py | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 hw1/LinZhu/knapsack 9.6.py diff --git a/hw1/LinZhu/knapsack 9.6.py b/hw1/LinZhu/knapsack 9.6.py new file mode 100644 index 0000000..5f39cd1 --- /dev/null +++ b/hw1/LinZhu/knapsack 9.6.py @@ -0,0 +1,40 @@ +def knapsack_value_dp(weights, values, capacity): + l = len(weights) + Vmax = max(values) + total_value = sum(values) + + # Initialize DP table with infinity + INF = float('inf') + dp = [[INF] * (total_value + 1) for _ in range(l + 2)] + + # Base case: 0 value requires 0 weight + dp[l + 1][0] = 0 + + # Build table from item l down to 1 + for j in range(l, 0, -1): + for v in range(total_value + 1): + # Option 1: exclude item j-1 + dp[j][v] = dp[j + 1][v] + # Option 2: include item j-1, if value allows + if v >= values[j - 1]: + dp[j][v] = min(dp[j][v], weights[j - 1] + dp[j + 1][v - values[j - 1]]) + + # Find the maximum value v such that dp[1][v] <= capacity + for v in range(total_value, -1, -1): + if dp[1][v] <= capacity: + return v # maximum value achievable within capacity + + return 0 # no items can be included + +# Example usage +weights = [2, 3, 4, 5] +values = [3, 4, 5, 6] +capacity = 7 + +result = knapsack_value_dp(weights, values, capacity) +print("Maximum value within capacity:", result) + + +#If P = NP, the NP problem will be solved in polynomial time, +#O(l^2 * v_max) where v_max is a constant, so bits required for v_max is log2(v_max), which is not a polynomial +#P != NP \ No newline at end of file From 2241e9117ceecb4e0dd7f13b642b9008a07dddb5 Mon Sep 17 00:00:00 2001 From: real-lin-zhu Date: Sat, 10 May 2025 18:05:03 +0100 Subject: [PATCH 4/4] Update 9.6 --- hw1/LinZhu/9.6 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hw1/LinZhu/9.6 b/hw1/LinZhu/9.6 index 8b13789..c82a2b3 100644 --- a/hw1/LinZhu/9.6 +++ b/hw1/LinZhu/9.6 @@ -1 +1 @@ - +code is in the .py file with explaination