UVA 11991 Easy Problem from Rujia Liu?

本文介绍了一种通过预处理排序和二分查找的方法来高效解决数组中特定元素查询的问题。该方法适用于需要多次查询相同数组的不同位置的场景,尤其当查询数量较大时更为有效。

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


题意:给出一个数组,m次询问,问第k个v的位置,如果不存在,输出0.

先预处理排序,然后二分求下界。

#include <string>
#include <iostream>
#include <map>
#include <cstdio>
#include <algorithm>
using namespace std;
int n,m,k,v;
struct C {
    int pos,num;
}a[100005];
bool cmp(C a, C b) {
    if(a.num == b.num) return a.pos < b.pos;
    return a.num < b.num;
}
int bs(int v) {
    int m, x = 1, y = n;
    while(x < y) {
        m = x+(y-x)/2;
        if(a[m].num >= v) y = m;
        else x = m+1;
    }
    return x;
}
int main()
{
    while(~scanf("%d%d",&n,&m)) {
        for(int i=1;i<=n;i++) {
            scanf("%d",&a[i].num);
            a[i].pos = i;
        }
        sort(a+1, a+1+n, cmp);
        for(int i=1; i<=m; i++) {
            scanf("%d%d",&k,&v);
            int p = bs(v);
            if(p+k-1 <= n && a[p+k-1].num == v) printf("%d\n",a[p+k-1].pos);
            else printf("0\n");
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值