Dynamic planning 01 Backpack Records

Source: Internet
Author: User

01 Backpack is a type of dynamic programming its main forms are:

1, all types of goods each type only one

2, only one at a time and the items can not be divided

3, only take or not take (so call 01 backpack, is only these two cases)

4, under the premise of the knapsack capacity dissatisfaction, as much as possible to load the maximum value of goods

The capacity of the backpack is V, the weight of the article I is weigh[i] corresponds to the value of price[i]; The maximum value of a backpack with a capacity of J (the maximum size of a backpack) is dp[j]

n is the total number of items, we start with the 1th data, then this item weighs weigh[1], then we put all the bags greater than weigh[1] into the 1th item (i.e. from DP[V] to

DP[WEIGH[1]]) at this time all backpacks larger than weigh[1] weight are loaded into the first item.

Next we loaded the 2nd item, and we were going to load a second item for all the backpacks that were larger than weigh[2], but some of the backpacks had been loaded when the first item was loaded.

The first item, how to do it? There are several situations:

1. If the capacity is insufficient to load the second item after loading the first item and the value of the first item is greater than the second piece, the second piece is not loaded

2. If the remaining capacity is insufficient to load the second item after loading the first item and the value of the first item enters the second piece, the second item is loaded to take out the first piece (of course in the program

Can be directly overwritten as the first item removed)

3. If the capacity of the first item is sufficient to fit the second item, two items will be loaded into the backpack together.

Code implementation:

And so on

Big God don't squirt

Dynamic planning 01 Backpack Records

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.