题目
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 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.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: , the total number of coins and , 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.
Output Specification:
For each test case, print in one line the face values such that . 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]
.
Sample Input 1:
8 9
5 9 8 7 2 3 4 1
Sample Output 1:
1 3 5
Sample Input 2:
4 8
7 2 4 3
Sample Output 2:
No Solution
题目大意
给定N个硬币,以及对应的面值,以及要付的款M,找出能够满足付款M面值的最小排序硬币组合。
解题思路
- 首先应想到动态规划;
- 对输入数据按小到大排序,方便动态规划选取;
- 因为输入数据已排序,所以动态规划应优先考虑选取当前数;
- 当选取的数之和等于M时,动规就可以结束了,因为我们是优先选取较小数的,所以先得到的那组结果一定是最优结果;
- 递归层数容易调用过深,造成题目超时,当所有硬币面值之和小于M时,特判一下,直接输出。
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int n, m;
vector<int> coin(10000), temp, ans;
int t = 0, ok = 0;
void dp(int i){
if(t == m){
ans = temp;
ok = 1;
return;
}
if(i == n || t > m || ok)
return;
t += coin[i], temp.push_back(coin[i]); // 优先考虑较小数
dp(i+1);
t -= coin[i], temp.pop_back();
dp(i+1);
}
int main(){
int sum = 0;
scanf("%d%d", &n, &m);
for(int i=0; i<n; i++){
scanf("%d", &coin[i]);
sum += coin[i];
}
if(sum < m){
printf("No Solution");
return 0;
}
sort(coin.begin(), coin.begin()+n);
dp(0);
if(ans.empty())
printf("No Solution");
else
for(int i=0; i<ans.size(); i++){
if(i)
printf(" ");
printf("%d", ans[i]);
}
printf("\n");
return 0;
}
来源:CSDN
作者:李小白~
链接:https://blog.csdn.net/qq_40941722/article/details/104512275