贪心 逆向思维 HDU 3348 coins

    xiaoxiao2021-03-25  61

    coins

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

    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 6 9 1 10 -1 -1

            刚拿的这个题的时候,想到求最小纸币数时,从面额大的纸币开始,每次选择尽可能多的大面额纸币,如果最终剩余金额p不为0,则说明不能凑整,同理,求最大纸币数时,从最小面额纸币开始,每次选择尽可能多的小面额纸币。在代码实现时,最小纸币数的求解没什么问题,但是,求最大纸币数时,不仅操作十分繁琐,而且漏洞百出。

            那么,怎样才能更简单地求得最小纸币数呢?其实,两个问题再求解的过程中有诸多相似的过程,既然,我们已经实现了求最小纸币数,运用逆向思维,通过求买完书后,剩余金额的最小纸币数,不就能得到买书金额的最大纸币数了吗?代码还是求最小纸币数的代码,只需要改几个变量就行了。

    代码

    #include <iostream> #include <cstdio> using namespace std; int a[6] = {0, 1, 5, 10, 50, 100}; int main() { int T, p; int total, sum;//总金额;总纸币数 int minn, maxn, mint;//minn/maxn:最小/最大纸币数;mint:剩余金额最小纸币数 int b[6]; scanf ("%d",&T); while (T--) { total = 0; sum = 0; minn = maxn = mint = 0; scanf ("%d",&p); for (int i=1; i<=5; i++) { scanf ("%d",&b[i]); sum += b[i]; total += b[i]*a[i]; } //求最小纸币数 int tmp = p; for (int i=5; i>=1; i--) { if (p/a[i] <b[i]) { minn += p/a[i]; p -= a[i]*(p/a[i]); } else { minn += b[i]; p -= a[i]*b[i]; } } if (p != 0) { printf ("-1 -1\n"); continue; } //求最大纸币数 //逆向求解,通过求买完书后,剩余金额的最小纸币数,从而得到买书的最大纸币数 int r = total-tmp;//剩余金额 for (int i=5; i>=1; i--) { if (r/a[i] < b[i]) { mint += r/a[i]; r -= a[i]*(r/a[i]); } else { mint += b[i]; r -= a[i]*b[i]; } } maxn = sum-mint; printf ("%d %d\n",minn,maxn); } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-36344.html

    最新回复(0)