Thursday, February 23, 2012

My UVA 357 Let me count the ways Solution


http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=293


#include <iostream>
#include <stdint.h>

#define MAX_COINS 5
#define MAX_CENTS 30001

using namespace std;

unsigned int coins[MAX_COINS] = {1, 5, 10, 25, 50};
unsigned long long dp[MAX_CENTS][MAX_COINS] = {0};


int lim=0;
void init(int to) {
    int i, j, k, c;
    if(to<=lim)return;
    for(i = lim+1; i <= to; ++i) 
    {
        dp[i][0] = 1;
        for (j = 1; j < MAX_COINS; ++j)
        {
            c = coins[j];
            for(k = 0; k <= j; ++k) 
            if(i>c)
                dp[i][j] += dp[i-c][k];
            else if(i==c)
                dp[i][j] = 1;
        }
    }


    lim=to;

}

int main() {
    int N;
    unsigned long long res = 0L;
    dp[0][0]=1;     
    
    while (cin >> N) {
        init(N);
        res = dp[N][0]+dp[N][1]+dp[N][2]+dp[N][3]+dp[N][4];
        if (res == 1)
            cout << "There is only 1 way to produce " << N << " cents change.\n";
        else
            cout << "There are " << res << " ways to produce " << N << " cents change.\n";
    }
    return 0;

}

No comments:

Post a Comment