UVA11991

来源:互联网 发布:天气预报软件哪个好 编辑:程序博客网 时间:2024/05/18 02:09

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 41 3 2 2 4 3 2 11 32 43 24 2

Output for the Sample Input

2070

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!








解题思路:

         题意是说给你一个长度为n的数组,进行m次询问,每次询问输入k和v,输出第k次出现v时的下标是多少。

          为了不超时,用到STL里的map,以a[ v ][ k ]这样的方式进行询问,其中a[ v ] 是指在a这个map中 v 所对

应的值,即a[ v ]应该是一个数组,保存从左到右依次出现的下标(第k次就是a[ v ][ k ])。

          因为不同整数出现的次数相差可能很大,所以a[ v ]开成vector<int>长度可变数组(随机存取O(1))。

          注:(1)用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的

映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了

                  (2)push_back函数,在vector类中作用为在vector尾部加入一个数据。

                  (3)在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数

          

            一篇写的不错的STL博客链接:

            http://blog.csdn.net/muximuxi_kgsecond/article/details/8128613











AC代码:

#include <cstdio>#include <vector>#include <map>using namespace std;map< int , vector<int> > a;int main(){    #ifdef DoubleQ    freopen("in.txt","r",stdin);    #endif    int n , m , x , y;    while(~scanf("%d%d",&n,&m))    {        a.clear();        for(int i = 0 ; i < n ; i ++)        {            scanf("%d",&x);            if(!a.count(x))                a[x] = vector<int>();            a[x].push_back(i + 1);        }        while(m --)        {            scanf("%d%d",&x,&y);            if(!a.count(y) || a[y].size() < x)                printf("0\n");            else                printf("%d\n",a[y][x - 1]);        }    }    return 0;}


0 0
原创粉丝点击