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