#P16218. [ECUSTPC 2025] 钟塔

[ECUSTPC 2025] 钟塔

Problem Description

Maddy is preparing to rebuild a clock tower.
Maddy has a sequence {ai}\{a_i\} of length nn. Now she wants to transform a sequence {hi}\{h_i\} of length nn that is initially all 0 into {ai}\{a_i\} using the minimum number of operations. Each operation works as follows:

  • Maddy chooses a position kk (1kn1 \le k \le n) and a direction d{L,R}d \in \{L, R\}.
  • If d=Ld = L, then for all 1ik1 \le i \le k, set hih_i to ik+1|i - k| + 1.
  • If d=Rd = R, then for all kink \le i \le n, set hih_i to ik+1|i - k| + 1.
  • Note that each operation completely overwrites the corresponding interval.

Please help her find the minimum number of operations needed. If it is impossible to achieve the goal using the operations above, report that there is no solution.

Input Format

The first line contains an integer TT (1T1051 \le T \le 10^5), denoting the number of test cases.
For each test case, the first line contains an integer nn (1n1051 \le n \le 10^5), denoting the length of the sequence.
The next line contains nn integers a1,a2,,ana_1, a_2, \dots, a_n (1ain1 \le a_i \le n), denoting the target sequence {ai}\{a_i\} that Maddy wants to construct.
It is guaranteed that n3×105\sum n \le 3 \times 10^5 over all test cases.

Output Format

For each test case, if the goal can be achieved using the operations above, output one integer on a line, denoting the minimum number of operations Maddy needs.
Otherwise, output one integer 1-1 on a line.

4
6
1 2 1 1 2 3
3
3 3 3
6
1 1 1 1 1 1
11
1 2 1 3 4 1 2 1 1 2 3
3
-1
6
6

Hint

Explanation for Sample 1

For the 1st sample, the operations can be described as:

  1. Choose k=4k = 4, d=Rd = R, then {hi}={0,0,0,1,2,3}\{h_i\} = \{0, 0, 0, 1, 2, 3\}.
  2. Choose k=3k = 3, d=Ld = L, then {hi}={3,2,1,1,2,3}\{h_i\} = \{3, 2, 1, 1, 2, 3\}.
  3. Choose k=1k = 1, d=Ld = L, then {hi}={1,2,1,1,2,3}\{h_i\} = \{1, 2, 1, 1, 2, 3\}.

It is easy to see that this is a minimum sequence of operations.
For the 2nd sample, it is easy to see that no matter what operations Maddy performs, h2h_2 can never become 3.

Translated by ChatGPT 5