01 backpack in-depth explanation (one-dimensional array method) + detailed procedures

Source: Internet
Author: User

Based on the previous article, we can optimize the code from the space complexity, that is, to see if it can be done using a one-dimensional array.

According to the Code, we need to know that if we start to push f [V] in every main loop in the second loop, this ensures that f [v] f [v-c [I] saves the value of State f [I-1] [v-c [I.

The Code is as follows:

# Include <cstdio>
# Include <cstring>

Int sum_values [1005];

Int main ()
Int T;
Int N, V;
Int I, j;

While (scanf ("% d", & N, & V) & (N + V ))
Int weight [1001], value [1001];

For (I = 1; I <= N; I ++)
Scanf ("% d", & weight [I]);
Scanf ("% d", & value [I]);

Memset (sum_values, 0, sizeof (sum_values ));
For (I = 1; I <= N; I ++) // starts from the first fruit to the nth fruit.
For (j = V; j> = weight [I]; j --) // starting from the full state, and the capacity of the j-state should be larger than the size of the I-state.
If (sum_values [j-weight [I] + value [I]> sum_values [j]) // if, before the j state, that is, the J-1 State is placed into a fruit of class I, and the total value is greater than the value of the j state, select to put in the J-1 state
Sum_values [j] = sum_values [j-weight [I] + value [I];

Printf ("% d \ n", sum_values [V]);

Return 0;

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.