codeforces 1003d
n个硬币,q次询问。第二行给你n个硬币的面值(保证都是2的次幂!)。每次询问组成b块钱,最少需要多少个硬币?
Example
Input
5 4
2 4 8 2 4
8
5
14
10
Output
1
-1
3
2
解题思路:总体上使用的是贪心策略,从最大面值的往下贪心选择就可以了,由于数据量较大这里使用了map,这样就最多才32个数。第一次使用map的迭代器
反向迭代器的rbegin和rend的位置
和正向迭代器的begin和end的位置如下图
#include<cstdio> #include<cstring> #include<cstdio> #include<algorithm> #include<map> using namespace std; map<int,int>mp; int main() { int n,m,a,b,i; scanf("%d%d",&n,&m); for(i=0; i<=n-1; i++) { scanf("%d",&a); mp[a]++; } for(i=1;i<=m;i++) { int flag=0; int ans=0; scanf("%d",&a); map<int,int>::reverse_iterator it;//反向迭代器 for(it=mp.rbegin();it!=mp.rend();it++) { int z=min(a/it->first,it->second); a-=z*it->first; ans+=z; if(a==0) { flag=1; break; } } if(flag==1) { printf("%d\n",ans); } else printf("-1\n"); } }