# 01 backpack, 01 backpack Problems

Source: Internet
Author: User

01 backpack, 01 backpack Problems
I used to talk about backpacks in acm classes. However, they are simple, that is, a simple greedy problem. The problem is solved by sorting them first, and then processing them, it seems that it is more difficult than that. This requires traversing and finding the right one. The simple principle is as follows.

For example, we have a backpack with a capacity of m and k different products with a weight of w and a value of v. How can we buy them to maximize the value?

Idea: If it is greedy, the product is directly sorted by price from large to small, and then bought in sequence. Obviously, this is wrong. We should try to buy a high value within the capacity range, sometimes it is bought that the capacity is full. At this time, the value is maximized.

Direct dp traversal:

Memset (d, 0, sizeof (d);/initialize to 0.

For (int I = 0; I <k; I ++)/k items in total

For (int j = m; j> = w [I]; j --)/d [j] indicates that when the capacity is j, the maximum value of the backpack is d [j]

D [j] = max (d [j], d [j-w [I] + v [I]);/compare the value of choosing to buy or not to buy

Cout <d [m] <endl;/maximum value when the output capacity is m

The simple 01 backpack template is the top one. You can modify it when you encounter similar questions.

This template is recursive, but it is also recursive. However, it is relatively long and generally uses recursive.

Some exercise questions provided by xuejie are sorted first, and some require you to convert the question into a 01 backpack on your own, just like the probability of robbing a bank.

Exercise question URL:

To be continued ......

Related Keywords:

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.