码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 674 Coin Change

时间:2014-05-04 12:00:00      阅读:363      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

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

联系一下完全背包,因该可以想到这样一个dp
dp[i]=sum(dp[i-1],dp[i-5],dp[i-10],dp[i-20],dp[i-50]),但是很容易想到会算重复,但是在背包里就说了一种避免重复的方法,下面给出两个程序
bubuko.com,布布扣
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int dp[8000];
int st[5]={1,5,10,25,50};
int main()
{
    int n;
    while (scanf("%d", &n))
    {
        memset(dp,0,sizeof(dp));
        dp[0]=1;
        for (int i=0;i<=n;i++)
        for (int j=0;j<5;j++)
        dp[i]+=dp[i-st[j]];
        printf("%d\n",dp[n]);
    }
    return 0;
}
bubuko.com,布布扣

这个程序看上去不错,不过它真的是错的,在计算的时候重复计算了很多,下面再给出一个程序

bubuko.com,布布扣
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int dp[8000];
int st[5]={1,5,10,25,50};
int main()
{
    memset(dp,0,sizeof(dp));
    dp[0]=1;
    for (int i=0;i<5;i++)
        for (int j=st[i];j<=7490;j++)
        dp[j]+=dp[j-st[i]];
    int n;
    while (scanf("%d", &n)!=EOF)
    {
        printf("%d\n",dp[n]);
    }
    return 0;
}
bubuko.com,布布扣

而把循坏顺序变一下,结果就不一样了,这样就对了,上面这个程序跑了将近15ms,下面再给出一个

bubuko.com,布布扣
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int dp[8000];
int st[5]={1,5,10,25,50};
int main()
{
    int n;
    while (scanf("%d", &n)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        dp[0]=1;
        for (int i=0;i<5;i++)
        for (int j=st[i];j<=n;j++)
        dp[j]+=dp[j-st[i]];
        printf("%d\n",dp[n]);
    }
    return 0;
}
bubuko.com,布布扣

而这个程序跑了将近2s,差别啊!!!是不是很神奇啊

UVA 674 Coin Change,布布扣,bubuko.com

UVA 674 Coin Change

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/chensunrise/p/3705472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!