coins
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1864 Accepted Submission(s): 596
"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.
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.
3 33 6 6 6 6 6 10 10 10 10 10 10 11 0 1 20 20 20
6 9 1 10 -1 -1
基本的思路:(数学+贪心)
分为从最大的取和从最小的取,从最大的取比较容易,一直取下去就可以了,从最小的取得时候要考虑把小的换成大的,不过这个操作只有一次机会,不成功的话大的coin也不会成功。(但是开始用最小的补时,需要考虑找到满足条件的最小纸币总数对应的值)(==我用的是暴力,看了看其他队友的代码,还是觉得暴力更好理解(捂脸))。
碰见数学的题一直就不太会敲。。。。。
已经AC过的代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int t,s;
int a[7];//面值为c[i]的硬币剩余的个数为a[i]个
int b[7];//面值为c[i]的硬币用来b[i]个
int c[7]={0,1,5,10,50,100};
scanf("%d",&t);
while(t--)
{
scanf("%d",&s);
for(int i=1;i<=5;i++)
{
scanf("%d",&a[i]);
}
int x=s;
int min=0,max=0;
memset(b,0,sizeof(b));
for(int i=5;i>=1;i--)//因为先从最大的开始取,所以减减
{
if(x>=c[i])//如果所需书的价格大于最大的
{
int num=x/c[i];//求出所需最大的钱币的总数量
if(num>a[i])//如果这个总数量大于剩余的个数
num=a[i];
min+=num;//记录一下所需的总数量
a[i]-=num;//求出下一次剩余钱币的数量
b[i]=num;
x-=num*c[i];//求出每一次还需要多少硬币来买书
}
}
if(x!=0)
min=-1;//如果x!=0,则说明所有的钱都花完了,但是仍然不够买书,因此输出-1,-1
if(min==-1)
{
printf("-1 -1\n");
continue;
}
max=min;//求最大值,就是将大的尽量转换成小的
while(1)
{
int flag=1;//标记一下是否有转换
for(int i=5;i>1;i--)
{
if(b[i])//用的个数
{
for(int j=i-1;j>=1;j--)//
{
if(b[i]==0)
break;
//开始转换
if(a[j]*c[ j ]>=c[i])//如果比i小的硬币还有剩余的话,且总的剩余的面值大于或等于i的面值
{
int x=a[ j ]*c[ j ]/c[i];//则计算出可以转换的数量
if(x>=b[i])//如果这个数量大于等于该大的面值的数量时
{
max=max-b[i]+c[i]*b[i]/c[ j ];//可以转换成小面值的张数
b[ j ]+=c[i]*b[i]/c[ j ];
a[i]+=b[ j ];
a[ j ]=a[j]-c[i]*b[i]/c[ j ];
b[i]=0;
flag=0;
}
else
{
max=max-x+c[i]*x/c[ j ];//如果该部分的数量不够时,
b[ j ]+=c[i]*x/c[ j ];//可以转换成小面值的张数
a[i]+=x;//记录张数
a[ j ]-=c[i]*x/c[ j ];
b[i]-=x;
flag=0;
}
}
}
}
}
if(flag)
break;
}
printf("%d %d\n",min,max);
}
return 0;
}