AcWing 3. 完全背包问题 - Java(逆向)
原题链接
简单
作者:
hiboy
,
2020-08-02 11:37:55
,
所有人可见
,
阅读 2
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int V = in.nextInt();
int[] v = new int[N+1];
int[] w = new int[N+1];
for(int i = 1; i <= N; i++){
v[i] = in.nextInt();
w[i] = in.nextInt();
}
System.out.println(solution(N, V, v, w));
}
public static int solution(int n, int v, int[] va, int[] wa){
int[] dp = new int[v+1];
dp[0] = 0;
for(int i = 1; i <= n; i++){
for(int j = v; j >= 1; j--){//逆向推
for(int k = 0; k <= j/va[i]; k++){
dp[j] = Math.max(dp[j], dp[j-k*va[i]]+k*wa[i]);
}
}
}
return dp[v];
}
}