Algorithmic Learning-01 knapsack problem (Dynamic programming C + +)

Source: Internet
Author: User

    • Dynamic planning
    • 01 Backpack
      • Problem description
      • Solving ideas
    • Code implementation
    • Which items to put in
    • Code

Dynamic planning

I've already talked about a little bit of dynamic planning in my last blog, Portal: Algorithmic Learning-Dynamic programming (DP problem) (c + +)

Here's how to find a solution to how dynamic planning should be.

The main thing is actually to find the equation of state transfer, for example, in the previous blog, looking for the current two production lines of the first station of the shortest time and the time of the previous moment relationship.

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

The question to be told Today is the 01 knapsack problem.

01 knapsack Problem Description

01 The backpack is in the m pieces of items taken out several pieces placed in the space W backpack, the volume of each item is W1,W2 ... Wn, corresponding to the value of P1,P2 ... Pn.

The maximum value of this backpack can be solved. (objects cannot be split).

Solving ideas

This is actually more difficult than the last problem where?
Difficult in the last topic assembly line is always two, not much, not less. The quantity we change is only the number of assembly stations.

The amount of change in this topic is the number of items, and one is the space for the backpack. This means that the assembly line does not vary with station, but the space of the backpack changes as the item is loaded.

So what we need to do is to determine if we j can load the first i item and increase the total value when the remaining space for the backpack is.
That

max//v[i]表示第i个物品的体积,w[i]表示第i个物品的价值。

In fact, when I first saw the above-mentioned state-shifted equation, I felt that it was not certain to j put items in space when the value was greater than what was not put into the item. After all, just put in to prove that added value AH.

It's not like this, because it's only 0 when it's not loaded at the very beginning. The load will increase in value. But if we have the following items:

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

When we put the first item, suppose the backpack space is 5, then d[2 ... 5] All are for 5. Because d[0 ... 1] The space is not enough so it is 0. When we put the item 2, d[5] = 5 > d[5 - 4] + 3 because d[1] = 0; .

Found out No! is not put on a certain total value increase!

So we traverse all the items, starting with the first item and looking for j the space, whether the loaded item will add value!

Code implementation

The code is rarely implemented, and it's not good to see those who write two screens, and there may be no more features.

////Main.cpp//Dp_01backpack////Created by Alps on 15/4/28.//Copyright (c) 2015 Chen. All rights reserved.////code directly defines the number of stones and the space of the backpack, in fact, can not be defined in advance. //Here for convenience, and in C + + 11 can dynamically specify the size of the array. #include <iostream>usingnamespace Std;#ifndef Stone_num#Define stone_num 5//define the number of stones#endif #ifndef backpack_space#define backpack_space#endif intMainintargcConst Char* argv[]) {intStonespace, Stonevalue;//Save the currently entered item space and value    int value[backpack_space+1] = {0};//Initialize value array     for(inti =0; i < Stone_num; i++) {scanf ("%d%d", &stonespace, &stonevalue);//Receive Item input         for(intj = Backpack_space; J >0; j--) {//When the backpack space is different, * * must be from big to small * *            if(J >= Stonespace &&value[J] < (value[J-stonespace] + stonevalue)) {//If the backpack space is sufficient and the total value added                value[j] =value[J-stonespace] + stonevalue;//Put in and update total value}}} printf ("%d\n",value[Backpack_space]);return 0;}

This explains why, in the second for loop, J is from the largest to the smallest. Because we compare the current items into, whether the value has changed, that is value[j] and value[j-v] comparison. If it is updated, then VALUE[J + 1] will need to compare with Value[j + 1-v], possibly Value[j + 1-v] has been updated. I can't! Because at that time the total value of Value[j + 1-v] has been counted as the current item. Again, it repeats.

Which items to put in

The above code does not know exactly what to put in, in fact, because in order to save space, did not save each stonespace and Stonevalue.
So let's just turn them into arrays.

Then the first thing we have to do is: How much space to find the total backpack!

This is important, because the maximum value of the backpack is not necessarily full, so we need to find out how much space to use to know exactly what items are put in.

How to find it?

If our value array is as follows:

0
0
4
6
9
10
13
15
15
19
19

It's easy to know, this backpack has a space left? Why, because the largest 19 there are two, J more 1 but the value has not increased, indicating that the 1 of the space is not put in items, that is, spare.

In this way, the first maximum number of subscripts is found, which is the space used.

Code

Relatively simple, just one more step to find those items put in, that is, when the backpack space minus the item space, the total value also just increases the value of the item, then the item is put in.

The code is as follows:

////Main.cpp//Dp_01backpack////Created by Alps on 15/4/28.//Copyright (c) 2015 Chen. All rights reserved.////code directly defines the number of stones and the space of the backpack, in fact, can not be defined in advance. //Here for convenience, and in C + + 11 can dynamically specify the size of the array. #include <iostream>usingnamespace Std;#ifndef Stone_num#Define stone_num 5//define the number of stones#endif #ifndef backpack_space#define backpack_space#endif intMainintargcConst Char* argv[]) {int value[backpack_space+1] = {0};intStonespace[stone_num],stonevalue[stone_num]; for(inti =0; i < Stone_num; i++) {scanf ("%d%d", &stonespace[i], &stonevalue[i]); for(intj = 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 has almost no change, just storage is an array of storage.      for(inti =0; I <= backpack_space; i++) {printf ("%d\n",value[i]); }//Print the value array, which holds the maximum total value of all items when the backpack has only space I.     intBackpackspace = Backpack_space;//Get backpack space     while(value[Backpackspace] = =value[backpackspace-1]) {backpackspace--;//If the backpack value and backpack space-1 are the same value, space -1}//Find out how much space is used altogether     for(inti = 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 just equal to the value of the item, indicating that the item was put in. printf"%d", i+1);//Print this item. I+1 is because the subscript of an item starts from 0. Backpackspace = Backpackspace-stonespace[i];//Backpack has been put into this item, natural space is reduced. }    }return 0;}

The entire code is relatively simple. If you have questions, you can communicate with each other.

I read an article about other blogs, and I thought it was great to get started with a two-dimensional matrix. Recommendation: http://www.hawstein.com/posts/dp-knapsack.html

Algorithmic Learning-01 knapsack problem (Dynamic programming C + +)

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.