UVa 166 - Making Change

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址
中文網址

Solution

可以先把每次要找的零錢中所需的各錢幣數記下(貪心去做即可)。

DP[n]: 湊得 n 所需的最少錢幣數,如湊不出來就是 1e9。

接著以各錢幣和其擁有的個數,去更新 DP[],要從總價錢高做到小,才不會使用超出擁有的錢幣數。

接著再去找 付出的零錢 + 大於價錢時的找零,最小的即為答案。

Code

UVa 166
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
#include <cstdio>
#include <cstring>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define N 601

int main()
{
//freopen("test.out", "w", stdout);
const int coin[6] = {5, 10, 20, 50, 100, 200};
int have[6];
int dp[N] = {}; //the number of coins
int change[201] = {}; //該數目零錢所需的錢幣數(除不盡的零錢數在本題不會使用到)
for (int i = 5; i < 201; ++i)
{
int back = i;
for (int k = 5; k >= 0 && back; --k)
{
change[i] += back / coin[k];
back %= coin[k];
}
}

while (scanf("%d%d%d%d%d%d", &have[0], &have[1], &have[2], &have[3], &have[4], &have[5]))
{
int sum = 0;
for (int i = 0; i < 6; ++i)
sum += coin[i] * have[i];
if (!sum)
return 0;

int a, b, price;
scanf("%d.%d", &a, &b);
price = a * 100 + b;

for (int i = 1; i < N; ++i)
dp[i] = 1e9;

for (int i = 0; i < 6; ++i)
for (int k = have[i]; k; --k)
for (int p = MIN(600, sum); p >= coin[i]; --p)
{
int tmp = p - coin[i];
if (dp[tmp] < 1e9)
dp[p] = MIN(dp[tmp] + 1, dp[p]);
}

//最多 500,但可以用 3*200 = 600 來付
int min = 1e9;
for (int p = MIN(600, sum); p >= price; --p)
{
if (dp[p] < 1e9)
{
if (p > price)
dp[p] += change[p - price];

if (dp[p] < min)
min = dp[p];
}
}

printf("%3d\n", min);
}

return 0;
}