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

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);
	}	
	
	
	
} 



猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/79326083