jorge's blog

By jorge, 12 years ago, In English

Some one can hel me in this problem?? In an array of length at most 100000 and each number is <= 1000000. I need answer many querys (at most 100000) of: in an interval [a,b] : a < b, how many different numbers are inside of the interval

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
12 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
»
12 years ago, hide # |
← Rev. 2  
Vote: I like it +4 Vote: I do not like it

Spoj — Dquery My Solution: The result of a query [a, b] is number of integers whose last occurrence in [1, b] is >= a. http://pastebin.com/j9g9CHAL

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

Another nice idea would be the following one. Let's calculate next[i] = the next position in the array where the value is equal to a[i]. If such a position doesn't exist next[i] = array.lenght + 1. For example, if the initial array is 1,3,1,2,3, then next[1]=3, next[2]=5, next[3]=6, next[4]=6, next[5]=6. Now if we represent the points (i,next[i]) in a cartesian plane, a query [a,b] means the number of points in the rectangle [a..b] x [b+1..N+1] where N is the number of points. This can be done in O(N*log(N)) using segment trees.

Hope it helps!

  • »
    »
    12 years ago, hide # ^ |
    ← Rev. 2  
    Vote: I like it +3 Vote: I do not like it

    this can be simplified if we go offline:

    sort queries by left bound, then for each query [li, ri]:

    for j in range(l[i-1], l[i]):
      set(j, 0)
      if next[j] <= n: set(next[j], 1)
    
    print sum(1, r[i])