湖南大学第十五届程序设计竞赛(重现赛):F题 (map与unordered_map)

湖南大学第十五届程序设计竞赛(重现赛):F题 (map与unordered_map)

链接:https://ac.nowcoder.com/acm/contest/908/F
来源:牛客网


题目描述


AFei has many cards. Each card has a number written on it. Now he wants to takes some out of his card and puts them in a box. And he wants to know whether the card with the number x was in the box. So he has the following two operations:
0 x (It means to put a card with the number x in the box.)
1 x (It means to query if there is a card with the number x in the box.)


输入描述:


The first line of the input is an integer n (1 <= n <= 106), the number of operations. Next n lines represent n operations, and two integers k ( k∈{0,1}) and x (0<=x<=109) are separated by spaces on each line, as described above.


输出描述:


For each query, output one line “yes” if there is a card with the number x in the box, otherwise output one line “no”.


示例1


输入
5
0 1
1 2
0 2
1 3
1 2
输出
no
no
yes

题解:题意应该不难,就是有两种操作,每个操作对应两个数字,第一个数字如果是0,则相当于向容器中放值,如果为1,这就是查找操作
开始想着直接 用数字,然后在查找的时候用个二分,结果发现可能放进去的数的顺序可能不一样,于是就必须还得进行排序,当然结果不出意外TLE,后面就想着用map试试,结果就开始一顿猛操作,由于开始对map还不是用的太熟,于是就一边查资料,一边敲,最终发现好像用map好简单,下面是我的代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    map<int,int>mp;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int num1,num2;
        scanf("%d%d",&num1,&num2);
        if(num1==0)
        {
            mp.insert(make_pair(num2,num1));    //由于map是按键值排序,于是我选择把num2放在key值
        }
        else
        {
            if(mp.find(num2)==mp.end())             //这就是map比较强的地方所在,tcl
            {
                printf("no\n");
            }
            else
                printf("yes\n");
        }
    }
    return 0;
}

但是还是TLE,在牛客群里看了大佬的指点,说用unordered_map,于是又学了下unordered_map,结果发现自己没允许c++14编译,又在网上看了大佬的头文件提示,我是不知道啥意思,但是用unordered_map就A了。。。。

#include<iostream>
#include<cstdio>
#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    unordered_map<int,int>mp;
    int n;
    cin>>n;
    int num1,num2;
    while(n--)
    {
        cin>>num1>>num2;
        if(num1==0)
        {
            mp.insert(make_pair(num2,num1));
        }
        else
        {
            if(mp.find(num2)==mp.end())
                printf("no\n");
            else
                printf("yes\n");
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值