include iostream include vector using namespace std vector vector unsi

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
using namespace std;
vector< vector<unsigned long long> > cache;
unsigned long long compress(const vector<unsigned> &coins, unsigned n, unsigned i)
{
unsigned long long result = 0;
if (!n)
return 0;
if (coins[i] == 1)
return 1;
const unsigned n_coins = n / coins[i];
if (!n_coins)
{
unsigned long long *cached_value = &cache[n][i - 1];
if (!*cached_value)
*cached_value = compress(coins, n, i - 1);
return *cached_value;
}
for (unsigned j = 0; j <= n_coins; ++j)
{
const unsigned piece_to_cut = j * coins[i];
if (piece_to_cut == n)
++result;
else if (i > 1)
{
const unsigned remainder = n - piece_to_cut;
unsigned long long *cached_value = &cache[remainder][i - 1];
if (!*cached_value)
*cached_value = compress(coins, remainder, i - 1);
result += *cached_value;
}
else
++result;
}
return result;
}
unsigned long long solve_v3(unsigned n, const vector<unsigned> &coins)
{
if (cache.size() < n + 1)
cache.resize(n + 1);
for (unsigned i = 0; i < cache.size(); ++i)
{
if (cache[i].size() < coins.size())
cache[i].resize(coins.size());
}
return compress(coins, n, coins.size() - 1);
}
int main()
{
vector<unsigned> coins;
coins.push_back(1);
coins.push_back(5);
coins.push_back(10);
coins.push_back(25);
coins.push_back(50);
unsigned n;
while (cin >> n)
{
unsigned long long solutions = solve_v3(n, coins);
if (solutions > 1)
cout << "There are " << solutions << " ways to produce " << n << " cents change.\n";
else
cout << "There is only 1 way to produce " << n << " cents change.\n";
}
}