map的简单例题

A - Let the Balloon Rise

题意:输入n种颜色,输出出现最多次数的颜色。

思路:创建一个以颜色为key,出现次数为value的map,每次输入一种颜色都给对应的value加1。注意map的初始化。

代码:

#include<bits/stdc++.h>
using namespace std;
int n;
string st;
map<string,int>mp;
int main(){
     while(cin>>n){
         if(!n)  break;
         mp.clear();
         int maxx=0;
         string result;
         for(int i=1;i<=n;i++){
             cin>>st;
             mp[st]++;
             if(mp[st]>maxx){
                 maxx=mp[st];
                 result=st;
             }
         }
         cout<<result<<endl;
     }
}

B - Gunner

题意:有n只鸟,每只鸟的高度为h[1],h[2],h[3]…h[n],猎人可以射击m次,每次射击的高度为q[1],q[2],q[3]…q[m],问每次射击能击落多少只鸟。如果射击高度为h,那么在高度为h的鸟都会被击落,无论多少只。

思路:创建一个以鸟的高度为key,鸟的数量为value的map。射击时只用输出当前高度的鸟的总数就可以了,注意一次射击完之后当前高度的鸟为0只。建议用cin要关闭同步。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1000010;
int n,m,h[maxn],q[maxn];
map<int,int>mp;
int main(){
     while(~scanf("%d%d",&n,&m)){
         mp.clear();
         for(int i=1;i<=n;i++){
             scanf("%d",&h[i]);
             mp[h[i]]++;
         }
        for(int i=1;i<=m;i++){
            scanf("%d",&q[i]);
            printf("%d\n",mp[q[i]]);
            mp[q[i]]=0;
        }
     }
}

C - Word Amalgamation

题意:给一串字符串字典,再给一串字符串,求字典中是否存在与字符串字符相同的字符串。

思路:建一个map<string,string>,以字典中的字符串为key,对字典中的字符串进行排序存进value,然后对要判断的字符串进行排序,然后用一个迭代器遍历,如果map中有对应的value值,那就输出key,否则输出"NOT A VALID WORD"。

代码:

#include<bits/stdc++.h>
using namespace std;
string st1,st2;
map<string,string>mp;
int main(){
     while(cin>>st1&&st1!="XXXXXX"){
           string s=st1;
           sort(s.begin(),s.end());
           mp[st1]=s;
     }
     while(cin>>st2&&st2!="XXXXXX"){
           sort(st2.begin(),st2.end());
           map<string,string> ::iterator it;
           int flag=0;
           for(it=mp.begin();it!=mp.end();it++){
                   if(it->second==st2){
                        cout<<it->first<<endl;
                        flag=1;
                   }
           }
           if(!flag) {
                  cout<<"NOT A VALID WORD"<<endl;
           }
           cout<<"******"<<endl;
     }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值