Please read the new rule regarding the restriction on the use of AI tools. ×

Koemann's blog

By Koemann, history, 2 years ago, In English

I saw a problem somewhere and I want to know the most efficient for this problem.

You're given t testcases an array aof n elements and q queries. Each query gives you a range l and r. You want to get a subsegment in [l,r] so that the subsegment is sorted in increasing order.

For example

Input

3

5 2

1 2 3 5 4

1 5

3 5

5 2

1 2 3 4 5

1 5

3 5

6 5

1 4 2 3 9 1

1 3

1 2

1 6

3 6

6 6

Output

4

2

5

3

2

2

3

3

1

I heard that problem can bo solved with segment trees but I don't know how

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

| Write comment?
»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

What do you mean by "You want to get a subsegment in [l,r] so that the subsegment is sorted in increasing order."? Is it to get any pair $$$(tl;tr)$$$ s.t. $$$a[tl..tr]$$$ is sorted, or get number of such pairs or what?

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +10 Vote: I do not like it

    Based on "reverse-engineering" the provided input-output, I think the OP probably means to find the length of a longest such sorted subarray a[tl..tr] with l <= tl <= tr <= r.

    A "hint" to the OP could be:

    Spoiler
»
2 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Segment trees seem like the way to go. Using them, for each testcase, the time complexity will be O(n) for preprocessing and O(q * logn) for the queries (in total). We can round the total complexity for the problem to O(t * n * logn), so around 20 * 100000 * 17 = 34000000 = 34M "steps" at most, which is really reasonable.

Segment tree building hint
Segment tree building hint 2