11991 - Easy Problem from Rujia Liu?
Time limit: 1.000 seconds
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 :D
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). The size of input file does not exceed 5MB.
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
Output for the Sample Input
2 0 7 0
Rujia Liu's Present 3: A Data Structure Contest Celebrating the 100th Anniversary of Tsinghua University
Special Thanks: Yiming Li
Note: Please make sure to test your program with the gift I/O files before submitting!
简单题,我的方法是先带下标的排序,然后二分查找就行了。
这里用lower_bound()的时候需要用到它的第四个参数:
(这里有解释:http://msdn.microsoft.com/zh-cn/library/34hhk3zb.aspx)
comp
二进制谓词采用两个参数,并且在满足时返回 true,在未满足时返回 false。
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<map> #include<set> #include<vector> #include<algorithm> #include<stack> #include<queue> using namespace std; #define INF 1000000000 #define eps 1e-8 #define pii pair<int,int> #define LL long long int struct node { int id,val; } a[100005]; int n,m,k,v; bool cmp(node x,node y) { if(x.val!=y.val) return x.val<y.val; else return x.id<y.id; } bool cmp2(node x,int y) { return x.val<y; } int main() { //freopen("in6.txt","r",stdin); //freopen("out.txt","w",stdout); while(scanf("%d%d",&n,&m)==2) { for(int i=0; i<n; i++) { scanf("%d",&a[i].val); a[i].id=i+1; } sort(a,a+n,cmp); for(int i=1;i<=m;i++) { scanf("%d%d",&k,&v); int t=lower_bound(a,a+n,v,cmp2)-a; if(t+k-1>=n||a[t+k-1].val!=v) { printf("0\n"); } else { printf("%d\n",a[t+k-1].id); } } } //fclose(stdin); //fclose(stdout); return 0; }