博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Codeforces 1003D(贪心)
阅读量:4365 次
发布时间:2019-06-07

本文共 2203 字,大约阅读时间需要 7 分钟。

题面:

D. Coins and Queries
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Polycarp has nn coins, the value of the ii-th coin is aiai. It is guaranteed that all the values are integer powers of 22 (i.e. ai=2dai=2d for some non-negative integer number dd).

Polycarp wants to know answers on qq queries. The jj-th query is described as integer number bjbj. The answer to the query is the minimum number of coins that is necessary to obtain the value bjbj using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value bjbj, the answer to the jj-th query is -1.

The queries are independent (the answer on the query doesn't affect Polycarp's coins).

Input

The first line of the input contains two integers nn and qq (1n,q21051≤n,q≤2⋅105) — the number of coins and the number of queries.

The second line of the input contains nn integers a1,a2,,ana1,a2,…,an — values of coins (1ai21091≤ai≤2⋅109). It is guaranteed that all aiai are integer powers of 22 (i.e. ai=2dai=2d for some non-negative integer number dd).

The next qq lines contain one integer each. The jj-th line contains one integer bjbj — the value of the jj-th query (1bj1091≤bj≤109).

Output

Print qq integers ansjansj. The jj-th integer must be equal to the answer on the jj-th query. If Polycarp can't obtain the value bjbj the answer to the jj-th query is -1.

Example
input
Copy
5 42 4 8 2 4851410
output
Copy
1-132

题目描述:

    给你n个硬币,每个硬币的面值都为2的幂次方。先有q个询问,每个询问给出一个数b,问你至少用多少个硬币才能使得他们的面值凑成b。若不能凑出,则输出-1。

题目分析:

    因为题目中所给的硬币的面值都是2的倍数,因此,若我们要使得用最少的硬币凑出一个数,我们则应该贪心的从最大的2的倍数进行枚举,优先选取大的硬币,并将该数除以该面值。而若将这个过程做完后还不能使得原来的数为0,则输出-1。

代码:

#include 
using namespace std;map
mp;//用map来存储硬币的面额int main(){ int n,q; cin>>n>>q; for(int i=0;i
=1;i>>=1){ if(mp.count(i)==0) continue;//如果不存在i的面额 else{ int x=min(mp[i],num/i);//取面额i和num/i中的最小值 num-=x*i; ans+=x; } } if(num){ puts("-1"); continue; } else cout<
<

转载于:https://www.cnblogs.com/Chen-Jr/p/11007271.html

你可能感兴趣的文章
APACHE2 服务器配置 (一)
查看>>
JAVA JVM 流程一
查看>>
Jquery的普通事件和on的委托事件
查看>>
MTK Android Driver :Camera
查看>>
两种方法将Android NDK samples中hello-neon改成C++
查看>>
20145202马超《信息安全系统设计基础》实验二总结
查看>>
物联网架构成长之路(24)-Docker练习之Compose容器编排
查看>>
Spring事务配置方式(一) 拦截器方式配置
查看>>
nios pio interrupt 的使能
查看>>
【UVA 10816】 Travel in Desert (最小瓶颈树+最短路)
查看>>
Ubuntu 安装中文
查看>>
自己初学时的随笔记录
查看>>
python关于字典嵌套字典,列表嵌套字典根据值进行排序
查看>>
高可用集群搭建
查看>>
pandas.read_csv参数详解
查看>>
C# 调用Windows API实现两个进程间的通信
查看>>
Android N 新特性 + APP开发注意事项
查看>>
C++:从C继承的标准库
查看>>
解决Error: ENOENT: no such file or directory, scandir 安装node-sass报错
查看>>
错误1083:配置成在该可执行程序中运行的这个服务不能执行该服务 【解决办法】...
查看>>