#P4505. Combinator Normal Form Parentheses Insertion

    ID: 17751 Type: Default 1000ms 256MiB

Combinator Normal Form Parentheses Insertion

Combinator Normal Form Parentheses Insertion

A combinator term in this problem is defined in one of the following two forms:

$$P$$

$$(E_1\;E_2)$$

where P denotes a basic function and each Ei is itself a combinator term. Any expression that does not follow one of the above forms is not a combinator term.

The number of parameters of a combinator term \( E \) is defined as follows:

  • \( np(P) = P \). (In this problem a positive integer represents both a basic function and its number of parameters.)
  • \( np((E_1\;E_2)) = np(E_1)-1 \).

A combinator term \( E \) is said to be in normal form if np of \( E \) and every subterm contained in \( E \) is a positive integer.

We often use a simplified notation for combinator terms. Specifically, if a combinator term \( E \) contains a contiguous sequence of subterms in the form

[ (\ldots ((E_1;E_2);E_3) \ldots E_n) \quad (n \ge 3), ]

where each ( E_k ) is a combinator term (possibly already in simplified form), then that portion may be replaced by

[ (E_1;E_2;E_3 ;\ldots;E_n), ]

with the remainder of the expression unchanged. A combinator term may be simplified in this manner several times.

Given a sequence of basic functions (each represented by a positive integer, its value indicating both the function and its parameter count), your task is to determine the minimum number of pairs of parentheses that must be added so that the resulting expression is a simplified representation of a normal form. In other words, after inserting parentheses appropriately, the expression must be a valid combinator term (possibly using the simplified notation) and every combinator subterm (including the whole expression) must have a positive parameter count as defined above.

If no matter how parentheses are added the expression cannot be turned into a normal form, output \( -1 \).

inputFormat

The input is a single line containing a sequence of space‐separated positive integers. Each integer represents a basic function (and its parameter count).

outputFormat

Output a single integer: the minimum number of pairs of parentheses that must be added to form a normal form simplified representation. If it is impossible, output -1.

sample

3
0

</p>