1. 程式人生 > >UVA11991 Easy Problem from Rujia Liu?【vector+map】

UVA11991 Easy Problem from Rujia Liu?【vector+map】


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

問題簡述:(略)

問題分析

  給出n個整數的序列,有m個提問。這些提問是要找出一個整數v在序列中的第k次出現,有則輸出v的序號,沒有則輸出0。

  這個問題的關鍵是資料表示問題。用STL的vector陣列來表示是一種方法,但是還是一種沒有完全稀疏化的表示。使用STL的map來表示,其值型別為vector,可以完全採用稀疏化的表示。


程式說明

  方法一:

  使用vector陣列vkth[],陣列元素是向量。vkth[x]儲存整數序列中x的所有的下標位置,即vkth[x][k-1]儲存x第k次出現的下標。如果vkth[v].size()<k則表示x沒有第k次出現。

  這種方法必須滿足一個前提,那就是x值的範圍不能過大,否則陣列過大。

  方法二:

  使用map來則完全使用稀疏化的資料結構來表示問題。

題記:(略)

參考連結:(略)

AC的C++語言程式(方法二)如下:

/* UVA11991 Easy Problem from Rujia Liu? */

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, m, k, v, a;

    while(~scanf("%d%d", &n, &m)) {
        map<int, vector<int>> mv;

        for(int i=1; i<=n; i++) {
            scanf("%d", &a);
            mv[a].push_back(i);
        }

        while(m--) {
            scanf("%d%d", &k, &v);
            printf("%d\n", mv.count(v) > 0 && (int)mv[v].size() >= k ? mv[v][k - 1] : 0);
        }
    }

    return 0;
}


AC的C++語言程式(方法一)如下:

/* UVA11991 Easy Problem from Rujia Liu? */

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6;
vector<int> vkth[N + 1];

int main()
{
    int n, m, k, v, a;

    while(~scanf("%d%d", &n, &m)) {
        for(int i=1; i<=n; i++) {
            scanf("%d", &a);
            vkth[a].push_back(i);
        }

        while(m--) {
            scanf("%d%d", &k, &v);
            printf("%d\n", (int)vkth[v].size() < k ? 0 : vkth[v][k - 1]);
        }

        for(int i=1; i<=N; i++)
            vkth[i].clear();
    }

    return 0;
}