3 条题解

  • 0
    @ 2023-12-14 0:24:29

    正常01背包写法

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int M = sc.nextInt(), N =sc.nextInt();
            int[] W = new int[N];
            int[] C = new int[N];
            for (int i = 0; i < N; i++) {
                W[i] = sc.nextInt();
                C[i] = sc.nextInt();
            }
            int[][] bag = new int[N][M+1];
    
            for(int i = 0; i < N; i++){
                for (int j = M; j >= 1; j--) {
                    if(i == 0){
                        if(j >= W[i]){
                            bag[i][j] = bag[i][j-W[i]] + C[i];
                        }else bag[i][j] = bag[i][j-1];
                    }else if(j >= W[i]){
                        bag[i][j] = Math.max(bag[i-1][j],bag[i-1][j-W[i]] + C[i]);
                    }else bag[i][j] = Math.max(bag[i-1][j],bag[i][j-1]);
                }
            }
            System.out.println(bag[N-1][M]);
    
    
    
        }
    }
    

    信息

    ID
    574
    时间
    1000ms
    内存
    64MiB
    难度
    4
    标签
    (无)
    递交数
    43
    已通过
    21
    上传者