Set the meal card balance to total
After analysis, we can conclude that the consumption of some meals should be as close as possible to total-5 yuan, and then we can purchase another meal to reach the overdraft...
It can prove that the last purchased food is the most valuable.
Proof
Set a1 a2 a3... an-1 an to set the maximum price for each meal
Set
Sum = total-5
A1 + a2 + a3 +... an-2 + an-1 + an = M
A1 + a2 + a3 +... + an-2 + an-1 = x1 add an (by the limit of 5 yuan) at this time excess (an-1)-(sum-x1) = an-sum + a1 + a2 +... + an-2 + an-1 RMB 1
A1 + a2 + a3 +... + an-2 + an = x2 add an-1 (by the limit of 5 yuan) at this time excess (an)-(sum-x2) = (an-1) -sum + a1 + a2 +... + an-2 + an RMB 2
1-2 formula = 2 * (an)-(an-1)> 0
So the 1-level excess is more
So I finally chose the food with the largest price.
Note: If the total balance is less than 5 yuan, you can directly output the total, but you cannot buy things at this time.
Dynamic Planning
01 total number of backpacks with problems-5 w for each backpack's value and weight
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Define max (a, B) a> B? A: B
Int cmp (const void * a, const void * B)
{
Return * (int *) a-* (int *) B;
}
Int main ()
{
Int n, a [5000], I, bb [5000], m, j;
While (scanf ("% d", & n), n! = 0)
{
Memset (bb, 0, sizeof (bb ));
For (I = 0; I <n; I ++)
Scanf ("% d", & a [I]);
Scanf ("% d", & m );
Qsort (a, n, sizeof (a [0]), cmp );
If (m <5)
{
Printf ("% d \ n", m );
Continue;
}
Memset (bb, 0, sizeof (bb ));
M = M-5;
Bb [0] = 0;
For (I = 0; I <n-1; I ++)
{
For (j = m; j> = a [I]; j --)
{
Bb [j] = max (bb [j], bb [j-a [I] + a [I]);
}
}
Printf ("% d \ n", m + 5-bb [m]-a [n-1]);
}
Return 0;
}