1068. Find More Coins (30)

来源:互联网 发布:百分百综合采集软件 编辑:程序博客网 时间:2024/06/02 17:19

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 95 9 8 7 2 3 4 1
Sample Output 1:
1 3 5
Sample Input 2:
4 87 2 4 3
Sample Output 2:
No Solution

找出加起来和为指定的数m的若干个数,如果答案不唯一,输出“最小的”。这里用动态规划来实现,首先要降序排序(要符合答案的要求)。用数组dp储存用i个硬币能否凑出j块钱,用used数组储存用i个硬币凑出j块钱时是否用的上第i个硬币。在循环过程中同时维护这两个数组,最后看用n个硬币是否能凑出m块(即dp[n][m]是否是真),如果不能输出"No Solution“,如果能就跟据used数组得到硬币。


代码:

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <vector>#include <algorithm>using namespace std;int main(){int n,m;scanf("%d %d",&n,&m);vector<int>a(n+1);for(int i=1;i<=n;i++){scanf("%d",&a[i]);}sort(a.begin()+1,a.end(),greater<int>());vector<vector<bool> >dp(n+1,vector<bool>(m+1,false));vector<vector<bool> >used(n+1,vector<bool>(m+1,false));for(int i=0;i<=n;i++) dp[i][0]=true;for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){if(j-a[i]>=0&&dp[i-1][j-a[i]]){dp[i][j]=true;used[i][j]=true;}else{dp[i][j]=dp[i-1][j];}}}if(!dp[n][m]){printf("No Solution\n");}else{int i=n,j=m;vector<int>res;while(j){while(!used[i][j]) i--;res.push_back(a[i]);j-=a[i];i--;}printf("%d",res[0]);for(int k=1;k<res.size();k++){printf(" %d",res[k]);}}}


0 0
原创粉丝点击