当前位置: 首页 > news >正文

Minimizing Coins(Dynamic Programming)

题目描述

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to produce a sum of money x using the available coins in such a way that the number of coins is minimal.
For example, if the coins are {1,5,7} and the desired sum is 11, an optimal solution is 5+5+1 which requires 3 coins.

输入

The first input line has two integers n and x: the number of coins and the desired sum of money.
The second line has n distinct integers c1,c2,...,cn: the value of each coin.
Constraints
1 ≤ n ≤ 100
1 ≤ x ≤ 10^6
1 ≤ ci ≤ 10^6

输出

Print one integer: the minimum number of coins. If it is not possible to produce the desired sum, print -1.

样例输入
3 11
1 5 7
样例输出
3

思路分析

经典动态规划,硬币找零问题。

过滤比金额x更大的硬币。

状态转移方程:dp[i]=min(当前解,使用当前硬币的解)。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll N=1e9;
ll n,x,c;
int main(){cin>>n>>x;vector<ll>dp(x+1,N);vector<ll>coins;dp[0]=0;for(ll i=1;i<=n;i++){cin>>c;if(c<=x)coins.push_back(c);}for(ll c:coins){for(ll i=c;i<=x;i++){dp[i]=min(dp[i],dp[i-c]+1);}}if(dp[x]==N)dp[x]=-1;cout<<dp[x];return 0;
}

(起初N的位置,我用的是LONG_MAX,WA了。因为没考虑到dp[i-c]+1可能会溢出。)

http://www.lryc.cn/news/608016.html

相关文章:

  • OAuth 2.0 的安全升级版授权协议 OAuth 2.1 详解
  • 【转】大模型安全治理的现状与展望
  • 【龙芯99派新世界】buildroot快速使用笔记
  • WPFC#超市管理系统(4)入库管理
  • STM32——启动过程浅析
  • Shell【脚本 02】离线安装配置Zookeeper及Kafka并添加service服务和开机启动(脚本分析)
  • Kubernetes Gateway API 详解:现代流量路由管理方案
  • Flink2.0学习笔记:Stream API 窗口
  • ubuntu 系统风扇控制软件 CoolerControl
  • 关于项目发布中到后半夜的一些总结
  • Maven - 并行安全无重复打包构建原理揭秘
  • 公网服务器上Nginx或者Openresty如何屏蔽IP直接扫描
  • 译|Netflix 技术博客:一个利用视觉-语言模型和主动学习高效构建视频分类器的框架
  • 初始C语言---第四讲(数组)
  • Python So Easy 大虫小呓三部曲 - 高阶篇
  • 【语音技术】什么是实体
  • appium中urllib3.exceptions.LocationValueError: No host specified. 的错误解决办法
  • cv快速input
  • InfluxDB 与 Node.js 框架:Express 集成方案(二)
  • SpringBoot与TurboGears2跨栈、整合AI服务、智能客服路由系统整合实战
  • 基于Redis自动过期的流处理暂停机制
  • dbt中多源数据的处理
  • 仿真电路:(十七下)DC-DC升压压电路原理简单仿真
  • Git下载及安装保姆级教程
  • 电子电气架构 --- 汽车网络安全概述
  • 深入 Go 底层原理(九):context 包的设计哲学与实现
  • 八股取士-go
  • python爬取豆瓣电影评论通用代码
  • Getedit-得辑SCI论文润色的重要性?
  • 自动驾驶:技术、应用与未来展望——从开创到全面革新交通出行