題目
傳送門: HDU-3348
“Yakexi, this is the best age!” Dong MW works hard and get high pay, he has many 1 Jiao and 5 Jiao banknotes(紙幣), some day he went to a bank and changes part of his money into 1 Yuan, 5 Yuan, 10 Yuan.(1 Yuan = 10 Jiao)
“Thanks to the best age, I can buy many things!” Now Dong MW has a book to buy, it costs P Jiao. He wonders how many banknotes at least,and how many banknotes at most he can use to buy this nice book. Dong MW is a bit strange, he doesn’t like to get the change, that is, he will give the bookseller exactly P Jiao.
input:
T(T<=100) in the first line, indicating the case number.
T lines with 6 integers each:
P a1 a5 a10 a50 a100
ai means number of i-Jiao banknotes.
All integers are smaller than 1000000.
output:
Two integers A,B for each case, A is the fewest number of banknotes to buy the book exactly, and B is the largest number to buy exactly.If Dong MW can’t buy the book with no change, output “-1 -1”.
Sample Input:
3
33 6 6 6 6 6
10 10 10 10 10 10
11 0 1 20 20 20
Sample Output:
6 9
1 10
-1 -1
題意
分別給出1,5,10,50,100角面值的紙幣張數,求湊出p角的最小張數和最大張數。
分析
- 最小:每次貪心選擇面值最大的紙幣來湊成p角,湊不成則輸出-1。
- 最大:用對立反面來求,用最小張數湊成它的反面,那麼剩餘張數就是湊成p的最大張數。設所有紙幣組成總價值sum和紙幣總數cnt,用上一點求湊成(sum-p)最小張數x,cnt-x即可。
代碼
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1000006;
int t, p, a[5], b[5] = { 1,5,10,50,100 };
int mi, ma, sum, cnt, fp, ti;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d%d%d%d%d", &p, &a[0], &a[1], &a[2], &a[3], &a[4]);
mi = ma = sum = cnt = 0;
for (int i = 0; i <= 4; i++) {
sum += b[i] * a[i];//紙幣總價值
cnt += a[i];//紙幣總數
}
fp = sum - p;
for (int i = 4; i >= 0; i--) {
ti = p / b[i];//最多換b[i]面值幾張
if (ti > a[i])ti = a[i];//超過題目輸入張數
mi += ti;
p -= ti * b[i];
}
if (p) {
printf("-1 -1\n");
continue;
}
for (int i = 4; i >= 0; i--) {
ti = fp / b[i];
if (ti > a[i])ti = a[i];
ma += ti;
fp -= ti * b[i];
}
printf("%d %d\n", mi, cnt - ma);
}
return 0;
}
你的點贊將會是我最大的動力