重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

第八章动态规划3AcWing1554.找更多硬币-创新互联

第八章 动态规划 3 AcWing 1554. 找更多硬币 原题链接

AcWing 1554. 找更多硬币

创新新互联,凭借十余年的成都网站设计、成都网站建设、外贸网站建设经验,本着真心·诚心服务的企业理念服务于成都中小企业设计网站有上1000+案例。做网站建设,选创新互联建站。算法标签

DP 背包问题

思路

经典01背包问题
在这里插入图片描述
闫氏DP分析法
状态表示
在这里插入图片描述
状态初始化
在这里插入图片描述
状态计算
在这里插入图片描述
状态转移方程式
在这里插入图片描述

要求字典序最小,因此先存硬币面额到数组再降序排列,保证逆序得到的是升序的方案序列

代码
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include#define int long long
#define x first
#define y second
#define ump unordered_map
#define ums unordered_set
#define pq priority_queue
#define rep(i, a, b) for(int i=a;i=b;--i)
using namespace std;
typedef pairPII;
const int N=10005, M=105, INF=0x3f3f3f3f3f3f3f3f;
const double Exp=1e-8;
//int t, n, m, cnt, ans;
int n, m, w[N];
bool f[N][M];
inline int rd(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}
void put(int x) {
    if(x<0) putchar('-'),x=-x;
    if(x>=10) put(x/10);
    putchar(x%10^48);
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	f[0][0]=true;
	n=rd(), m=rd();
	rep(i, 1, n+1){
	    w[i]=rd();
	}
	sort(w+1, w+n+1, greater());
	rep(i, 1, n+1){
	    rep(j, 0, m+1){
	        f[i][j]=f[i-1][j];
	        if(j>=w[i]){
	            f[i][j]|=f[i-1][j-w[i]];
	        }
	    }
	}
	if(!f[n][m]){
	    puts("No Solution");
	}else{
	    bool fi=true;
	    while(n){
	        if(m>=w[n]&&f[n-1][m-w[n]]){
	            if(fi){ 
	                fi=false;
	            }else{
	                printf(" ");
	            }
	            printf("%lld", w[n]);
	            m-=w[n];
	        }
	        n--;
	    }
	}
	return 0;
}
参考文献

AcWing 1554. 找更多硬币(PAT甲级辅导课)y总视频讲解

原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
在这里插入图片描述

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网页题目:第八章动态规划3AcWing1554.找更多硬币-创新互联
当前URL:http://cqcxhl.com/article/iddjp.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP