Algorithm learning-01 knapsack problem (dynamic programming C ++)

Source: Internet
Author: User

Algorithm learning-01 knapsack problem (dynamic programming C ++)

Dynamic Planning 01 knapsack problem description solution ideas code implementation what item code is included

Dynamic Planning

I have already talked about dynamic planning in my previous blog. Portal: algorithm learning-Dynamic Planning (DP problem) (C ++)

Here we will talk about how to find a solution in the face of dynamic planning.

The most important thing is to find the state transfer equation. For example, in the previous blog, we found the shortest time of the first station of the current two production lines and the time relationship between the previous time.

minTime(station[1][i]) = minTime(station[1][i-1] + time[i], station[2][i-1] + time[i] + trans[i-1])

The question to address today is the question of the 01 backpack.

01 knapsack problem description

01 A backpack is a backpack with several items taken out of M and placed in W space. The size of each item is W1, W2 ...... Wn, corresponding value: P1, P2 ...... Pn.

Solve the maximum value of this backpack. (Objects cannot be separated ).

Solution

This is actually more difficult than the previous question?
It is difficult to have two assembly lines in the previous question. We only change the number of assembly stations.

This question changes the quantity of items, and the space for backpacks. That is to say, the assembly line will not change with the number of stations, but the space of the backpack will change with the loading of items.

So what we need to do is determine when the remaining space of the backpack isjCan I mountiItems, and the total value is increased.
That is:

D [j] = max (d [j], d [j-v [I] + w [I]); // v [I] indicates the volume of the I-th item, and w [I] indicates the value of the I-th item.

In fact, when I first saw the above state transfer equation, I thought it was not a sure space.jWhen you put an item, the value is greater than not put an item. After all, adding it proves that it adds value.

In fact, this is not the case, because only when there is no load at the beginning, all is 0. loading will increase the value. However, assume that our items are as follows:

Item 1: space 2 value 5
Item 2: Space 4 value 3

When we put the first item, assume that the space of the backpack is 5, then d [2... 5] is 5. Because d [0... 1] The space is not enough, so it is 0. When we put item 2,d[5] = 5 > d[5 - 4] + 3Becaused[1] = 0;.

No! The total value is increased if it is not put!

So we traverse all items, starting from the first item, and find the spacejWhen loading an item, will it increase the value!

Code Implementation

In fact, the number of lines of code is very small. It is difficult to look at those that write two screens and may not have more functions.

//// Main. cpp // DP_01backpack /// Created by Alps on 15/4/28. // Copyright (c) 2015 chen. all rights reserved. //// the Code directly defines the quantity of stones and the space of the backpack. In fact, you do not need to define them in advance. // For convenience, the array size can be dynamically specified in C ++ 11. # Include
  
   
Using namespace std; # ifndef STONE_NUM # define STONE_NUM 5 // defines the number of stones # endif # ifndef BACKPACK_SPACE # define BACKPACK_SPACE 10 # endifint main (int argc, const char * argv []) {int stoneSpace, stoneValue; // Save the space and value of the currently entered item int value [BACKPACK_SPACE + 1] = {0}; // initialize the value array for (int I = 0; I <STONE_NUM; I ++) {scanf (% d, & stoneSpace, & stoneValue); // receives the item input for (int j = BACKPACK_SPACE; j> 0; j --) {// when the backpack space is different, ** j must be from large to small ** if (j> = stoneSpace & value [j] <(value [j-stoneSpace] + stoneValue )) {// assume that the backpack has sufficient space and the total value is added. value [j] = value [j-stoneSpace] + stoneValue, total value updated }}printf (% d, value [BACKPACK_SPACE]); return 0 ;}
  

This explains why the second layerforIn a loop, j changes from the largest to the smallest. Because we compared whether the value of the current item has changed, that is, the comparison between value [j] and value [j-v. If it is updated, the value [j + 1] must be compared with the value [j + 1-v]. Maybe the value [j + 1-v] has been updated. It won't work! At that time, the total value of value [j + 1-v] was counted as the current item. The calculation is repeated.

Items

The above Code does not know what items are put into it, because every stoneSpace and stoneValue are not saved to save space.
So we can convert them into arrays.

The first thing we need to do is:Find out how much space is used for a total of backpacks!

This is very important, because the greatest value of a backpack is not always full, so we need to find out how much space we have used to know what items we have put.

How to find it?

Assume that our value array is as follows:

0
0
4
6
9
10
13
15
15
19
19

It is easy to know that this backpack has a space left? Why? Because there are two of the largest 19 s, j has 1 more but the value has not increased, it means that the space for this 1 is not put into an item, that is, it is free.

In this way, find the first subscript with the maximum number, that is, the space used.

Code

It is relatively simple, but it only takes one more step to find the items that are put in. That is, when the backpack space minus the item space, the total value also increases the value of the item, which means the item is put.

The Code is as follows:

//// Main. cpp // DP_01backpack /// Created by Alps on 15/4/28. // Copyright (c) 2015 chen. all rights reserved. //// the Code directly defines the quantity of stones and the space of the backpack. In fact, you do not need to define them in advance. // For convenience, the array size can be dynamically specified in C ++ 11. # Include
  
   
Using namespace std; # ifndef STONE_NUM # define STONE_NUM 5 // defines the number of stones # endif # ifndef BACKPACK_SPACE # define BACKPACK_SPACE 10 # endifint main (int argc, const char * argv []) {int value [BACKPACK_SPACE + 1] = {0}; int stoneSpace [STONE_NUM], stoneValue [STONE_NUM]; for (int I = 0; I <STONE_NUM; I ++) {scanf (% d, & stoneSpace [I], & stoneValue [I]); for (int j = BACKPACK_SPACE; j> 0; j --) {if (j> = stoneSpace [I] & & Value [j] <value [j-stoneSpace [I] + stoneValue [I]) {value [j] = value [j-stoneSpace [I] + stoneValue [I] ;}}// the above Code is almost unchanged, but the storage is an array storage. For (int I = 0; I <= BACKPACK_SPACE; I ++) {printf (% d, value [I]);} // print the value array, what is stored here is the maximum total value of all items when the backpack only has space I. Int backPackSpace = BACKPACK_SPACE; // get the backpack space while (value [backPackSpace] = value [backPackSpace-1]) {backPackSpace --; // if the value of the backpack is the same as that of the backpack space-1, space-1} // find the total space used for (int I = STONE_NUM-1; I> = 0; I --) {if (value [backPackSpace] = value [backPackSpace-stoneSpace [I] + stoneValue [I]) {// if the space of the current item is subtracted, the total value is equal to the value of the item, indicating that the item is placed. Printf (% d, I + 1); // print this item. I + 1 is because the subscript of an item starts from 0. BackPackSpace = backPackSpace-stoneSpace [I]; // This item is placed in the backpack, reducing the natural space.} Return 0 ;}
  

The entire code is relatively simple. Messages with questions can be exchanged.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.