Easy Problem from Rujia Liu?
Though Rujia Liu usually sets hard problems for contests (for example, regional contests like
Xi’an 2006, Beijing 2007 and Wuhan 2009, or UVa OJ contests like Rujia Liu’s Presents 1
and 2), he occasionally sets easy problem (for example, ‘the Coco-Cola Store’ in UVa OJ),
to encourage more people to solve his problems ?
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
这个题一看起来感觉很简单写个数组一下子就写完了。
代码:
#include<iostream>
#define MAXSIZE 1000000
using namespace std;
typedef long long ll;
ll a[MAXSIZE];
int main()
{
int n,m;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=0;i<m;i++){
bool flag=true;
int x,y;
int num=1;
cin>>x>>y;
for(int i=1;i<=n;i++){//时间复杂度O(n)
if(y==a[i]){
if(num==x){
cout<<i<<endl;
flag=false;
break;
}
num++;
}
}
if(flag==true){
cout<<"O"<<endl;
}
}
}
}
但是提交后tle了,然后看了刘汝佳大佬的思路,不经感概到大佬的脑回路就是牛皮,上面代码主要的原因就是时间复杂度O(n)太高了,而n还是指数级别的,不tle才怪了,然后更新后的代码是这样的:
#include<iostream>
#include<map>
#include<vector>
using namespace std;
map<int,vector<int> >t;
int main()
{
int n,m,x,y;
while(cin>>n>>m)
{
t.clear();
for(int i=1;i<=n;i++){
cin>>x;
if(!t.count(x))t[x]=vector<int>();
t[x].push_back(i);
}
for(int i=0;i<m;i++){
cin>>x>>y;
if(t[y].size()>=x){
cout<<t[y][x-1]<<endl;
}else{
cout<<"0"<<endl;
}
}
}
}
太强了,短短26行将map和vector的作用用的淋漓尽致,将查找元素的时间复杂度减少到O(logn)总时间复杂度O(nlogn),而且由于map的键值是数组方式的,取元素的时间复杂度是O(1),太强了比我之前的代码不知道强到哪里去了,思路也很清晰,考虑问题还是要把复杂度考虑上来,程序才能高效。