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

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

How can we solve the following problem efficiently (I am mainly looking for a Segment Tree solution) ? Given an array of integers A of size N , and Q queries of the form L,R,X we need to find the minimum index i such that L<=i<=R and A[i]>=X 1<=L<=R<=N and |X|<=10^9 1<=N<=10^5 1<=Q<=10^5 |A[i]|<=10^9 for 1<=i<=N

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

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

I guess I misunderstood the problem. Apologies. Please refer the comment by RedNextCentury.

»
8 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится +20 Проголосовать: не нравится

The problem is identical to finding the minimum index i such that max(A[L]...A[i]) ≥ X

O(log2(n)):

Binary search to find the answer, the check is a range max query.

O(log(n)):

Let the segment tree store the maximum element in range. For the query, start from the root of the segment tree, you have two cases:

1) The range of this node is not completely covered by the query range:

Query the left child, if it returns an answer, immediately return that. Otherwise, query the right child.

2) The range of this node is completely covered by the query range:

If the maximum element in the left child's range is greater than X query the left child and return that. Otherwise if the maximum element in the right child's range is greater than X, query the right child.

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

Moreover, a simpler solution would be constructing a sparse table so you can answer range-max queries in constant time. Rest is a simple binary search.

But if you are looking for only segment tree solution, the above comment is well written. It is also called "parallel binary search".