Give me some tricks to solve it. problem : Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.
Input
Line 1: n (1 ≤ n ≤ 30000). Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106). Line 3: q (1 ≤ q ≤ 200000), the number of d-queries. In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n). Output
For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line. Example
Input 5 1 1 2 1 3 3 1 5 2 4 3 5
Output 3 2 3
Have you tried a google search with something like dquery solution?
I assume the correct constraint is actually 1 ≤ ai ≤ 106. In this case, the problem can be solved with Mo's algorithm in .
Do you have a link to the problem?
UPDATE: Don't worry, I've found the problem at SPOJ. Mo's algorithm gets Accepted.
still i have no idea of Mo's algorithm. Is it possible of segment tree or BIT?
Yes, you can use a Persistent Segment Tree to solve it online or segment/bit tree to solve it offline after sorting all queries
The idea behind both solutions is to account for the last occurrence of an element and ignore the rest
[1, 2, 3, 2, 1, 2, 2]
If we were to store 1 for last occurrence and 0 fot the rest:
[0, 0, 1, 0, 1, 0, 1]
And if we were to perform any range sum query over any interval [L...N] such that N is the last index in the array and L is any index we will always get the right answer
Persistent Segment Tree will have a version for each sub array [1...R] 1 < = R < = N
Now answering any query [L...R] is just as easy as doing range sum query on the segment tree version that contains all updates until R
Code
Bit solution: Code
Just had to sort queries by their right end and update the tree with ones and zeros to so that only last occurrence has 1
I did coordinates compression by the way to make it easier for me :D
Similar problem can be found here on CF: 703D - Mishka and Interesting sum