1068 Find More Coins (30分)(dp)

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 1 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 (≤, the total number of coins) and M (≤, 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 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 k1 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

题目分析:读题后觉得这是一道动态规划 自己写的动态规划只过了4个测试点

查了别人的做法后 https://blog.csdn.net/qq_29762941/article/details/82903476
利用深度遍历优先也可以求解 而且正是因为需要最小的序列 利用dfs更容易求得
 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <climits>
 3 #include<iostream>
 4 #include<vector>
 5 #include<queue>
 6 #include<map>
 7 #include<set>
 8 #include<stack>
 9 #include<algorithm>
10 #include<string>
11 #include<cmath>
12 using namespace std;
13 int Array[10000];
14 int N, M;
15 vector<int> res, v;
16 int flag = 0;
17 void dfs(int i,int sum,int &flag)
18 {
19     if (sum > M || flag == 1)
20         return;
21     if (sum == M && flag == 0)
22     {
23         res = v;
24         flag = 1;
25         return;
26     }
27     for (int index = i; index < N; index++) {
28         v.push_back(Array[index]);
29         dfs(index + 1, sum + Array[index], flag);
30         v.pop_back();
31     }
32 }
33 
34 int main()
35 {
36     cin >> N >> M;
37     int total=0;
38     for (int i = 0; i < N; i++)
39     {
40         cin >> Array[i];
41         total += Array[i];
42     }
43     if (total < M)
44     {
45         cout << "No Solution";
46         return 0;
47     }
48     sort(Array, Array + N);
49     dfs(0, 0, flag);
50     if (!flag)
51         cout << "No Solution";
52     else
53     {
54         int i = 0;
55         for (; i < res.size() - 1; i++)
56             cout << res[i] << " ";
57         cout << res[i];
58     }
59 }
View Code

动态规划的方法 看了柳神的博客


猜你喜欢

转载自www.cnblogs.com/57one/p/12073389.html