#P4505. [CTSC2013] 组合子逻辑

[CTSC2013] 组合子逻辑

Description

Combinatory logic is a symbolic system invented by Moses Schönfinkel and Haskell Curry to eliminate the need for variables in mathematical logic. This problem considers a combinator system that slightly differs from the one in the real world.

A combinator term is one of the following forms:

PP (E1  E2)(E_1\;E_2)

Here PP denotes a primitive function, and E1E_1 and E2E_2 are combinator terms (they may be the same). Any expression not in the above forms is not a combinator term.

We define the number of arguments of a combinator term EE, denoted np(E)np(E), as follows:

np(P)np(P) equals the number of arguments (arity) of the primitive function PP.

np((E1  E2))=np(E1)1np((E_1\;E_2)) = np(E_1) - 1.

In this problem, we use a positive integer to denote both a primitive function and the arity of that primitive function.

For a combinator term EE, if npnp of EE and of all combinator subterms it contains are positive integers, we say that EE is in normal form.

We often use a simplified notation for combinator terms: if a combinator term EE contains a consecutive subsequence (((E1  E2)  E3)En)(… ((E_1\;E_2)\;E_3) …E_n) (where n3n ≥ 3), where each EkE_k denotes a combinator term (which may itself be in simplified notation), then we replace that part by (E1  E2  E3En)(E_1\;E_2\;E_3 … E_n) while keeping the rest unchanged, obtaining a simplified representation of EE. A combinator term may be simplified in this way multiple times.

Given a sequence of primitive functions, determine the minimum number of pairs of parentheses that must be added to make the expression a simplified representation of a normal form (i.e., it satisfies the normal-form property). If it is impossible to obtain a simplified representation of a normal form no matter how you add parentheses, output 1-1.

Input Format

The first line contains a positive integer TT, the number of queries.

Then follow 2T2T lines.

Line 2k2k contains a positive integer nkn_k, the number of primitive functions in the sequence of the kk-th query.

Line 2k+12k + 1 contains nkn_k positive integers, where the ii-th integer denotes the ii-th primitive function in the sequence.

Output Format

Output TT lines, each containing one integer, the answer for the corresponding query.

2
5
3 2 1 3 2
5
1 1 1 1 1
3
-1

Hint

【Sample Explanation】

For the first query: an optimal plan is (3 (2 1) (3 2)). One can prove that there is no plan that uses fewer pairs of parentheses.

For the second query: it is easy to prove that no valid plan exists.

【Constraints】

Let TNTN denote the sum of all nkn_k in the input.

测试点编号 规模
1 T30,nk3T ≤ 30, n_k ≤ 3
2 T30,nk15T ≤ 30, n_k ≤ 15
3 TN100TN ≤ 100
4 TN500TN ≤ 500
5 TN2000TN ≤ 2000
6 TN5000TN ≤ 5000
7
8 TN1000000TN ≤ 1000000
9 TN2000000TN ≤ 2000000
10

Translated by ChatGPT 5