PAT 1068. Find More Coins (30)

来源:互联网 发布:统计软件app 编辑:程序博客网 时间:2024/05/16 04:54

1068. Find More Coins (30)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

这道题是一个经典packing问题,用DP来解决。因为题目要求输出最小的序列,因此首先要对输入进行降序排序。然后思想是,从第一个位置开始,求出每一个位置在限定条件下所能得到的最大数(不超过题目给的限制,也就是M)。针对任意位置 i ,其在限定条件M下的最大数f(i,M) 为 f(i,M) = max{ f(i-1,M) , f(i-1,M-raw[i])+raw[i] },其中raw[i] 即为在i位置上的数。代码如下: 

#include <iostream>#include <algorithm>#include <cmath>#include <vector>#include <map>#include <set>#include <cstring>using namespace std;int M,N;int path[10001][101];int flag[10001][101];vector<int> raw;int findpath(int pos,int limit){for(int i=1;i<=pos;i++){for(int j=1;j<=limit;j++){if(j<raw[i]||path[i-1][j]>path[i-1][j-raw[i]]+raw[i])path[i][j]=path[i-1][j];else{path[i][j]=path[i-1][j-raw[i]]+raw[i];flag[i][j]=1;}}}return path[pos][limit];}bool cmp(int a,int b){return a>b;}int main(void){cin>>N>>M;raw.resize(N+1);memset(path,0,sizeof(path));memset(flag,0,sizeof(flag));int i;for(i=1;i<N+1;i++)cin>>raw[i];raw[0]=999999;sort(raw.begin(),raw.end(),cmp);if(findpath(N,M)!=M)cout<<"No Solution";else{bool judge=true;  while(M){  while(!flag[N][M])  N--;  if(judge){  cout<<raw[N];judge=false;  }elsecout<<" "<<raw[N];M-=raw[N--];}  }}


  

0 0
原创粉丝点击