oj dynamic programming algorithm ---- ---- knapsack problem

oj dynamic programming algorithm ---- ---- knapsack problem

1. Dynamic Programming

1.1 concept

Dynamic Programming (dynamic programming) is a branch of operations research, mathematical optimization method for solving the decision-making process (decision process)

1.2 Nature

Dynamic programming is generally used to deal with the problem of the optimal solution. Problem solving using a dynamic programming algorithm generally has optimal substructure and overlapping subproblems nature of these two factors.

<1> optimal substructure

     Optimal optimal solution by which a problem is included in the sub-problems, this property is called optimal substructure Properties 

<2> overlapping subproblems

     Recursive algorithm to solve the problem, the problem each time a child is not always new problems, some sub-problems are of iterations. This property is called proton overlap problem.

The difference between 1.3 and divide and conquer method

Dynamic programming and divide and conquer similarities, are to be broken down into several sub-problems to solve the problem. The difference, solving divide and conquer some sub-problems were double-counted many times; dynamic programming to achieve a solution to store these sub-issues to prepare for the child recurring problems, when the overlapping sub-problems, find solution has been resolved sub-problem We can avoid a lot of double counting.

1.4 Optimization

Can be optimized in consideration of the space, e.g. knapsack problem, the optimization of a two-dimensional array into two-dimensional arrays, which can then be optimized to a one-dimensional array

2. knapsack problem

2.1 knapsack problem is divided into 0/1 knapsack problem, knapsack problem completely, and multiple knapsack problem (the essential difference is the number of cases in the end max)

2.2 01 knapsack problem

Recurrence relations

① j<w(i)      V(i,j)=V(i-1,j) 

② j>=w(i)     V(i,j)=max{ V(i-1,j),V(i-1,j-w(i))+v(i) }

 Diagram

We must pay attention to the problem of initialization

 

 Space Optimization

From the above it can be seen in FIG., Each value V (i) (j) changed only with V (i-1) (x) {x: 1 ... j} related, V (i-1) (x ) i is a value stored before the cycle down;

Thus, V may be reduced to a one-dimensional array, so as to achieve the purpose of optimizing space, state transition equation is converted to  B (J) = max {B (J), B (JW (I)) + V (I)} ;

Further, the state transition equation, each derived V (i) (j) by V (i-1) (jw (i)) is derived, so the one-dimensional array to be scanned in descending order of j (Capacity to 0) , one cycle before preserved whether those values will be modified, resulting in an error.

#include <stdio.h> 
#include < String .h> int F [ 1010 ], w [ 1010 ], v [ 1010 ]; // F bearing different records the total value of the weight of the backpack, w items of different weight recorded, v recording different items of value int max ( int x, int y) { // returns the x, y is the maximum IF (X> y) return X;
     return y; 
} int main () {
     int T, m, I, J ; 
    Memset (F, 0 , the sizeof (F));   // total value is initialized to 0 
    Scanf ( " % D% D "
 

 

    
 
, & t, & m);   // Input backpack weight bearing t, the number m of articles 
    for (I = . 1 ; I <= m; I ++ ) 
        Scanf ( " % D% D " , & W [I], & V [I]) ;   // input m groups of items by weight w [i] and the value of V [I] 
    for (I = . 1 ; I <= m; I ++) {   // try placing each item 
        for (T = J; J> W = [I]; J -) { // flashback is to ensure that each article can be used once 
            F [J] = max (F [JW [I]] + V [I], F [J]);
             // in into the i-th goods back and forth, testing the total value of j different bearing weight of the backpack, improved compared to the value placed in front of if placed in the i-th item, the value of j bearing the weight of the backpack is modified, otherwise unchanged 
        } 
    } 
    printf ( " % D " , F [t]);   // output bearing the weight of the total value t of the backpack
    printf("\n");
    getch();
    return 0;
} 
After 01 bag space optimization

2.3 full backpack

Without limiting the amount of each item

2.3.1 Simple method

According to the i-th article put the number of pieces to make decisions, so the state transition equation

   

01 the same backpack, necessary to obtain the complete backpack NV states F [i] [j]. However, the need for complete backpack k are set to 0 when evaluated F [i] [j], ..., j / C [i] seeking the maximum F [i] [j] value. ( In fact, each state is updated when the max is no longer either case, or placed into a 0, but maxK case, into 0, 1, 2, 3 .... until the k .. )

This code should be three cycles (number of articles, article type, size backpack three cycles)

F[0][] ← {0}  
  
F[][0] ← {0}  
  
for i←1 to N  
  
    do for j←1 to V  
  
        do for k←0 to j/C[i]  
  
           if(j >= k*C[i])  
  
                then F[i][k] ← max(F[i][k],F[i-1][j-k*C[i]]+k*W[i])  
  
return F[N][V]
Backpack completely simple way pseudocode

This is triple loop, so consider optimizing

2.3.2 Optimization

 

Note here that, when j> = C [i] when the control is F [i] [jC [j]] updates rather than F [i-1] [jC [j]]. Since F [i] [jC [j]] state itself contains k-1 max a case (he put a max 0, ...... placed into a case of k-1), while the latter only max a situation that put 0 in case! ! !

2.3.3 0-1 backpacks and backpack completely different:

