Under construction

Still being built. Things may change

Rainforest Jump

Time limit3sMemory limit1024 MB

Summary
Given distinct tree heights, find the fewest jumps to the nearest taller tree that get from some tree in one range to some tree in a later range, or report it is impossible.
Level

Hard8 of 10

Topics
Tree, Union-find, Array
Solved
No attempts yet

Problem

In a tropical rainforest in Sumatra, there are NN trees numbered from 0 to N−1N - 1 from left to right. All trees have different heights. The height of tree ii is H[i]H[i].

A professor is training orangutans to move by jumping between trees. In one jump, an orangutan at the top of its current tree can jump left or right to the nearest tree that is taller than the current tree. Precisely, an orangutan at tree xx can jump to tree yy if and only if one of the following holds:

  • H[y]>H[x]H[y] > H[x], and yy is the largest nonnegative integer less than xx with this property.
  • H[y]>H[x]H[y] > H[x], and yy is the smallest nonnegative integer greater than xx with this property.

The professor has QQ plans for the orangutans. Each plan is given by four integers AA, BB, CC, DD (A≤B<C≤DA \le B < C \le D). The professor wants to know whether an orangutan can start at some tree ss (A≤s≤BA \le s \le B) and, through jumps, finally reach some tree ee (C≤e≤DC \le e \le D). If it is possible, the professor wants the orangutan to complete the plan with the fewest possible jumps.

Constraints

  • 2≤N≤200 0002 \le N \le 200\,000
  • 1≤Q≤100 0001 \le Q \le 100\,000
  • 1≤H[i]≤N1 \le H[i] \le N (for all 0≤i≤N−10 \le i \le N - 1)
  • H[i]≠H[j]H[i] \neq H[j] (for all 0≤i<j≤N−10 \le i < j \le N - 1)
  • 0≤A≤B<C≤D≤N−10 \le A \le B < C \le D \le N - 1

Examples1

  1. Example 1

    Input
    2
    1 2
    1
    0 0 1 1
    
    Expected output
    1