UVa 11259 - Coin Changing Again
Table of Contents
This took lot of my time and I managed to come up with this Top-down Dynamic Programming solution. This approach times out. Any suggestions? Problem Statement : http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2226\\
1# include <cstdio>
2# include <map>
3# include <set>
4using namespace std;
5struct State
6{
7 State (int v1, int v2, int v3, int v4)
8 {
9 V1 = v1; V2 = v2; V3 = v3; V4 = v4;
10 }
11 int getPart2(int Value = 0)
12 {
13 int Part2 = 0;
14 Part2 = (V4 >> 13);
15 Part2 |= (Value << 4);
16 return Part2;
17 }
18 unsigned long long getPart1()
19 {
20 unsigned long long Part1 = 0;
21 Part1 = V1;
22 Part1 |= (V2 << 17);
23 Part1 |= ((unsigned long long)V3 << 34);
24 Part1 |= ((unsigned long long)V4 << 51);
25 return Part1;
26 }
27 int V1, V2, V3, V4;
28};
29map <int, set<unsigned long long> > States;
30map <int, set<unsigned long long> > Solutions;
31int c1, c2, c3, c4, q, d1, d2, d3, d4, v;
32unsigned long long Result ;
33bool CheckVisited (unsigned long long Part1, int Part2)
34{
35 if (States[Part2].count (Part1)) return true;
36 States[Part2].insert (Part1);
37 return false;
38}
39void Solution (State & s, int Value)
40{
41 unsigned long long Part1 = s.getPart1();
42 int Part2 = s.getPart2(Value);
43 if (!Value)
44 {
45 Solutions[Part2].insert (Part1);
46 return;
47 }
48 if (CheckVisited(Part1, Part2)) return;
49 if (s.V1 - 1 >= 0 && Value - c1 >= 0)
50 {
51 s.V1--;
52 Solution (s, Value - c1);
53 s.V1++;
54 }
55 if (s.V2 - 1 >= 0 && Value - c2 >= 0)
56 {
57 s.V2--;
58 Solution (s, Value - c2);
59 s.V2++;
60 }
61 if (s.V3 - 1 >= 0 && Value - c3 >= 0)
62 {
63 s.V3--;
64 Solution (s, Value - c3);
65 s.V3++;
66 }
67 if (s.V4 - 1 >= 0 && Value - c4 >= 0)
68 {
69 s.V4--;
70 Solution (s, Value - c4);
71 s.V4++;
72 }
73}
74int main()
75{
76 freopen ("Input.txt", "r", stdin);
77 freopen ("Scratch.txt", "w", stdout);
78 int N;
79 scanf ("%d", &N);
80 State s (0, 0, 0, 0);
81 while (N--)
82 {
83 scanf ("%d%d%d%d%d", &c1, &c2, &c3, &c4, &q);
84 while (q--)
85 {
86 scanf ("%d%d%d%d%d", &s.V1, &s.V2, &s.V3, &s.V4, &v);
87 Result = 0;
88 States.clear();
89 Solutions.clear();
90 Solution (s, v);
91 for (map<int, set<unsigned long long> >::iterator it = Solutions.begin(); it != Solutions.end(); it++)
92 Result += it->second.size();
93 printf ("%lld\n", Result);
94 }
95 }
96}