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的位置如下图

stl库中的map (反向迭代器)以及例题

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

    }

}

 

相关文章:

  • 2021-08-22
  • 2021-08-20
  • 2021-05-10
  • 2021-04-27
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2021-12-01
  • 2022-12-23
  • 2021-12-06
  • 2021-04-12
相关资源
相似解决方案