AcWing 3. 完全背包问题(java)

希望多学学早日能做出来 dp的题

AcWing 3. 完全背包问题(java)_第1张图片

AcWing 3. 完全背包问题(java)_第2张图片 

好朴素 三层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]);
        
    }
}

你可能感兴趣的:(和y总约会❤️,java,acwing,动态规划,完全背包)