【贪心算法】硬币问题

Description
有1元、5元、10元、50元、100元、500元的硬币各c1、c5、c10、c50、c100、c500枚。现在要用这些硬币来支付A元,最少需要多少枚硬币?假定本题至少存在一种支付方案。

Input
一行c1、c5、c10、c50、c100、c500、A,中间用空格隔开。

Output
最少的硬币数量。

Sample Input
3 2 1 3 0 2 620
Sample Output
6
HINT
【注释】

500元硬币1枚,50元硬币2枚,10元硬币1枚,5元硬币2枚,合计6枚。
【限制条件】

0<= c1、c5、c10、c50、c100、c500<=10^9

0<=A<=10^9

采用深搜。

代码:

#include <iostream>

#define SIZE 501

using namespace std;

int a[SIZE], c[6] = {500, 100, 50, 10, 5, 1};

int dfs(int l, int k) // 深度优先搜索
{
	int i;
	
	if (!l)
	{
		return k;
	}
	for (i = 0; i < 6; i++)
	{
		if ((l >= c[i]) && (a[c[i]]))
		{
			a[c[i]]--; // 数量-1
			return dfs(l - c[i], k + 1); // 继续搜索
		}
	}
}

int main(int argc, char** argv)
{
	int l;
	
	cin >> a[1] >> a[5] >> a[10] >> a[50] >> a[100] >> a[500] >> l; // 读入数据
	
	cout << dfs(l, 0) << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/80258580