Find More Coins (30)

Find More Coins (30)
题目连接

题目描述
Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she must pay the exact amount. Since she has as many as 104 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find some coins to pay for it.

输入描述:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=104, the total number of coins) and M(<=102, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

输出描述:
For each test case, print in one line the face values V1 <= V2 <= … <= Vk such that V1 + V2 + … + Vk = M. All the numbers must be separated by a space, and there must be no extra space at the end of the line. If such a solution is not unique, output the smallest sequence. If there is no solution, output “No Solution” instead.
Note: sequence {A[1], A[2], …} is said to be “smaller” than sequence {B[1], B[2], …} if there exists k >= 1 such that A[i]=B[i] for all i < k, and A[k] < B[k].

输入例子:
8 9
5 9 8 7 2 3 4 1

输出例子:
1 3 5


大意:给你m个额度不同的硬币(m最大为10000,相同额度的硬币可重复),给出一个面额n。要求从这m个硬币中找出最佳组合使得组合中的硬币面额加起来等于n。最佳指字典序最小。
思路:
首先对输入的硬币进行排序,然后使用递归方式(dfs)求解,注意题目说道n<=10^2,且硬币都是整数,在前一百个硬币以内必能判断是否能找到组合。因为硬币已经小到大排序好,所以找到的第一个组合就是最佳组合。

My Code:

#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 10009;
int eoa = 0;			//the end of the coin-array
int coin[maxn];			//the value of each coin
vector<int>ans;			//save conin that have been choose

int recusion(int index, int need){
	if (index >= eoa)return -1;	//cant not find an answer
	int now = coin[index];
	if (now > need) return -1;	//cant not find an answer
	if (need == now){			//finally find the last choosed coin
		ans.push_back(now);
		return need;
	}
	int res = recusion(index + 1, need - now); //take this coin
	if (res != -1){
		ans.push_back(now);
		return res;
	}
	return recusion(index + 1, need);	//dont take it coin
}
int main(){
	int m;	
	cin >> eoa >> m;
	for (int i = 0; i < eoa; i++){
		cin >> coin[i];
	}
	sort(coin, coin + eoa);
	int res = recusion(0, m);
	if (res != -1){
		for (int i = ans.size()-1; i>0; i--){
			cout << ans[i] << " ";
		}
		cout << ans[0]<< endl;
	}
	else cout << "No Solution" << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值