“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的商品,求所花硬币数量最少和最多各是多少?
解析:
最少是多少好弄,贪心算法嘛!但是最多怎么弄?这里我们就要换个思路了!所花的硬币最多,则剩下的银币最少,这还是贪心!这就是两次贪心嘛!
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int book[10];
int money[5]={1,5,10,50,100};
int main()
{
int T,p,sum,Minum,Manum,num;
scanf("%d",&T);
while(T--)
{
Minum=0,Manum=0,num=0;
scanf("%d",&p);
sum=p;
for(int i=1;i<=5;i++)
{
scanf("%d",&book[i]);
}
int n;
for(int i=5;i>0;i--)
{
if(sum<money[i-1]||!book[i])
continue;
n=min(sum/money[i-1],book[i]);
sum-=money[i-1]*n;
Minum+=n;
}
if(sum!=0)
printf("-1 -1\n");
else
{
for(int i=1;i<=5;i++)
{
sum+=book[i]*money[i-1];
num+=book[i];
}
sum-=p;
for(int i=5;i>0;i--)
{
if(sum<money[i-1]||!book[i])
continue;
n=min(sum/money[i-1],book[i]);
sum-=money[i-1]*n;
Manum+=n;
}
printf("%d %d\n",Minum,num-Manum);
}
}
return 0;
}