1068 Find More Coins (30分)

痴心易碎 提交于 2020-02-26 11:52:59

题目

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 10410^4 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: N(104N(\le10^4, the total number of coins)) and M(102M(\le10^2, 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 V1V2VkV_1\le V_2\le\cdots\le V_k such that V1+V2++Vk=MV_1 + V_2 + \cdots +V_k=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].

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面值的最小排序硬币组合。

解题思路

  1. 首先应想到动态规划;
  2. 对输入数据按小到大排序,方便动态规划选取;
  3. 因为输入数据已排序,所以动态规划应优先考虑选取当前数;
  4. 当选取的数之和等于M时,动规就可以结束了,因为我们是优先选取较小数的,所以先得到的那组结果一定是最优结果;
  5. 递归层数容易调用过深,造成题目超时,当所有硬币面值之和小于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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!