PTA甲级考试真题练习68——1068 Find More Coins

题目

在这里插入图片描述

思路

用map<int,int>存下每个币值的硬币数,然后从小往大试即可。有点类似背包问题的递归解法

代码

#include <iostream>
#include <stack>
#include <map>
using namespace std;

map<int, int> coins;
stack<int> res;

bool findCoins(int value) {
	for (auto it = coins.begin(); it != coins.end() && (*it).first <= value; it++) {
		if ((*it).second) {
			coins[(*it).first]--;
			if ((*it).first == value) {
				res.push((*it).first);
				return true;
			}
			else if (findCoins(value - (*it).first)) {
				res.push((*it).first);
				return true;
			}
			else {
				coins[(*it).first]++;
			}
		}
	}
	return false;
}

int main(int argc, char const* argv[])
{
	int n, m;

	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		int num;
		cin >> num;
		if (num <= m) {
			coins[num]++;
		}
	}

	if (findCoins(m)) {
		bool first = true;
		while (!res.empty()) {
			if (first) {
				first = false;
			}
			else {
				cout << " ";
			}
			cout << res.top();
			res.pop();
		}
	}
	else {
		cout << "No Solution";
	}
	return 0;
}
发布了153 篇原创文章 · 获赞 4 · 访问量 3799

猜你喜欢

转载自blog.csdn.net/qq_43647628/article/details/105274003
今日推荐