【PAT(甲级)】1068 Find More Coins

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

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

解题思路:

一个动态规划问题,题目要求我们,在可以正好支付花费时给出所支付硬币数最多的解法,不能时输出No Solution。

首先分解一下问题,如果我们要得到一组总价值为(N+coin[7])的硬币组合,假设coin[1] + coin[3] + coin[6] = N,那么我们是不是只要找到等于N的路径,再加上coin[7]就可以得到答案了?

所以我们定义一个sum[ ]数组和dp[ ][ ]数组,来存储这一条路径。其中sum数组的下标就是这个数组所想要支付的金额,所以当sum[M] != M的时候就说明全部硬币找不到合适的组合来支付金额。

dp[ i ][ j ]数组中,如果为1,则代表下标为i的硬币是支付金额总值j的一种支付方式。

注意:检查路径的时候一定要从大往小的检查,这样才会正确。

代码:

#include
using namespace std;
int coin[10001];
int N,M,sum[101];// sum用来记录,到大不大于下标的总和 

int dp[10001][101];// 前面的下标为硬币编号,后面的下标代表此时所需支付的金钱总和 

bool cmp(int a,int b){
	return a>b;
}

int main(){
	scanf("%d %d",&N,&M);
	
	for(int i=0;i=coin[i];j--){
			if(sum[j]<=sum[j-coin[i]]+coin[i]){// 等于的时候就是再更新硬币组成更多的组合
				dp[i][j] = 1;// 表示下标为i的硬币,是支付金额j的一种组合 
				sum[j] = sum[j-coin[i]]+coin[i];
			}
		}
	}
	
	if(sum[M]!=M) printf("No Solution");
	else{
		vector r;
		int v = M,index = N-1;// 硬币要从小的开始取,以便硬币数量达到最多 
		while(v>0){
			if(dp[index][v] == 1){
				r.push_back(coin[index]);
				v -= coin[index];// 每当找到一个硬币,所需要支付的值就可以对应减少 
			}
			index--;// 说明这个硬币不在组合里面,找下一枚面额最小的硬币 
		}
		for(int i=0;i

你可能感兴趣的:(PAT(甲级),pat考试,c++)