UVA 674 Coin Change(动态规划 母函数)

  Coin Change 

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, two 5-cent coins and one 1-cent coin, 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 7489 cents.

 

Input 

The input file contains any number of lines, each one consisting of a number 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


题目大意:有5种货币,面值分别为1,5,10,25,50,求出给定价格共有多少种支付方式
看到这道题目,我的第一反应是母函数,拿来模板,一次超时,后来先打表便能AC。后来看大牛博客,原来可以用动态规划做的,时间复杂度为5*7500,这就是滚动数组吗?相比之下母函数就实在丑陋不堪了,现在贴两种代码如下:

母函数做法:
View Code
 1 #include
 2 using namespace std;
 3 # define maxn 7490
 4 int c1[maxn],c2[maxn];
 5 int cent[5]={1,5,10,25,50};
 6 int main(){
 7     int n,i,j,k;    
 8     for(i=0;i<=maxn;i++)
 9     {c1[i] = 1;  c2[i] = 0;}
10     for(i=1;i<5;i++){
11         for(j=0;j<=maxn;j++)
12             for(k = 0; k+j <= maxn;k += cent[i])
13             {c2[j+k] += c1[j];}
14             for(j=0;j<=maxn;j++)
15             {c1[j] = c2[j]; c2[j] = 0;}
16     }
17     while(cin>>n){
18         cout<endl;
19     }
20     return 0;
21 }

 

动态规划代码:
View Code
 1 #include 
 2 #include 
 3 
 4 using namespace std;
 5 # define maxn 7490
 6 
 7 int num[maxn];
 8 int cent[6]={0,1,5,10,25,50};
 9 
10 int main()
11 {
12     int n;    //初始化
13     for(int i=1;i<=maxn;i++)
14         num[i]=0;
15     num[0]=1;
16     
17     for(int t=1;t<=5;t++)
18         for(int i=1;i<=maxn;i++)
19         {
20             if(i>=cent[t]) num[i]+=num[i-cent[t]];    //  状态转移方程
21         }
22         while(cin>>n)
23         {
24             cout<endl;
25         }
26         return 0;
27 }
 
     

 

 

 

 

你可能感兴趣的:(UVA 674 Coin Change(动态规划 母函数))