A1068 Find More Coins (30 point(s))

动态规划--01背包

1. 原文

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.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤10^4, the total number of coins) and M (≤10^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 V1≤V2≤⋯≤V**k such that V1+V2+⋯+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:

1
2
8 9
5 9 8 7 2 3 4 1

Sample output 1:

1
1 3 5

Sample Input 2:

1
2
4 8
7 2 4 3

Sample output 2:

1
No Solution

2. 解析

前i个数恰好组成和为m的背包所能获得的价值m dp[m]

  • 选择了i,就等于前i-1个数恰好组成和为m-weight[i]的背包dp[i-weight[i]]+weight[i]
  • 不选择i,就等于前i-1个数恰好组成和为dp[m]

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int weight[10010]={};
int dp[10010]={};
bool choose[10010][110];
bool cmp(int x,int y){
return x>y;
}
vector<int> ans;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for (int i = 1; i <= n; ++i)
{
scanf("%d",&weight[i]);
}
sort(weight+1,weight+n+1,cmp);
for (int i = 1; i <= n; ++i)
{
for (int j = m; j >= weight[i] ; j--)
{
if (dp[j]<=dp[j-weight[i]]+weight[i])
{
dp[j]=dp[j-weight[i]]+weight[i];
choose[i][j]=true;
}
}
}
if (dp[m]!=m)
{
printf("No Solution\n");
return 0;
}
int v=m; int idx=n;
while(v>0){
if (choose[idx][v])
{
ans.push_back(weight[idx]);
v-=weight[idx];
}
idx--;
}
for (int i = 0; i < ans.size(); ++i)
{
if (i!=0)
{
printf(" ");
}
printf("%d",ans[i]);
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1068/
  • 发布时间: 2019-09-03 12:32
  • 更新时间: 2021-10-29 14:03
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!