Please read the new rule regarding the restriction on the use of AI tools. ×

slow_coder4's blog

By slow_coder4, history, 8 years ago, In English

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

  • Vote: I like it
  • -13
  • Vote: I do not like it

»
8 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Have you tried a google search with something like dquery solution?

»
8 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

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.

  • »
    »
    8 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    still i have no idea of Mo's algorithm. Is it possible of segment tree or BIT?

    • »
      »
      »
      8 years ago, # ^ |
      Rev. 6   Vote: I like it 0 Vote: I do not like it

      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

»
8 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Similar problem can be found here on CF: 703D - Mishka and Interesting sum