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 10​4​​ 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 (≤10​4​​, the total number of coins) and M (≤10​2​​, the amount of money Eva has to pay). The second line contains Nface 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 V​1​​≤V​2​​≤⋯≤V​k​​ such that V​1​​+V​2​​+⋯+V​k​​=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

 题目分析:

这道题其实是一道典型的DP题,网上也有很多经典的题解了,这里就不说DP做法了(整理一下状态转移方程即可)。那么这道题除了DP,其实按照数据暴力也能做,因为M只有100的大小,所以枚举一下组成M的所有可能性,然后找到第一个满足的输出即可,这里要注意的是DFS暴力枚举的时候要进行剪枝,否则你懂的,嘿嘿。

代码实现 :

#include 
using namespace std;
int num[105], a[105];
int n, m, x;

void DFS(int cur, int pre)
{
	if(cur > m)
		return;
	if(cur == m)//满足即可输出了 
	{
		int k = 0;
		for(int i = 1; i <= m; i++)
		{
			if(a[i])
			{
				for(int j = 0; j < a[i]; j++)
				{
					if(k == 0)
						printf("%d", i);
					else
						printf(" %d", i);
					k++;
				}					
			}
		}
		exit(0);
	}	
	for(int i = pre; i <= m-cur; i++)//注意硬币从pre开始枚举到M-cur结束! 
	{
		if(a[i] + 1 <= num[i])//注意枚举当前硬币的数量不可超出已有的硬币数 
		{
			a[i]++;
			DFS(cur+i, i);
			a[i]--;
		}
	}
}
int main()
{
	cin >> n >> m;
	for(int i = 0; i < n; i++)
	{
		cin >> x;
		if(x <= m)//剔除大于M的不合法数据 
			num[x]++;//记录每种硬币的数目 
	}
	DFS(0, 1);
	puts("No Solution");
} 

其实暴力也不难吧,好吧我就是动规方程懒得想了,而且经过本人评测,暴力求解的运行时间也不慢,如下图:

2019/8/15 08:50:56

答案正确

30 1068 C++ (g++) 6 ms 羁旅
测试点 结果 耗时 内存
0 答案正确 2 ms 424 KB
1 答案正确 3 ms 400 KB
2 答案正确 3 ms 484 KB
3 答案正确 6 ms 424 KB
4 答案正确 5 ms 552 KB
5 答案正确 3 ms 356 KB
6 答案正确 2 ms 364 KB

确实,100的组成方式确实不多,给大家提供一个思路。另外,今年本人也要去考PAT甲级了,希望能有个好成绩吧,也希望正在刷题的各位也有个好成绩! 

你可能感兴趣的:(暴力,PAT,枚举)