当前位置:网站首页>Detailed explanation of knapsack problem

Detailed explanation of knapsack problem

2022-07-23 14:09:00 qq_ twenty-five million four hundred and twenty-seven thousand

 Insert picture description here
Focus on mastering 01 Backpack and full backpack

01 Backpack details :
https://blog.csdn.net/u013445530/article/details/40210587
dp[i][j]=max(dp[i-1][j], dp[i-1][j - w[i]] + v[i]);
explain :1) Put in the i An object , be dp[i][j]=dp[i-1][j - w[i]] + v[i];
2) Don't put it in the second i An object :dp[i][j]=dp[i-1][j];

Two dimensional array

for(int i = 1; i <= n; i++)
    {
    
        for(int j = 0; j <= W; j++)
        {
    
            if(j < w[i])    dp[i][j]  = dp[i-1][j];
            else dp[i][j] =  max(dp[i-1][j], dp[i-1][j - w[i]] + v[i]);
        }
    }

To a one-dimensional array ,dp[i][j] As dp[j].
dp[i][j] By dp[i-1][j] and dp[i-1][j-w[i]] Derived from , be dp[j] from dp[j] and dp[j - w[i]] Derived from .

for(int i = 1; i <= n; i++)
    {
    
     for(int j = W; j >= w[i]; j--)
        	dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
    }

The following figure helps to understand why it is necessary to reverse the order when changing to one dimension :
Traverse horizontally , To make sure dp[j - w[i]] What is kept is dp[i-1][j - w[i]] Value , First i=1 when , Traverse from right to left

![ Figure helps to understand why turning to one dimension is in reverse order ](https://img-blog.csdnimg.cn/a62475c8e83d4bfd94ca013c7a28198b.jpeg

Here is traversal in reverse order , If you don't traverse back in reverse order, it will cause an item to be selected repeatedly .
Why repeat selection ? The maximum value of the back is from the value of the front , The first value is selected i Item , The following capacity can still be selected i Item , Lead to i Items selected repeatedly .
``
However, the complete knapsack problem happens to be an item n Pieces of , It just needs to be selected repeatedly , So the ergodic order is positive ergodic , as follows :

for(int i = 1; i <= n; i++)
    {
    
     for(int j = w[i]; j <= W; j++)
        	dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
    }
原网站

版权声明
本文为[qq_ twenty-five million four hundred and twenty-seven thousand ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230748045584.html