Problem Description
"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
简单题意:
Dong拥有很多1角、5角,并且换到了1元、5元、10元的纸币。他要买一本书,并且他不喜欢找零钱,所以编写一个程序求出最小的纸币张数和最大的纸币张数。
解题思路形成过程:
这是考验思路以及逻辑思维能力的题目。我真是没想出来,用自己的思路编写得到的代码太长,自己都没把握AC。所以,我搜索了类似的算法,最终从无到有把这类题型烂熟于心。
感想:
一步一步分解,逐步就能求出最佳的解。
AC代码:
#include <iostream>
#include <algorithm>
using namespace std;
int min(int a[],int p,int num[])
{
int cnt=0;
for(int i=5;i>1;i--)
if(p>=num[i]*a[i])
{
cnt+=num[i];
p-=a[i]*num[i];
}//当书的价格比当前的钱数还要大时,执行;
else
{
cnt+=p/a[i];//不能用掉所有a[i]角纸币时,只需要最高位数字就可以。这必然是最优的方式;
p=p%a[i];
}
if(p>num[1])return -1;
else return cnt+p;
}
int max(int a[],int num[],int sum[],int p)
{
int cnt=0;
for(int i=5;i>1;i--)
{
if(p<=sum[i-1])continue;
else
{
int b,c,d;
b=(p-sum[i-1])/a[i];
cnt+=b;
c=(p-sum[i-1])%a[i];
if(c!=0)
{
cnt+=1;
d=b+1;
}
else d=b;
p-=a[i]*d;
}
}
if(p>num[1])return -1;
else return cnt+p;
}
void greedy_select(int a[],int num[],int p)
{
int sum[6];
sum[0]=0;
sum[1]=num[1]*1;
for(int i=2;i<5;i++)
sum[i]=sum[i-1]+a[i]*num[i];
int minNum,maxNum;
minNum=min(a,p,num);
if(minNum==-1)cout<<"-1 -1"<<endl;
else
{
maxNum=max(a,num,sum,p);
if(maxNum==-1)cout<<"-1 -1"<<endl;
else cout<<minNum<<" "<<maxNum<<endl;
}
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int num[6],p,a[6]={0,1,5,10,50,100},sum=0;
cin>>p;
for(int j=1;j<6;j++)
{
cin>>num[j];
sum+=num[j]*a[j];
}
if(sum<p)cout<<"-1 -1"<<endl;
else greedy_select(a,num,p);
}
}
return 0;
}