背包算法

public class PackageProblem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int totalTime = scanner.nextInt();
        int amount = scanner.nextInt();
        int[] time = new int[amount];
        int[] value = new int[amount];
        for (int i = 0; i < amount; i++) {
            time[i] = scanner.nextInt();
            value[i] = scanner.nextInt();
        }
        int[][] arr = new int[amount+1][totalTime+1];
        for (int j = 0; j <= totalTime; j++){
            for (int i = 0; i <= amount; i++){
                if(i == 0 || j==0){
                    arr[i][j] = 0;
                }else{
                  if(time[i-1] > j){
                      arr[i][j] = arr[i-1][j];
                  }else{
                      arr[i][j] = Math.max(arr[i-1][j], value[i-1] + arr[i-1][j-time[i-1]]);
                  }
                }
            }
        }
        System.out.println(arr[amount][totalTime]);
        scanner.close();
    }
}

思路:动态规划,背包能装的重量从1开始慢慢增加,每个重量下装的物品,一件一件往里放。每次选取最优价值。

你可能感兴趣的:(算法)