PAT(动态规划)——1068. 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.
Input Specification:
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.
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 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
题目大意:
eva有n个有面值的硬币,现在要从中选择一些组成面值大小正好为m,如果没有方案输出no solution,有的话输出字典序最小的序列。
题目解析:
01背包问题+记录最小序列。
用dp[i][j] 表示面值不超过j的前i个硬币能够组成的最大和。
weight[i]表示第i个硬币的面值。
因此得到状态转移方程,dp[i][j]=max{dp[i-1][j],dp[i-1][j-weight[i]]+weight[i]}。
为了记录最小序列,flag[i][j]表示在面值等于j时选择了i硬币。
具体代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
#define MAXN 10005
int weight[MAXN];//weight[i] 第i个硬币的面值
int dp[MAXN][105];//dp[i][j] 表示面值不超过j的前i个硬币能够组成的最大和
bool flag[MAXN][105];//flag[i][j] 表示在面值等于j时选择了i硬币
bool cmp(int a,int b){
return a>b;
}
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=1;j<=m;j++){
if(j<weight[i]) dp[i][j]=dp[i-1][j];
else{
if(dp[i-1][j]>dp[i-1][j-weight[i]]+weight[i])//比较不使用和使用第i个硬币所组成的最大面值
dp[i][j]=dp[i-1][j];
else{
dp[i][j]=dp[i-1][j-weight[i]]+weight[i];
flag[i][j]=true;
}
}
}
if(dp[n][m]<m)
printf("No Solution");
else{
int i=n;
while(m){
while(flag[i][m]==false)
i--;
m-=weight[i];
if(m==0)
printf("%d",weight[i]);
else
printf("%d ",weight[i]);
i--;
}
}
return 0;
}