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 1Sample Output 1:
1 3 5Sample Input 2:
4 8 7 2 4 3Sample Output 2:
No Solution
思路:典型的背包问题,用DP做,关键是要找出状态方程:
(1)DP[ i ][ j ] = max { DP[ i-1] [ j ] , DP[ i-1 ][ j - price[ i ] ] + price[ i ] }
简单解释:max中的两个参数表示的含义:
1、价格j 无法用包含price[ i ]表示,用前i-1枚硬币表示 2、可以有price[ i ]用前i-1枚表示价格j-price[ i ],再加入price[ i ]刚好够!
其中price[ i ]为第 i 枚硬币的值 其中 price[ i ]经过排序,为降序数组
这里的DP[ i ][ j ]表示i 枚硬币能表示的<=j的最大值 其中 代码中的hasIt[ i ][ j ]用来记录DP[ i ][ j ]中是否包括price[ i ](这里 j 表示价格)
AC参考代码:
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;
int price[10001];
int priceArr[10001][101];
int hasIt[10001][101]; //标记priceArr[i][j]中是否包括price[i]项
int M,N;
int compare(int a,int b){
return a>b;
}
int main()
{
//ifstream cin("1.txt");
cin>>N>>M;
int index = 1; //记录符合条件的硬币的种类个数
for(int i=0;i<N;i++){
int temp = 0;
cin>>temp;
if(temp<=M){ //过滤那些值大于M的值
price[index++] = temp;
}
}
sort(price+1,price+index,compare); //因为最后的输入要按照字典排序,所以这边按照降序排序
for(int i=1;i<index;i++){
for(int j=1;j<=M;j++){
if(j>=price[i]){ //到达<=j时的最大值可以包括price[i]
if(priceArr[i-1][j]>priceArr[i-1][j-price[i]]+price[i]){ //包括price[i]比没包括要小
priceArr[i][j] = priceArr[i-1][j];
hasIt[i][j] = 0; //标记没有包括price[i]
}else{
priceArr[i][j] = priceArr[i-1][j-price[i]]+price[i];
hasIt[i][j] = 1; //包括price[i]
}
}else{
priceArr[i][j] = priceArr[i-1][j];
hasIt[i][j] = 0; //标记没有包括price[i]
}
}
}
if(priceArr[index-1][M]!=M){ //输入的硬币种类无法准确满足支付的M的值
cout<<"No Solution";
return 0;
}else{
while(M>0){
if(hasIt[index-1][M]){ //从index-1向前遍历只要hasIt标记为1的就输出
cout<<price[index-1];
M -= price[index-1];
if(M>0)
cout<<" ";
}
index--;
}
}
return 0;
}