2

Given an integer array A of n element and m query each query contain an integer x i have to answer number of element in a array less than x. 0 < A[i] < 10^6 && x < 10^6

example:

A[]={105,2,9,3,8,5,7,7}

query

6

8

104

answer

3

5

7

Explanation:

for query1 elements are={2,3,5}

for query2 elements are={2,3,5,7,7}

for query3 elements are={2,9,3,8,5,7,7}

Question:

How to solve this question using segment tree?(I have built segment tree for finding max,min and sum in a range but my mind is going blank how to built segment tree for this).please explain with example

Note:I already know the nlogn solution using sorting and binary search(for each query).I want to learn how segment tree can be exploited to solve this.

Thank you

OmG
  • 18,337
  • 10
  • 57
  • 90
puja
  • 31
  • 3

2 Answers2

0

I don't think the segment tree would work if you build it for elements of the array A. You may use some heuristics/pruning using maximum and minimum for a segment, but in the end for cases like

0, 10^6, 0, 10^6, 0, 10^6,...

the queries will degenerate to O(n), because you need to go down in every leaf.

What you should do is to build a segment tree over the range of the possible values: For every value 0<a<10^6 you remember how many elements with this value are in the array A. For example for

A=[5,2,3,3,3,5,7,7] 

the array of occurrences would be

f=[0,0,1,3,0,2,0,1,0,...]

Now the query for the number of elements in an array A which are less-equal than x, translates to the query for the sum of elements in the occurrences array f from 0 til x.

You could use segment tree to answer this queries.

However if you know the whole array prior to the queries - this is a pretty boring case - you could just use the prefix sum on the array f with preprocessing time O(n) and query time O(1).

Segment trees are only interesting if queries and updates of the array A are interleaved.

If queries and updates are interleaved, I would recommend to use the Fenwicktree, it is not as flexible as a segment tree, but it is tailored for exactly this kind of problems. It is easier to implement, faster and needs less memory.

ead
  • 32,758
  • 6
  • 90
  • 153
0

Using a normal segment tree it is not possible to answer this type of queries in O(logn). You need to use wavelet tree (there are also few other data structures that enable answering this query but wavelet trees are most fun). This links might be helpful if you don't know this data structure:

https://codeforces.com/blog/entry/52854

https://youtu.be/4aSv9PcecDw