01 backpack [TEMPLATE]

Source: Internet
Author: User
01 A backpack is the most basic problem. It has the following characteristics: You can choose to put or not to put each item. Define the state with sub-problem: that is, F [I, V] indicates the maximum value that the first I-item can be obtained by placing a backpack with a capacity of V. The state transition equation is:
F [I, V] = max (F [I, V], F [I-1, V-W [I] + V [I])
This equation is very important. Basically all the equations related to the backpack are derived from it. Therefore, it is necessary to explain in detail: "Put the first I items into a backpack with a capacity of V, if you only consider the I-th item Policy (put or not put), you can convert it into a problem related to the first I-1 item. If I-1 items are not placed, the problem is converted to "the first I-1 items are placed in a V-sized backpack". The value is f [I-1; V]. if I items are placed, the problem is converted to "the first I-1 items are placed in the left V-ci backpack ", in this case, the greatest value that can be obtained is f [I-1; V-CI] plus the value wi obtained by placing the I-th item. The pseudocode is as follows:
F [0, 0.. V] <-- 0
For I <-- 1 to n
For v <-- CI to V

F [I; V] <-- max {f [I-1, V], F [I-1, V-CI] + wi}

The Code is as follows:

# Include <stdio. h> # include <stdlib. h> # include <string. h> # define max (x, y) x> Y? X: Y; int V [1001]; // value int W [1001]; // weight int DP [1001] [1001]; int main () {int N, m, I, j; while (scanf ("% d", & M, & N )! = EOF) {memset (DP, 0, sizeof (DP); // initialize for (I = 1; I <= N; I ++) scanf ("% d", & W [I], & V [I]); for (I = 1; I <= N; I ++) // number of items for (j = m; j> = W [I]; j --) // put the backpack DP [I] [J] = max (DP [I-1] [J], DP [I-1] [J-W [I] + V [I]); // compare with printf ("% d \ n ", DP [N] [m]);} return 0 ;}


01 backpack [TEMPLATE]

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.