Given an array, your task is to find the k-th occurrence (from left to right) of an integer v. To make the problem more difficult (and interesting!), you’ll have to answer m such queries.
Input
There are several test cases. The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 100, 000), the number of elements in the array, and the number of queries. The next line contains n positive integers not larger than 1,000,000. Each of the following m lines contains two integer k and v (1 ≤ k ≤ n, 1 ≤ v ≤ 1, 000, 000). The input is terminated by end-of-file (EOF).
Output
For each query, print the 1-based location of the occurrence. If there is no such element, output '0' instead.
Sample Input
8 4
1 3 2 2 4 3 2 1
1 3
2 4
3 2
4 2
Sample Output
2
0
7
0
问题链接:UVA11991 Easy Problem from Rujia Liu?
问题简述:(略)
问题分析:
给出n个整数的序列,有m个提问。这些提问是要找出一个整数v在序列中的第k次出现,有则输出v的序号,没有则输出0。
这个问题的关键是数据表示问题。用STL的vector数组来表示是一种方法,但是还是一种没有完全稀疏化的表示。使用STL的map来表示,其值类型为vector,可以完全采用稀疏化的表示。
程序说明:
方法一:
使用vector数组vkth[],数组元素是向量。vkth[x]存储整数序列中x的所有的下标位置,即vkth[x][k-1]存储x第k次出现的下标。如果vkth[v].size()<k则表示x没有第k次出现。
这种方法必须满足一个前提,那就是x值的范围不能过大,否则数组过大。
方法二:
使用map来则完全使用稀疏化的数据结构来表示问题。
题记:(略)
参考链接:(略)
AC的C++语言程序(方法二)如下:
/* UVA11991 Easy Problem from Rujia Liu? */
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, k, v, a;
while(~scanf("%d%d", &n, &m)) {
map<int, vector<int>> mv;
for(int i=1; i<=n; i++) {
scanf("%d", &a);
mv[a].push_back(i);
}
while(m--) {
scanf("%d%d", &k, &v);
printf("%d\n", mv.count(v) > 0 && (int)mv[v].size() >= k ? mv[v][k - 1] : 0);
}
}
return 0;
}
AC的C++语言程序(方法一)如下:
/* UVA11991 Easy Problem from Rujia Liu? */
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
vector<int> vkth[N + 1];
int main()
{
int n, m, k, v, a;
while(~scanf("%d%d", &n, &m)) {
for(int i=1; i<=n; i++) {
scanf("%d", &a);
vkth[a].push_back(i);
}
while(m--) {
scanf("%d%d", &k, &v);
printf("%d\n", (int)vkth[v].size() < k ? 0 : vkth[v][k - 1]);
}
for(int i=1; i<=N; i++)
vkth[i].clear();
}
return 0;
}