[Programming questions] Change

The currency system of country Z includes 4 kinds of coins with a face value of 1, 4, 16 and 64 yuan, as well as a banknote with a face value of 1024 yuan. Now Xiao Y uses 1024 yuan banknotes to buy a product with a value of N (0 <N \le 1024)N (0<N≤1024), how many coins will he receive at least?
Enter a description:

一行,包含一个数N。

Output description:

一行,包含一个数,表示最少收到的硬币数。

Example:

输入
200
输出
17
说明
花200,需要找零824块,找1264元硬币,316元硬币,24元硬币即可。

Remarks:

对于100%的数据,N (0 < N \le 1024)N(0<N≤1024)

Analysis: Greedy is not necessarily right, it is recommended to use dynamic programming

#include <iostream>
#include <vector>
using namespace std;

int min(int a,int b)
{
    
    
	return (a < b) ? a : b;
}

int ans(int num)
{
    
    
	//为了取最小,先塞最大的给数组,可计算0~num的找零
	vector<int> dp(num + 1, num + 1);
	//初始化0块钱
	dp[0] = 0;
	//建立货币系统
	int money[] = {
    
     1,4,16,64 };
	//从1块钱开始,到第num块钱
	for(int i=1;i<=num;i++)
	{
    
    
		//从塞1块钱开始,慢慢塞大钱以取最小值
		for(int j=0;j<4;j++)
		{
    
    
			//看现在的钱可以用什么样的货币支付
			if(i>=money[j])
			{
    
    
				dp[i] = min(dp[i], dp[i - money[j]] + 1);
			}
		}
	}
	return dp[num];
}
int main()
{
    
    
	int N;//商品价格
	cin >> N;
	cout << ans(1024 - N) << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/114806666