package com.hhmstu.Algorithmdesignandanalysis.Dynamicprogramming; public class Backpack_01 { public static void main(String[] args) { int n = 5; int c = 20; int w[] = {0, 15, 10, 2, 5, 8}; int v[] = {0, 16, 10, 6, 7, 9}; int m[][] = new int[6][21]; int max = BP(n, c, w, v, m); System.out.println("最大商品价值为:" + max + "元!"); for (int i = 0; i < 6; i++) { for (int j = 0; j < 21; j++) { System.out.print(m[i][j] + "\t"); if ((j + 1) % 21 == 0) { System.out.println(); } } } } public static int BP(int n, int c, int[] w, int[] v, int m[][]) { //初始化二维表 for (int i = 0; i < c + 1; i++) { m[0][i] = 0; } for (int i = 0; i < n + 1; i++) { m[i][0] = 0; } //根据递推表达式一行一行地填表 for (int i = 1; i < n + 1; i++) { for (int j = 1; j < c + 1; j++) { if (j < w[i]) { m[i][j] = m[i - 1][j]; } else { m[i][j] = max(m[i - 1][j], m[i - 1][j - w[i]] + v[i]); } } } //返回最优值 return m[n][c]; } public static int max(int a, int b) { int max = 0; if (a > b) { max = a; } else { max = b; } return max; } }
0-1背包问题与动态规划
最新推荐文章于 2024-07-22 14:15:06 发布