When the difference between 0-1 and a backpack full backpack from the two-dimensional array that is the state transition equation on the difference in the i-th place in the article, complete the backpack when choosing to put this item, the optimal solution is F [i] [jc [i] ] + w [i] Videos i.e. that a peer table, the 0-1 knapsack comparison is F [i-1] [jc [i]] + w [i], the one on the line.

The difference from the one-dimensional array knapsack full backpack and the difference in the cycle sequence , 0-1 backpacks must reverse order, because it ensures that no duplicate selected items have been selected, the backpack is completely order, the order will overwrite the previous state, there are cases of multiple choice, also in line with a backpack full meaning of the questions. State transition equation are both F [i] = max (F [i], dp [Fc [i]] + v [i]).
2.3.4 code to achieve full backpack

#include<cstdio>
#include<algorithm>
using namespace std;
int w[300],c[300],f[300010];
int V,n;
int main()
{
    scanf("%d%d",&V,&n);
    for(int i=1; i<=n; i++)
    {
        scanf("%d%d",&w[i],&c[i]);
    }
    for(int i=1; i<=n; i++)
        for ( int J = W [I]; J <= V; J ++) // Note that here, the 0-1 knapsack different, here order, out of order 0-1 knapsack 
            f [j] = max (f [j ], F [JW [I]] + C [I]); 
    the printf ( " max D =% \ n- " , F [V]);
     return  0 ; 
}
Backpack completely one-dimensional array optimization

2.4 Multiple backpack

2.4.1 Simple method

M max is the case Finite

2.4.2 Optimization

Solving for the conversion of 01 backpack: the i-th device 01 n items into backpack items [i]. Consider the binary thinking, consider the i-th item into a plurality of items, so that the original problem in the i-th article preferably each policy - 0..n take [i] member - can take a number equivalent to piece substitution after items. Also, taking more than n [i] member strategy will not appear.

The method is: the i-th item into several items, wherein each item has a coefficient value of these items and costs are the costs and the original value multiplied by this factor. These coefficients are 1,2,4, ..., 2 ^ (k-1), n ​​[i] -2 ^ k + 1, and k satisfy n [i] -2 ^ k + 1> 0 the largest integer. For example, if n [i] is 13, this article will be divided into four coefficients of 1,2,4,6 items.

The coefficients of these items into and is n [i], shows that n can not take more than the i-th item [i] member. In addition this method can be guaranteed for every integer can be expressed, proved by a number of coefficients and 0..n [i] between I have not seen here is not labeled, mainly need to understand the code , the code is given below.
2.4.3 code implementation

#include <stdio.h> 
#include <the iostream> 
#include <algorithm> 
#include <CString>
 #define MAX 1000000
 the using  namespace STD; 
 
int DP [MAX]; // store the last backpack can store the maximum number 
int value [MAX] , weight [MAX], number [MAX]; // are stored is the value of the article, and the amount by weight of each of the 
int Bag; 
 
void ZeroOnePack ( int weight, int value) // 01 backpack 
{
     int I;
     for (I Bag =; I> = weight; i-- ) 
    { 
        DP [I] = max (DP [I], DP [I-weight] +value); 
    } 
} 
void CompletePack ( int weight, int value) // complete backpack 
{
     int I;
     for (I = weight; I <= Bag; I ++ ) 
    { 
        DP [I] = max (DP [I], DP [ weight-I] + value); 
    } 
} 
void MultiplePack ( int weight, int value, int Number) // multiple backpacks 
{
     IF (Bag <= Number * weight) // if this is smaller than the total volume capacity of the article, then the finished article can take up, entirely corresponding to the backpack 
    { 
        CompletePack (weight, value);
        return ; 
    } 
    the else // otherwise it will be converted to multiple backpack 01 backpack 
    {
         int K = . 1 ;
         the while (K <= Number) 
        { 
            ZeroOnePack (K * weight, K * value); 
            Number = number- K; 
            K = 2 * K; // this binary thought 
        } 
        ZeroOnePack (Number * weight, Number * value); 
    } 
} 

int main () 
{ 
    int n-;
     the while (~ Scanf ( " % D% D" , & Bag, & n-)) 
    { 
        int I, SUM = 0 ;
         for (I = 0 ; I <n-; I ++ ) 
        { 
            Scanf ( " % D " , & Number [I]); // number of inputs 
            Scanf ( " % D " , & value [I]); // input value of this question is no article weight, will be understood to be equal to the volume and the value 
        } 
        Memset (DP, 0 , the sizeof (DP));
         for (I = 0 ; I <n-; ++ I ) 
        { 
            MultiplePack (value [I], value [I], Number [I]); //Multiple calls backpack, when attention wear parameters are the weight, the value and quantity 
        } 
        COUT << DP [Bag] << endl; 
    } 
    return  0 ; 
}
 
Multiple backpack

other

Reference links

https://blog.csdn.net/niaonao/article/details/78249256

https://blog.csdn.net/qq_38984851/article/details/81133840

https://www.cnblogs.com/aiguona/p/7274222.html

expand

1. The nature of the problem and knapsack problem, like coins, but there is a non-state solution

2. Learn binary compression of thought, the idea is very elegant and sophisticated

Guess you like

Origin www.cnblogs.com/guopinghai/p/11442901.html