码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划(一)01背包问题

时间:2015-06-16 14:20:17      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

有编号分别为a,b,c,d,e的五件物品,它们的重量分别是2,2,6,5,4,它们的价值分别是6,3,5,4,6,现在给你个承重为10的背包,如何让背包里装入的物品具有最大的价值总和?

 

状态转换方程 f[i,j] = Max{ f[i-1,j-Wi]+Pi( j >= Wi ),  f[i-1,j] }

技术分享
 1 import java.util.Arrays;
 2 
 3 public class Dp {
 4     public static void main(String[] args) {
 5 
 6         int[] weight = { 2, 2, 6, 5, 4 }; // 物品重量
 7         int[] value = { 6, 3, 5, 4, 6 }; // 物品价值
 8         int content = 10; // 背包容量
 9         int[][] ans = new int[11][11];// 数组记录
10 
11         for (int c = 1; c <= content; c++) {
12             for (int j = weight.length - 1; j >= 0; j--) {
13                 if (c - weight[j] < 0)
14                     ans[j][c] = ans[j + 1][c];
15                 else
16                     ans[j][c] = Math.max(ans[j + 1][c - weight[j]] + value[j],
17                             ans[j + 1][c]);
18             }
19         }
20         System.out.println("背包放入总价值最大为:" + ans[0][10]);
21         int[] save = { 0, 0, 0, 0, 0 }; // 是否放入
22         for (int i = 0; i <= weight.length - 1; i++) {
23             if (ans[i][content] - value[i] == ans[i + 1][content - weight[i]]) {
24                 save[i] = 1;
25                 content = content - weight[i];
26             }
27         }
28         System.out.println("放入哪些物品:" + Arrays.toString(save));
29 
30     }
31 }
View Code

测试结果:

背包放入总价值最大为:15
放入哪些物品:[1, 1, 0, 0, 1]

 

动态规划之01背包问题 容易的讲解在这里 :http://blog.csdn.net/mu399/article/details/7722810

动态规划形象生动的讲解在这里:http://www.cnblogs.com/sdjl/articles/1274312.html

动态规划(一)01背包问题

标签:

原文地址:http://www.cnblogs.com/AloneAli/p/4580461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!