有面值为1元、5元、10元、50元、100元、500元的硬币各C1, C5, C10, C100, C500枚。现需要用这些硬币来支付A元,最少要支付多少枚硬币?假设本题至少存在一种支付方案。
例如:C1 = 3, C5 = 2, C10 = 1, C50 = 3, C100 = 0, C500 = 2, A = 620
则需要支付6枚(500元1枚, 50元2枚, 10元1枚, 5元2枚, 合计6枚。注:只输出合计枚数)
Input Specification:
3 2 1 3 0 2
620
Output Specification:
6
解法1:
#include <stdio.h>
#define SIX 6
#define min(a, b) (((a) <= (b)) ? (a) : (b))
const int v[SIX] = {1, 5, 10, 50, 100, 500};
int c[SIX];
int A;
void read();
int calc_coins();
int main()
{
printf("%d\n", calc_coins());
return 0;
}
void read(){
int i;
for (i = 0; i < SIX; i++)
scanf("%d", &c[i]);
scanf("%d", &A);
}
int calc_coins(){
int i, t;
int ans = 0;
read();
for (i = SIX - 1; i >= 0; i--){
t = min(A / v[i], c[i]);
A -= t * v[i];
ans += t;
}
return ans;
}
解法2:
#include <stdio.h>
#define SIX 6
#define min(a, b) (((a) <= (b)) ? (a) :(b))
const int v[SIX] = {1, 5, 10, 50, 100, 500};
void read(int c[], int n, int *pA);
int calc_coins(int c[], const int v[], int n, int A);
int main()
{
int c[SIX];
int A;
read(c, SIX, &A);
printf("%d\n", calc_coins(c, v, SIX, A));
return 0;
}
void read(int c[], int n, int *pA){
int i;
for (i = 0; i < n; i++)
scanf("%d", &c[i]);
scanf("%d", pA);
}
int calc_coins(int c[], const int v[], int n, int A){
int i, t;
int ans = 0;
for (i = n - 1; i >= 0; i--){
t = min(A / v[i], c[i]);
A -= t * v[i];
ans += t;
}
return ans;
}