Coin Change

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10590    Accepted Submission(s): 3535


Problem Description Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.


For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, or two 5-cent coins and one 1-cent coin, or one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.


Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 100 coins.  


Input The input file contains any number of lines, each one consisting of a number ( ≤250 ) for the amount of money in cents.  


Output For each input line, output a line containing the number of different ways of making changes with the above 5 types of coins.  


Sample Input 11 26  


Sample Output 4 13  


Author Lily  


Source 浙江工业大学网络选拔赛  

思路: 此题可以采取dfs,但是用分治法还是可以的,优化一下可以达到15ms......

在此贴出代码:

HDUOJ----Coin Change_HDUOJHDUOJ----Coin Change_ios_02

1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int n,count;
6 int j,k,m,g,l;
7 while(cin>>n)
8 {
9 count=0;
10 for( j=0;j<=n/50;j++) //50
11 {
12 k=m=g=l=0;
13 if(n==j*50+k*25+m*10+g*5+l)
14 {
15 count++;
16 break;
17 }
18 else
19 if(n<j*50+k*25+m*10+g*5+l)
20 break;
21
22 for( k=0;k<=n/25;k++) //25
23 {
24 m=g=l=0;
25 if(n==j*50+k*25+m*10+g*5+l)
26 {
27 count++;
28 break;
29 }
30 else
31 if(n<j*50+k*25+m*10+g*5+l)
32 break;
33 for( m=0;m<=n/10;m++) //10
34 {
35 g=l=0;
36 if(n==j*50+k*25+m*10+g*5+l)
37 {
38 count++;
39 break;
40 }
41 else
42 if(n<j*50+k*25+m*10+g*5+l)
43 break;
44 for( g=0;g<=n/5;g++) //5
45 {
46 l=0;
47 if(n==j*50+k*25+m*10+g*5+l)
48 {
49 count++;
50 break;
51 }
52 else
53 if(n<j*50+k*25+m*10+g*5+l)
54 break;
55 for( l=0;l<=100-j-k-m-g;l++) //1
56 {
57 if(n==j*50+k*25+m*10+g*5+l)
58 {
59 count++;
60 break;
61 }
62 else
63 if(n<j*50+k*25+m*10+g*5+l)
64 break;
65 }
66 }
67 }
68 }
69 }
70
71 cout<<count<<endl;
72 }
73 return 0;
74 }

View Code





编程是一种快乐,享受代码带给我的乐趣!!!