Problem 684
Count Distinct Values in Range Queries
Hard · 30 pts · Array, Fenwick Tree, Offline Queries
Problem
You are given an array of N integers (positions 1 to N) and Q queries (l, r). For each query, count how many different values appear among A[l], ..., A[r]. Answer the queries offline: sort them by r and sweep the array from left to right, keeping a Fenwick tree with a 1 at the last position where each value has appeared so far. Then the answer for (l, r) is the number of ones between l and r.
Input
The first line contains N and Q. The second line contains the N values. Each of the next Q lines contains l and r.
Output
Print the answer to each query, one per line, in input order.
Constraints
1 <= N, Q <= 100000; 1 <= A[i] <= 10^9; 1 <= l <= r <= N
Example input
5 3 1 1 2 1 3 1 5 2 4 3 5
Example output
3 2 3
Explanation
For A = 1 1 2 1 3: positions 1 to 5 contain the values 1, 2 and 3, so the answer is 3. Positions 2 to 4 contain 1, 2 and 1, which is 2 different values.