luogu#P16362. [BalticOI 2026] Sort

    ID: 16541 远端评测题 1000ms 512MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>贪心树状数组BalticOI(波罗的海)2026双指针 two-pointer离线处理

[BalticOI 2026] Sort

Problem Description

You are given an array x1,x2,,xnx_1,x_2,\dots,x_n of nn integers. Your task is to answer qq queries (a,b)(a, b). In one operation, you are allowed to do one of the following:

  • sort the first aa numbers in nondecreasing order, or
  • sort the last bb numbers in nondecreasing order.

What is the minimum number of operations needed to sort the whole array in nondecreasing order? In each query, the array starts from the initial values x1,x2,,xnx_1,x_2,\dots,x_n.

Input Format

The first line contains two integers nn and qq: the length of the array and the number of queries.

The second line contains nn integers x1,x2,,xnx_1,x_2,\dots,x_n: the contents of the array.

The next qq lines describe the queries. Each line contains two integers aa and bb.

Output Format

Print qq lines with the answers to each query. If it is impossible to sort the array, print "-1".

6 3
3 1 4 1 5 9
4 1
3 3
2 5
1
-1
2

Hint

Explanation

In the first query, the array can be sorted in one operation by sorting the first 44 numbers.

The array cannot be sorted with the available operations in the second query.

In the third query, the array can be sorted in two operations: start by sorting the first 22 numbers and then sort the last 55 numbers.

Constraints

  • 1n,q21051 \le n,q \le 2 \cdot 10^5
  • 1xi1091 \le x_i \le 10^9
  • 1a,bn1 \le a,b \le n in all queries

Scoring

Subtask Constraints Points
1 n,q10n,q\le 10 and a+bna+b\le n in all queries 66
2 n,q10n,q \le 10 55
3 a+bna+b \le n in all queries 77
4 1xi21 \le x_i \le 2 1414
5 n,q5000n,q \le 5000 and the array is a permutation of the numbers 1,2,,n1,2,\dots,n 2323
6 n,q5000n,q \le 5000 1212
7 No additional constraints 3333