Because the data range is 20, the direct enumeration is 2 ^ 20 and does not time out. Simply find the combination. In N, take 1 and 2 .... N number. You can find a minimum difference.
The following is a combination of algorithms-175 MS
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <math. h>
# Define nMax 25
Int N, B;
Int height [nMax];
Int ans;
Int getSum (int pos)
{
Int sum = 0;
For (int I = 0; I <N; ++ I)
{
If (pos & (1 <I ))
{
Sum + = height [I];
}
}
Return sum;
}
Int main ()
{
While (scanf ("% d", & N, & B )! = EOF)
{
Ans = 0x7FFFFFFF;
For (int I = 0; I <N; ++ I)
{
Scanf ("% d", & height [I]);
}
For (int I = 1; I <(1 <N); ++ I)
{
If (getSum (I) <B)
{
Continue;
}
Int tmp = getSum (I)-B;
If (ans> tmp)
{
Ans = tmp;
}
}
Printf ("% d \ n", ans );
}
Return 0;
}
This question can also be done using 01 backpack dynamic planning-32 MS
[Cpp]
# Include <iostream>
# Include <cstring>
Using namespace std;
Int f [1000050], c [10000];
Int main (){
Int n, v;
While (cin> n> v ){
Memset (f, 0, sizeof (f ));
Memset (c, 0, sizeof (c ));
Int sum = 0;
For (int I = 1; I <= n; ++ I ){
Cin> c [I];
Sum + = c [I];
}
For (int I = 1; I <= n; I ++ ){
For (int j = sum; j> = c [I]; j --)
F [j] = max (f [j], f [j-c [I] + c [I]);
}
For (int I = 1; I <= sum; ++ I ){
If (f [I]> = v ){
Cout <f [I]-v <endl;
Break;
}
}
}
Return 0;
}
This question can also be done with the dfs deep Priority Search-32 MS
[Cpp]
# Include <stdio. h>
Int cow [20];
Int B;
Int n;
Int ans = 99999999;
Void DFS (int num, int sum)
{
If (sum> = ans) return;
If (num = n)
{
If (sum> = B) ans = sum;
Return;
}
DFS (num + 1, sum );
DFS (num + 1, sum + cow [num]);
}
Int main ()
{
// Freopen ("input", "r", stdin );
Int I, j, cnt, tmp;
Int sum;
Scanf ("% d", & n, & B );
For (I = 0; I <n; I ++)
Scanf ("% d", & cow [I]);
DFS (0, 0 );
Printf ("% d", ans-B );
Return 0;
}