Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя slow_coder4

Автор slow_coder4, история, 8 лет назад, По-английски

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

  • Проголосовать: нравится
  • -13
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

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

    • »
      »
      »
      8 лет назад, # ^ |
      Rev. 6   Проголосовать: нравится 0 Проголосовать: не нравится

      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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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