当前位置: 首页 > 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.dtcms.com/a/312203.html

相关文章:

  • 【智能体cooragent】创建 workflow 时 候选 Agent 和 Tool 获取来源详细分析
  • Python从入门到精通——第五章 列表与元组
  • 机器人学中路径规划(Path Planning)和轨迹生成(Trajectory Generation)关系
  • 海康皓视通 对接测试和比较
  • 【学习笔记】MySQL技术内幕InnoDB存储引擎——第8章 备份与恢复
  • 自进化智能体综述:通往人工超级智能之路
  • 安卓自动点击器:设置点击周期 / 滑动,抢票、游戏刷日常秒会
  • UNet改进(28):KD Attention增强UNet的知识蒸馏方法详解
  • 适 配 器 模 式
  • Anthropic最新研究Persona vector人格向量
  • C语言---函数的递归与迭代
  • 第14届蓝桥杯Python青少组中/高级组选拔赛(STEMA)2023年3月12日真题
  • Python从入门到精通计划Day01: Python开发环境搭建指南:从零开始打造你的“数字厨房“
  • 【语音技术】什么是实体
  • AI原生数据库:告别SQL的新时代来了?
  • 高效截图的4款工具深度解析
  • 淘宝商品API可以获取哪些商品详情数据?
  • ARM架构ELR、LR 和 ESR寄存器含义
  • Codeforces Global Round 27
  • 衡石湖仓一体架构深度解构:统一元数据层如何破除数据孤岛?
  • C++11 -- 智能指针
  • 【故障处理】redis会话连接满导致业务系统某个模块数据不显示
  • JJWT 核心工具类 Jwts 源码解析
  • 3 数字字符串格式化
  • 安灯系统(Andon System)
  • h3c路由器查看温度是否正常
  • 记录一次Spring Cloud Gateway配置的跨域处理:解决 ‘Access-Control-Allow-Origin‘ 头包含多个值的问题
  • 【Shell自动化脚本——for循环创建账户,测试主机连通性,for循环密码的修改】
  • 【Java面试题】一分钟了解反射机制
  • 切换python多版本