zoukankan      html  css  js  c++  java
  • stl库中的map (反向迭代器)以及例题

    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
    ",ans);
            }
            else
                printf("-1
    ");
    
        }
    
    }
    
  • 相关阅读:
    setCookie
    EF getCookie
    EF
    Dapper修改
    Dapper显示
    Dapper上传图片
    Dapper存储过程分页
    Azure Function(.Net Cor框架)读取配置文件
    .Net Core3.1中出现AssemblyInfo特性重复
    YAML配置文件 基础学习
  • 原文地址:https://www.cnblogs.com/bhd123/p/9441377.html
Copyright © 2011-2022 走看看