背包问题九讲_背包问题
背包問題九講
我發(fā)現(xiàn)背包問題既棘手又有趣。 我敢肯定,如果您正在訪問此頁面,您已經(jīng)知道了問題說明,但是只是為了完成本章:
問題:
給定一個最大容量為W和N的背包,每個背包都有自己的值和重量,將它們放入背包中,使最終內容物具有最大值。 kes!
- 鏈接到Wiki中的問題頁面
這是解釋問題的一般方法-考慮一個小偷進入家中搶劫,他背著背包。 家里有固定數(shù)量的物品-每個物品都有自己的重量和價值-珠寶首飾,重量和重量比桌子高,價值少,但重量重。 為了給火上加油,小偷有一個老式的背包,容量有限。 顯然,他不能將桌子分成兩半,也不能將珠寶分成3/4分。 他要么接受要么離開。
范例:
Knapsack Max weight : W = 10 (units)Total items : N = 4Values of items : v[] = {10, 40, 30, 50}Weight of items : w[] = {5, 4, 6, 3}粗略看一下示例數(shù)據(jù)可知,在最大權重為10的情況下,我們可以容納的最大值為50 + 40 = 90(權重為7)。
方法:
最佳解決方法是使用動態(tài)編程-解決較小的背包問題,然后將其擴展為較大的問題。
讓我們構建一個名為V(值數(shù)組)的Item x權重數(shù)組:
V[N][W] = 4 rows * 10 columns此矩陣中的每個值代表一個較小的背包問題。
基本案例1 :讓我們以第0列為例。 這僅意味著背包的容量為0。 你能在他們身上抱什么? 沒有。 因此,讓我們用0填充它們。
基本情況2 :讓我們以0行為例。 這僅表示房子中沒有物品。 如果沒有物品,您在背包里會做什么? 沒事了! 全零。
解:
我們應檢查以下情況。
為什么要上一行?
僅僅是因為權重為4的前一行本身是一個較小的背包解決方案,它給出了該權重在該點之前可以累積的最大值(遍歷所有項目)。
舉例來說,
計算如下:
兩者之間的最大值為40(0和40)。
因此,計算公式為:
10比50 = 50。
解決所有這些較小的問題后,我們只需要返回權重為10的V [N] [W] –項目4的值:
復雜
分析解決方案的復雜性非常簡單。 我們只是在N => O(NW)的循環(huán)中有一個W循環(huán)
實現(xiàn)方式:
這是Java中的強制性實現(xiàn)代碼:
class Knapsack {public static void main(String[] args) throws Exception {int val[] = {10, 40, 30, 50};int wt[] = {5, 4, 6, 3};int W = 10;System.out.println(knapsack(val, wt, W));}public static int knapsack(int val[], int wt[], int W) {//Get the total number of items. //Could be wt.length or val.length. Doesn't matterint N = wt.length; //Create a matrix. //Items are in rows and weight at in columns +1 on each sideint[][] V = new int[N + 1][W + 1]; //What if the knapsack's capacity is 0 - Set//all columns at row 0 to be 0for (int col = 0; col <= W; col++) {V[0][col] = 0;}//What if there are no items at home. //Fill the first row with 0for (int row = 0; row <= N; row++) {V[row][0] = 0;}for (int item=1;item<=N;item++){//Let's fill the values row by rowfor (int weight=1;weight<=W;weight++){//Is the current items weight less//than or equal to running weightif (wt[item-1]<=weight){//Given a weight, check if the value of the current //item + value of the item that we could afford //with the remaining weight is greater than the value //without the current item itselfV[item][weight]=Math.max (val[item-1]+V[item-1][weight-wt[item-1]], V[item-1][weight]);}else { //If the current item's weight is more than the //running weight, just carry forward the value //without the current itemV[item][weight]=V[item-1][weight];}}}//Printing the matrixfor (int[] rows : V) {for (int col : rows) {System.out.format("%5d", col);}System.out.println();}return V[N][W];}}翻譯自: https://www.javacodegeeks.com/2014/07/the-knapsack-problem.html
背包問題九講
總結
以上是生活随笔為你收集整理的背包问题九讲_背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机主题图片(手机主题图片壁纸)
- 下一篇: 海尔电脑都有哪些系列(海尔电脑都有哪些系