XhhDream

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

给定一组物品,每种物品都有自己的重量和价格,在限定的总重量内,我们如何选择,才能使得物品的总价格最高。

使用动态规划算法解答

 1 import java.util.Scanner;
 2 
 3 public class 一维数组解背包问题 {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         int W = sc.nextInt(), n = sc.nextInt();//W=背包容量   n=物品数量
 7         int[] c = new int[n + 1], w = new int[n + 1], f = new int[W + 1];
 8         for (int i = 1; i <= n; i++) {
 9             c[i] = sc.nextInt();
10             w[i] = sc.nextInt();
11         }
12         for (int i = 1; i <= n; i++) {
13             for (int j = W; j >= 0; j--) {
14                 if (c[i] <= j)
15                     f[j] = Math.max(f[j], f[j - c[i]] + w[i] * c[i]);
16             }
17         }
18          for (int i = 0; i < f.length; i++) {
19          System.out.print(f[i] + " ");
20          }
21     }
22 }

 

posted on 2016-08-24 17:43  XhhDream  阅读(167)  评论(0编辑  收藏  举报