UVA 10626 Buying Coke (DP + 记忆化搜索)

本文探讨了一种特定场景下的硬币找零问题:在固定价格的自动贩卖机上购买多瓶饮料,并且每次购买仅能获取一瓶,如何利用不同面额的硬币达到最少硬币使用数量的目标。通过递归动态规划的方法,文章提供了一个具体的实现方案。

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

I often buy Coca-Cola from the vending machine at work. Usually I buy several cokes at once, since my working mates also likes coke. A coke in the vending machine costs 8 Swedish crowns, and the machine accept crowns with the values 15 and 10. As soon as I press the coke button (after having inserted sufficient amount of money), I receive a coke followed by the exchange (if any). The exchange is always given in as few coins as possible (this is uniquely determined by the coin set used). This procedure is repeated until I've bought all the cokes I want. Note that I can pick up the coin exchange and use those coins when buying further cokes.

Now, what is the least number of coins I must insert, given the number of cokes I want to buy and the number of coins I have of each value? Please help me solve this problem while I create some harder problems for you. You may assume that the machine won't run out of coins and that I always have enough coins to buy all the cokes I want.

Input

The first line in the input contains the number of test cases (at most 50). Each case is then given on a line by itself. A test case consists of four integers: C (the number of cokes I want to buy), n1n5n10 (the number of coins of value 15 and 10, respectively). The input limits are 1 <=C <= 1500 <= n1 <= 5000 <= n5 <= 100 and 0 <= n10 <= 50.

Output

For each test case, output a line containing a single integer: the minimum number of coins needed to insert into the vending machine.

Sample Input
3
2 2 1 1
2 1 4 1
20 200 3 0

Sample Output

5

3

148

一瓶可乐8块,,你有 1 块的 5 块的 10块的

你想买 n 瓶可乐,但是一次只能买一瓶,每次售货机返回你最少的零钱,

注意,,可以返还 5 块的,

用 f[a][b][c] 来记录各种钱的剩余,以及用了多少硬币。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int f[820][110][60];

int dp(int n, int a, int b, int c)
{
	if (n == 0) return 0;
	if (f[a][b][c] != -1) return f[a][b][c];
	int ans = INF;
	if (a >= 8) ans = min(ans,dp(n-1,a-8,b,c) + 8);
	if (b >= 2) ans = min(ans,dp(n-1,a+2,b-2,c) + 2);
	if (b >= 1 && a >= 3) ans = min(ans,dp(n-1,a-3,b-1,c) + 4);
	if (c >= 1) ans = min(ans,dp(n-1,a+2,b,c-1) + 1);
	if (a >= 3 && c >= 1) ans = min(ans,dp(n-1,a-3,b+1,c-1) + 4);
	if (ans == INF) ans = 0;
	f[a][b][c] = ans;
	return ans;
}
int main()
{
	int tt;
	scanf("%d",&tt);
	while(tt--)
	{	
		int n, a, b, c;
		scanf("%d%d%d%d",&n,&a,&b,&c);
		memset(f,-1,sizeof(f));
		int sum;
		sum = dp(n,a,b,c);
		printf("%d\n",sum);
	}	
	
	
	
} 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值