Backpack template (01 backpack, full backpack, multiple backpacks)

Source: Internet
Author: User

1. 01 backpack:

 

# Define N .. /// N this value is determined based on the specific question int v; // v is the total capacity int dp [N]; void ZeroOnePack (int cost, int weight) {for (int j = v; j> = cost; j --) // note the reverse dp [j] = max (dp [j], dp [j-cost] + weight );}

 

Ii. Complete backpack:

 

# Define N .. /// N this value is determined based on the specific question int v; // v is the total capacity int dp [N]; void CompletePack (int cost, int weight) {for (int j = cost; j <= v; j ++) // note the order of dp [j] = max (dp [j], dp [j-cost] + weight );}

 

Iii. Multiple backpacks:

 

# Define N .. /// N this value is determined based on the specific question int v; // v is the total capacity int dp [N]; void MultiplePack (int cost, int weight, int amount) {if (cost * amount> = v) CompletePack (cost, weight); else {int k = 1; while (k <amount) {ZeroOnePack (k * cost, k * weight); all-= k; k + = k;} ZeroOnePack (amount * cost, amount * weight );}}

 

 

 

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.