Va 674: coin change

Source: Internet
Author: User

Dynamic Planning questions. For coins ranging from 1, 5, 10, 25, and 50, the number is 0 ~ 4. Save it to the cent array. The iway [k] [I] element of the array iway indicates that only 0 ~ is used ~ The number of coins used by I to generate K cents, which is classified by whether I-numbered coins are used, the state transition equation iway [k] [I] = iway [k] [I-1] + iway [k-cent [I] [I] can be obtained.

An optimization method: The analysis shows that the number of methods with 15, 16, 17, 18, and 19 cents is the same, because the difference is only one cent of the number of coins. Therefore, iway [k] [I] = iway [k/5*5] [I]. This statement can save a little time for running the program.

My problem-solving code is as follows:

# Include <iostream >#include <cstdio> # include <cstring> using namespace STD; # define Max 7500 # define coins 5int cent [coins] = {1, 5, 10, 25, 50}; int iway [Max] [coins]; // use 0 ~ Iway [k] [k] = iway [k] [k] [k] [I-1] + iway [k-cent [I] [I] int F (int value, int coins) {If (iway [value] [coins]) return iway [value] [coins]; If (value> = cent [coins]) iway [value] [coins] = f (value, coins-1) + f (value-cent [coins], coins ); else iway [value] [coins] = f (value, coins-1);/* For (INT I = value/5*5; I <value/5*5 + 5; I ++) iway [I] [coins] = iway [value] [coins]; * // can be used to optimize the program return iway [value] [coins];} int main () {int N; memset (iway, 0, sizeof (iway )); for (INT I = 0; I <coins; I ++) iway [0] [I] = 1; for (INT I = 0; I <Max; I ++) iway [I] [0] = 1; while (CIN> N) {cout <F (n, coins-1) <Endl;} return 0 ;}

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.