UVA Problem 674 – Coin Change Solution:
Click here to go to this problem in uva Online Judge.
Solving Technique:
Given 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We are to calculate the number of ways the input amount can be distributed with this coins.
This problem is a bit harder. It can be solved with dynamic programming or using greedy technique. Use bottom up technique instead of top down to speed it up.
We can also replace this,
for(i = 5; i < N; ++i)
a[i] = a[i - 1];
with this since we know no matter what the input it is always possible to give 1 cents,
for(j = 0; j < N; ++j)
a[j] = 1;
It is hard to visualize without drawing the recursion tree or the array. The first 20 indexes of the array looks like this,
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Coins: 1 1 1 1 1 2 2 2 2 2 4 4 4 4 4 6 6 6 6 6 9
Explanation:
/* TO DO */
Important: Be sure to add or print a new line after each output unless otherwise specified. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.
Input:
11 26 5 4
Output:
4 13 2 1
Code Bottom Up:
/**
* @author Quickgrid ( Asif Ahmed )
* @link https://quickgrid.wordpress.com
* Problem: UVA 674 Coin Change
*/
#include <stdio.h>
#define N 8000
static int a[N] = {1, 1, 1, 1, 1};
static const int coins[4] = {5, 10, 25, 50};
int main()
{
register int i, j;
for(i = 5; i < N; ++i)
a[i] = a[i - 1];
for(i = 0; i < 4; ++i){
for(j = coins[i]; j < N; ++j)
a[j] += a[ j - coins[i] ];
}
int n;
while(scanf("%d", &n) == 1)
printf("%d\n", a[n]);
return 0;
}
Loop Fission Variant:
/**
* @author Quickgrid ( Asif Ahmed )
* @link https://quickgrid.wordpress.com
* Problem: UVA 674 Coin Change
*/
#include <stdio.h>
#define N 8000
#define M 5
static int a[N] = {1, 1, 1, 1, 1};
int main()
{
register int i, j;
for(j = M; j < N; ++j)
a[j] += a[j - 1];
for(j = 5; j < N; ++j)
a[j] += a[j - 5];
for(j = 10; j < N; ++j)
a[j] += a[j - 10];
for(j = 25; j < N; ++j)
a[j] += a[j - 25];
for(j = 50; j < N; ++j)
a[j] += a[j - 50];
int n;
while(scanf("%d", &n) == 1)
printf("%d\n", a[n]);
return 0;
}
2 thoughts on “UVA Problem 674 – Coin Change Solution”