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");
}
}
