Question 1209: Dynamic Programming JAVA Implementation of the minimum number of stamps

Source: Internet
Author: User
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];
}

}
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.