希望多学学早日能做出来 dp的题
?
好朴素 三层for?
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int v = scan.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for(int i = 1; i <= n; i ++){
a[i] = scan.nextInt();
b[i] = scan.nextInt();
}
int[][] dp = new int[n + 1][v + 1];
for(int i = 1; i <= n; i ++){
for(int j = 0; j <= v; j ++){
for(int k = 0; k * a[i] <= j; k ++){
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * a[i]] + k * b[i]);
}
}
}
System.out.println(dp[n][v]);
}
}
稍稍优化一下
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int v = scan.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for(int i = 1; i <= n; i ++){
a[i] = scan.nextInt();
b[i] = scan.nextInt();
}
int[][] dp = new int[n + 1][v + 1];
for(int i = 1; i <= n; i ++){
for(int j = 0; j <= v; j ++){
if(a[i] <= j){
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - a[i]] + b[i]);
}else{
dp[i][j] = dp[i - 1][j];
}
}
}
System.out.println(dp[n][v]);
}
}
|