https://vjudge.net/problem/UVA-11991
题意:
给出一个包含n个整数的数组,你需要回答若干询问。每次询问两个整数k和v,输出从左到右第k个v的下标。
思路:
把每个数字所出现的下标存储在vector中。
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std; const int maxn = + ; int n, m;
vector<int> s[maxn]; int main()
{
//freopen("D:\\txt.txt", "r", stdin);
while (cin >> n >> m)
{
int x;
for (int i = ; i < maxn; i++)
s[i].clear();
for (int i = ; i <= n; i++)
{
cin >> x;
s[x].push_back(i);
}
int k, v;
for (int i = ; i < m; i++)
{
cin >> k >> v;
if (k <= s[v].size()) cout << s[v][k - ] << endl;
else cout << '' << endl;
}
}
}
刘汝佳的做法更妙一些。
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std; int n, m;
map <int, vector<int> > a; int main()
{
//freopen("D:\\txt.txt", "r", stdin);
while (cin >> n >> m)
{
a.clear();
int x;
for (int i = ; i <= n; i++)
{
cin >> x;
if (!a.count(x)) a[x] = vector<int>();
a[x].push_back(i);
}
int k, v;
for (int i = ; i < m; i++)
{
cin >> k >> v;
if (k <= a[v].size()) cout << a[v][k - ] << endl;
else cout << '' << endl;
}
}
}