Hdu 2546 meal card (DP _ backpack)

Source: Internet
Author: User

Q: How can I swipe my card in the canteen of the E-Science and Technology Department? If the balance on the card is equal to 5, I can cook at will, even if I make more dishes than the balance. The unit price of n dishes is given now. If you buy one dish at a time, what is the minimum remaining balance on the card?


Solution: This question can be applied to the idea of 01 backpack. The value is that the value becomes reachable. Use dp [j] to indicate whether the balance is j reachable. The value can be 1; otherwise, the value is 0. the state transition equation is if (dp [j] & j-price [I]> = 5) dp [j-price [I] = 1; then records are transferred to the minimum value, the final output is enough. There are two points to note in this question: 1. traverse the order of balance from 0 to sum. In this way, the previous result is used for the transfer, because sum is in the same initial state as the 0 state in the 01 backpack. 2. The price must be sorted in advance. Otherwise, if the previous value is greater than 5, the subsequent values cannot be updated.

 


Test data:


3
10000 1 3
9

1
50
5

10
1 2 3 2 1 1 2 3 2 1
50

3
1 2 3
3

 

Code: [cpp] # include <stdio. h>
# Include <string. h>
# Include <algorithm>
Using namespace std;
# Deprecision MAX 100000
 
 
Int n, price [MAX];
Int sum, minn, dp [MAX];
 
 
Int main ()
{
Int I, j, k, t;
 

While (scanf ("% d", & n), n ){
 
For (I = 1; I <= n; ++ I)
Scanf ("% d", & price [I]);
Scanf ("% d", & sum );
Sort (price + 1, price + 1 + n );
 
 
Memset (dp, 0, sizeof (dp ));
Dp [sum] = 1, minn = sum;
For (I = 1; I <= n; ++ I)
For (j = 5; j <= sum; ++ j)
If (dp [j] = 1 ){
 
If (j-price [I]> = 5)
Dp [j-price [I] = 1;
If (j-price [I] <minn)
Minn = j-price [I];
}
 
 
Printf ("% d \ n", minn );
}
}

 


From ZeroClock


 

Related Article

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.