PAT A1068 DP

PAT A1068 DP

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 N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

Output Specification:

在这里插入图片描述
在这里插入图片描述

思路

DP问题,分清死胡同和岔路口。

如何看待,最小的规定一致都是,在k之前,两个序列的值相等,在k以及之后,两个队列的值不等;那么输出最小队列,就要求尽可能选择小面额的硬币,输出最大队列,就要求尽可能选择大面的隐蔽无论如何,都是要dp的,也就是动态规划。

关于最小队列的比较,如果你自己编写函数,来比较就太傻了,其实STL是有自己的专门的比较方式的,就是大于小于号。当然,一个刚声明的vector由于里面什么元素都没有,肯定是最小的。

本题最主要的就是如何写递归函数,递归函数主要考虑的就是死胡同和岔路口,那么我们什么时候死胡同,什么时候岔路口呢?

此外的一个大问题就是何时return的问题,return的影响巨大,甚至会让一个TLE的AC。
在递归中,所有的return都是返回当前的函数体,所以,规定,在所有的dp后面,统一写上return。

#include<iostream> 
#include<set>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 110;
int n,m,value;

//记录某种买呢的硬币的数目 
int coin[maxn] = {0};
vector<int> temppath,path;
//这里的path是必须要声明的,否则无法进行。 
bool flag = false;

void dp(int cur_value,int index){
	if(cur_value == 0){
		if(flag == false){
			path = temppath;
			flag = true;
			return;
		}
		if(flag == true && path > temppath) {
			path = temppath;
		}
		return; 
	}
	if(coin[index] == 0){
		index++;
		dp(cur_value,index);
		return;
	}
	if(coin[index] != 0){
		//sp
		if(index > cur_value){
			return;
		}
		else if(index <= cur_value){
			temppath.push_back(index);
			coin[index]--;
			dp(cur_value-index,index);
			coin[index]++;
			temppath.pop_back();
			//在递归函数里面,千万不要使用++或者--运算符号 
			dp(cur_value,index+1);	
			return;
		}
	}
	return;
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%d",&value);
		coin[value]++;
	}
	//从m面额,和1元开始遍历  
	dp(m,1);
	if(!flag) {
		cout<<"No Solution\n";
		return 0;
	}
	int cnt = 0;
	int tot = path.size(); 
	for(auto &x:path){
		printf("%d",x);
		if(cnt < tot-1){
			printf(" ");
		}
		cnt++; 
	} 
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值