5

I'm trying to solve this problem.

I found tutorial for this problem but I don't get how to build segment tree that will find amount of numbers less than x in O(log n) (x can change). In tutorial it has been omitted.

Can anyone explain me how to do it ?

Badf
  • 325
  • 2
  • 10

1 Answers1

5

It is pretty simple:

  1. Store a sorted array of all numbers in a range covered by a particular node
    ( O(n * log n) memory and time for initialization).

  2. To answer a query, decompose the query segment into O(log n) nodes(the same way as it is done for a standard min/max/sum segment tree) and run binary search over the array stored in each of those nodes to find the number of elements less than x. It gives O(log^2 n) time per query. You can also achieve O(log n) using fractional cascading, but it is not necessary.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
  • how can we do 1 in nlogn? There are n^2 elements in the sorted ranges. Storing the sorted result itself will take n^2 – cegprakash Nov 20 '18 at 12:17
  • 1
    @cegprakash There are O(n log n) elements because a segment tree doesn't store all ranges. It has O(log n) levels and each element is present only once at each level. A naive sort would take O(n log^2 n), but we can use merge sort for each consecutive level, making it O(n log n). – kraskevich Nov 20 '18 at 12:45