UVa 11991 - Easy Problem from Rujia Liu?

题目链接:UVa 11991 - Easy Problem from Rujia Liu?

map离散化。

先来看这样一个问题。

假如有m个数(m较小),但是每个数的取值范围很大(0<=ai<=1000000000)。我想记录哪些数字出现过,应该怎么离散呢?我知道最基本的作法是开一个标记的数组,哪个数字出现,就让那个数字对应的下标数组变成1,但是范围太大,没可能开1000000000的数组来存放标记,那要怎么办?这里就应该是用STL中的map。把ai当成key,value随便都行,那么查询是否有这个数的时候使用map的函数count(key)就可以了。

#include <iostream>
#include <map>
#include <vector>

using namespace std;

map <int,int> _map;
int n,m;

int main()
{
    while(cin >> n >> m)
    {
        int temp,a,b;
        _map.clear();
        for(int i = 1;i <= n;i++)
        {
            cin >> temp;
            _map[temp] = 1;//随便给一个值就行
        }
        for(int i = 1;i <= m;i++)
        {
            cin >> b;
            if(!_map.count(b))
                cout << 0 << endl;
            else
                cout << _map[b] << endl;
        }

    }
    return 0;
}


现在看看这道题,其实是很类似的,直接用一个数组搜过去估计得超时,那么整一个二维数组,第一维记录key(也就是题目给的值),第二维可以记录下标,速度倒是有了,但是这个数组太大了。那么可以想到使用map。

#include <iostream>
#include <map>
#include <vector>

using namespace std;

map <int,vector<int> > _map;
int n,m;

int main()
{
    while(cin >> n >> m)
    {
        int temp,a,b;
        _map.clear();
        for(int i = 1;i <= n;i++)
        {
            cin >> temp;
            //if(!_map.count(temp))
                //_map[temp] = vector<int>();
            _map[temp].push_back(i);
        }
        for(int i = 1;i <= m;i++)
        {
            cin >> a >> b;
            if(!_map.count(b) || _map[b].size() < a)
                cout << 0 << endl;
            else
                cout << _map[b][a - 1] << endl;
        }

    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值