動態規劃-揹包問題
阿新 • • 發佈:2020-07-28
題目網站:https://www.acwing.com/problem/content/description/2/
dp[i][j]表示1前i件物品放入體積為j的揹包裡可以獲得的最大價值。
1. 0-1揹包(AcWing2)
import java.util.Scanner; public class Main{ public static void main(String[] args) throws Exception { Scanner reader = new Scanner(System.in); int N = reader.nextInt(); int V = reader.nextInt(); int[] v = new int[N + 1] ; int[] w = new int[N + 1] ; for (int i=1 ; i <= N ; i++){ v[i] = reader.nextInt(); w[i] = reader.nextInt(); } reader.close() ; int[][] dp = new int[N+1][V+1]; dp[0][0] = 0; for(int i = 1; i <= N; i++){ for(int j = 0; j <= V; j++){ if(j >= v[i]){ dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-v[i]] + w[i]); }else{ dp[i][j] = dp[i-1][j]; } } } System.out.println(dp[N][V]); } }
2. 完全揹包(AcWing3)
import java.util.Scanner; public class Main{ public static void main(String[] args) throws Exception { Scanner reader = new Scanner(System.in); int N = reader.nextInt(); int V = reader.nextInt(); int[] v = new int[N + 1] ; int[] w = new int[N + 1] ; for (int i=1 ; i <= N ; i++){ v[i] = reader.nextInt(); w[i] = reader.nextInt(); } reader.close() ; int[][] dp = new int[N+1][V+1]; dp[0][0] = 0; for(int i = 1; i <= N; i++){ for(int j = 0; j <= V; j++){ if(j >= v[i]){ //此處是和0-1揹包問題唯一的不同之處,參考了《演算法筆記》上的內容 dp[i][j] = Math.max(dp[i-1][j], dp[i][j-v[i]] + w[i]); }else{ dp[i][j] = dp[i-1][j]; } } } System.out.println(dp[N][V]); } }