publicclassMain{ publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int V = sc.nextInt(); int[] v=newint[N+1]; int[] w=newint[N+1]; for(int i=1;i<=N;i++){ v[i] = sc.nextInt(); w[i] = sc.nextInt(); } //dp1(v,w, N, V);// 无优化数组 dp2(v,w, N, V);// 优化为1维数组 } publicstaticvoiddp1(int[] v,int [] w, int N, int V){ int[][] dp = newint[N+1][V+1]; dp[0][0]= 0; for(int i=1;i<=N;i++){ for(int j=1;j<=V;j++){ if(j<v[i]) dp[i][j]=dp[i-1][j]; else{ dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-v[i]]+w[i]); } } } System.out.println(dp[N][V]); } publicstaticvoiddp2(int[] v,int [] w, int N, int V){ int[] dp = newint[V+1]; dp[0]= 0; for(int i=1;i<=N;i++){ for(int j=V;j>=v[i];j--){ // if(j<v[i]) dp[j]=dp[j]; // else{ dp[j] = Math.max(dp[j], dp[j-v[i]]+w[i]); // } } } System.out.println(dp[V]); }
}
还可以优化输入
处理数据时,我们是一个物品一个物品,一个体积一个体积的去枚举
因此可以不必开两个数组去记录体积和价值,而是边输入边处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassMain{ publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int V = sc.nextInt(); int[] f=newint[V+1]; for(int i=1;i<=N;i++){ int v = sc.nextInt(); int w = sc.nextInt(); for(int j = V;j >= v;j--){ f[j] = Math.max(f[j], f[j-v]+w); } } System.out.println(f[V]); } }
publicclassMain{ publicstaticvoidmain(String[] args){ Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int V = scanner.nextInt();
int[] f = newint[110];
for (int i = 0; i < N; i++) { int v = scanner.nextInt(); int w = scanner.nextInt(); int s = scanner.nextInt(); for (int j = V; j >= 0; j--) { for (int k = 1; k <= s && k * v <= j; k++) { f[j] = Math.max(f[j], f[j - k * v] + k * w); } } }