UVA - 11991:Easy Problem from Rujia Liu?

Easy Problem from Rujia Liu?

来源:UVA

标签:数据结构

参考资料:

相似题目:

题目

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.

输入

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).

输出

For each query, print the 1-based location of the occurrence. If there is no such element, output ‘0’ instead.

输入样例

8 4
1 3 2 2 4 3 2 1
1 3
2 4
3 2
4 2

输出样例

2
0
7
0

参考代码1(60ms)

#include
#include
#include
#define MAXN 1000005
using namespace std;

vector<int> num[MAXN];

int main(){
	int n,m;
	while(~scanf("%d%d",&n,&m)){
		int k,v;
		memset(num,0,sizeof(num));//此处可能错误,待解决
		for(int i=1;i<=n;i++){
			scanf("%d",&v);
			if(num[v].empty())
				num[v].push_back(0);
			num[v][0]++;//对v个数计数 
			num[v].push_back(i);//记录编号 
		}
		for(int i=0;i<m;i++){
			scanf("%d%d",&k,&v);
			if(num[v][0]<k)
				printf("0\n");
			else 
				printf("%d\n",num[v][k]);
		}
	}
	return 0; 
}

参考代码2(40ms)

#include
#include
#include
using namespace std;

map<int, vector<int> > num;

int main(){
	int n,m;
	while(~scanf("%d%d",&n,&m)){
		num.clear();
		int k,v;
		for(int i=1;i<=n;i++){
			scanf("%d",&v);
			if(!num.count(v)){
				num[v]=vector<int>();
			}
			num[v].push_back(i);
		}
		for(int i=0;i<m;i++){
			scanf("%d%d",&k,&v);
			if(!num.count(v) || num[v].size()<k) 
				printf("0\n");
			else 
				printf("%d\n",num[v][k-1]);
		}
	}
	return 0; 
}

你可能感兴趣的:(【记录】算法题解)