Skip to code
Skip to analysis

This is a explanation of this problem from USACO's training website. I have converted it to markdown. Please do not just copy code; you will not learn anything; at least type it out and understand so you can do it yourself in the future!

The cows have not only created their own government but they have chosen to create their own money system. In their own rebellious way, they are curious about values of coinage. Traditionally, coins come in values like 1, 5, 10, 20 or 25, 50, and 100 units, sometimes with a 2 unit coin thrown in for good measure.

The cows want to know how many different ways it is possible to dispense a certain amount of money using various coin systems. For instance, using a system of {1, 2, 5, 10, …} it is possible to create 18 units several different ways, including: 18x1, 9x2, 8x2+2x1, 3x5+2+1, and many others.

Write a program to compute how many ways to construct a given amount of money using supplied coinage. It is guaranteed that the total will fit into both a signed long long (C/C++) and Int64 (Free Pascal).

PROGRAM NAME: money

INPUT FORMAT

The number of coins in the system is V (1 <= V <= 25).

The amount money to construct is N (1 <= N <= 10,000).

Line 1: Two integers, V and N
Lines 2..: V integers that represent the available coins (no particular number of integers per line)

SAMPLE INPUT (file money.in)

3 10
1 2 5

OUTPUT FORMAT

A single line containing the total number of ways to construct N money units using V coins.

SAMPLE OUTPUT (file money.out)

10

CODE

Java


C++


Pascal



ANALYSIS

Russ Cox

We use dynamic programming to count the number of ways to make n cents with the given coins. If we denote the value of the kth coin by c_k, then the recurrence is:

nway(n, k) = no. of ways to make n cents with the first k types of coins
nway(n, k) = nway(n, k-1) + nway(n-c_k, k)

This just says the number of ways to make n cents with the first k coins is the number of ways to make n cents using the first k-1 coins (i.e., without using the kth coin) plus the number of ways to make n-c_k cents using the first k coins. For the second set of ways, we then add the kth coin to arrive at a total of n cents.

We keep track of the number of ways to total “n” cents in “nway”, updating the array as we read the value of each coin.

/*
PROG: money
ID: rsc001
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define MAXTOTAL 10000

long long nway[MAXTOTAL+1];

void
main(void)
{
	FILE *fin, *fout;
	int i, j, n, v, c;

	fin = fopen("money.in", "r");
	fout = fopen("money.out", "w");
	assert(fin != NULL && fout != NULL);

	fscanf(fin, "%d %d", &v, &n);

	nway[0] = 1;
	for(i=0; i<v; i++) {
		fscanf(fin, "%d", &c);

		for(j=c; j<=n; j++)
			nway[j] += nway[j-c];
	}

	fprintf(fout, "%lld\n", nway[n]);
}

Back to top