题目链接: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;
}