-
Description:
-
There are several stamps that require the minimum number of stamps to be selected to generate a given total value.
For example, if one, three, and four stamps are required to be scored as 10, three stamps are used: 3, 3, and 4.
-
Input:
-
There are multiple sets of data. For each set of data, the first requirement is to generate a total stamp value of M, m <100. Then there is a number N, N <20, indicating there are n stamps. Next there are n positive integers, which represent the face values of the N stamps in ascending order.
-
Output:
-
For each set of data, the minimum number of stamps can be aggregated into M. If no solution is available, 0 is output.
-
Sample input:
-
1051 3 3 3 4
-
Sample output:
-
3
Import java. Io. bufferedinputstream;
Import java. util. arrays;
Import java. util. collections;
Public class stamp 1209 {
Static int sum;
Static int N;
Static int arr [];
Static int max = 99999;
Static int OPT [] [];
Public static void main (string [] ARGs ){
S = new second (New bufferedinputstream (system. In ));
While (S. hasnextint ()){
Sum = S. nextint ();
N = S. nextint ();
Arr = new int [N];
Opt = new int [n + 1] [Sum + 1];
For (INT I = 0; I <n; I ++)
Arr [I] = S. nextint ();
Arrays. Sort (ARR );
Int r = f (n-1, sum );
If (r> = max)
System. Out. println (0 );
Else
System. Out. println (R );
}
}
Static int F (int I, int sum ){
If (sum <= 0)
Return Max;
If (OPT [I] [Sum]> 0)
Return OPT [I] [Sum];
If (arrays. binarysearch (ARR, 0, I + 1, sum)> = 0 ){
OPT [I] [Sum] = 1;
Return OPT [I] [Sum];
}
Else if (I> 0 ){
Return OPT [I] [Sum] = math. Min (f (I-1, Sum-Arr [I]) + 1, F (I-1, sum ));
}
If (I = 0)
Return OPT [I] [Sum] = (ARR [0] = sum? 1: Max );
Return OPT [I] [Sum];
}
}