HDU 3348 coins

该题意:给你一个价格,还有面值分别为1,5,10,50,100(单位:毛)纸币的数量,要你用最少数量的纸币和最多数量的凑出这个价格,输出最少和最多的数量。

最少的数量要用贪心的思想,优先取面值尽量大 的纸币来凑这个价格。

而最多的数量网上许多算法提供的方法多是用较小的纸币去补较大的纸币,这里提供另一种想法:因为我们要求的是花的最多数量纸币,所以就是要保证手上的纸币数量最少!!这样想的话问题就比较简单了,就转化为最少数量问题了。假设手上总共有p毛,而价格为q毛,我们用手上最少的数量的纸币去凑(p-q)毛,然后再用总数量减去该最少数量即可。

 

               

coins

问题描述 :

"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.

输入:

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.

输出:

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.

样例输入:

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

 

代码比较简陋,跟大家分享想法为主:

 

 

#include "stdio.h"
#include "string.h"

int b[10]={0,1,5,10,50,100};
int main()
{
    int t;
    int p,r;
    int a[10],c[10],e[10];
    int i,j,k,sum;

    scanf("%d",&t);
    while(t--)
    {
        sum=0;
        scanf("%d",&p);
        r=p;
        for(i=1;i<=5;i++)
        {
            scanf("%d",&a[i]);
            sum=sum+b[i]*a[i];
        }
        for(i=5;i>0;i--)
        {
            if(r/b[i]<a[i])
            {
                c[i]=r/b[i];
                r=r-b[i]*c[i];
            }
            else
            {
                c[i]=a[i];
                r=r-c[i]*b[i];
            }
        }
        if(r!=0)
        {
            printf("-1 -1\n");
        }else
        {
            k=sum-p;
            for(i=5;i>0;i--)
            {
                if(k/b[i]<a[i])
                {
                    e[i]=k/b[i];
                    k=k-b[i]*e[i];
                }
                else
                {
                    e[i]=a[i];
                    k=k-e[i]*b[i];
                }
            }
            if(k==0)
            {
                printf("%d %d\n",c[1]+c[2]+c[3]+c[4]+c[5],(a[1]+a[2]+a[3]+a[4]+a[5]-(e[1]+e[2]+e[3]+e[4]+e[5])));
            }
            
        }    

    }
}

posted @ 2014-08-12 16:38  Joker.  阅读(494)  评论(0)    收藏  举报