0-1背包问题(递推)java

import java.util.Scanner;

public class demo2 {
  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];
    int[] w = new int[n];
    int[][] p = new int[n + 1][V + 1];
    for (int i = 0; i < n; i++) {
      v[i] = in.nextInt();
      w[i] = in.nextInt();
    }
    for (int i = 0; i < p.length; i++) {
      for (int j = 0; j < p[i].length; j++) {
//        构造表格
        if (i == 0 || j == 0) {
          p[i][j] = 0;
          continue;
        }
//        如果放不进去,就不放,就等于上一次的结果
        if (j - v[i - 1] < 0) {
          p[i][j] = p[i - 1][j];
          continue;
        }
        p[i][j] = Math.max(p[i - 1][j - v[i - 1]] + w[i - 1], p[i - 1][j]);
      }
    }
    System.out.println(p[n][V]);
  }
}

你可能感兴趣的:(0-1背包问题(递推)java)