hdu-3348 coins(贪心法)

本文探讨了一道编程题,涉及如何利用一角、五角、一元等不同面额的钞票,计算最少和最多数量来恰好支付固定金额的书籍费用,同时避免找零。通过贪心算法求解最少钞票数,反转问题思路求解最多钞票数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

coins

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3592 Accepted Submission(s): 1300

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

题意

输入

T(T<=100),表示案例编号。

各有6个整数的T行:

P a1 a5 a10 a50 a100

ai是指一角钞票的数量。

所有整数都小于1000000。

输出

两个整数A,B分别代表每一种情况,A是买书最少的钞票数,B是买书最多的钞票数。如果不能用手上的钱刚刚好付款,输出“-1-1”。

分析

买书最少的钞票数直接用贪心就可以求,因为包含面值为1毛的钞票,所以不要担心用贪心无解。比较难的是买书最多的钞票数怎么求?这里作了一些转变,因为要求买书最多的钞票数A,那么可以反过来求买完书后剩余最少钞票数B。然后设总钞票数为C,则A=C-B。

代码

#include<iostream>
using namespace std;
const int N = 5;
int num[N];
int jiao[N]={1,5,10,50,100};
int main()
{
//	freopen("data.txt","r",stdin);
	int t;
	scanf("%d",&t);
	while(t--){
		int P,Q=0,coins=0;//P为题目要求面额,Q为总面额,coins为硬币总数 
		bool flag=true;
		scanf("%d",&P);
		for(int i=0;i<N;i++) {
			scanf("%d",&num[i]);
			Q+=num[i]*jiao[i];
			coins+=num[i];
		}
//		printf("Case\n");
		int sum=P,f=0,l=0;
		for(int i=N-1;i>=0;i--){
			int k=sum/jiao[i];
//			printf("%d\n",k);
			if(k<=num[i]){
				sum-= k*jiao[i];
				f+=k;
			}
			else{
				sum-= num[i]*jiao[i];
				f+=num[i];
			}
			if(sum==0) break;
		}
		if(sum) flag=false;
//		printf("-----");
		sum=Q-P;
		for(int i=N-1;i>=0;i--){
			int k=sum/jiao[i];
//			printf("%d\n",k);
			if(k<=num[i]){
				sum-= k*jiao[i];
				l+=k;
			}
			else{
				sum-= num[i]*jiao[i];
				l+=num[i];
			}
			if(sum==0) break;
		}
		if(sum) flag=false;
		if(!flag) printf("-1 -1\n");
		else printf("%d %d\n",f,coins-l);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值