#P11061. Minimizing Program Length
Minimizing Program Length
Minimizing Program Length
You are given a program represented by a nonnegative integer sequence \( [a_1, a_2, \ldots] \). The program executes the commands sequentially. For the \( i\)-th element \( a_i \):
- If \( a_i = 0 \), it represents an input operation: the program reads an integer from the input.
- If \( a_i > 0 \), it represents an output operation: the program outputs the integer that was read in the \( a_i\)-th input operation. It is guaranteed that when this output operation is executed, there have been at least \( a_i \) inputs.
A program (even an empty one of length 0) is considered valid.
Now, you are given a program \( [b_1, b_2, \ldots, b_n] \) of length \( n \). Two programs are considered functionally equivalent if for every input (of length \(10^{10^{10}}\) and each integer between \(1\) and \(10^{10^{10}}\)), they execute the same number of output statements and each time the output values are identical.
Your task is to compute the minimum possible length of a program that is functionally equivalent to the given one.
Observation: The given program performs some input and output commands. Notice that an output command with value \(x\) outputs the \(x\)-th input that was read so far. In any equivalent program, it is unnecessary to perform extra input operations that are never used by any output command. Therefore, if the given program performs \( r \) output operations and the maximum number among all output commands is \( m \), then an equivalent program can be constructed by performing exactly \( m \) input operations (to provide the needed inputs) and \( r \) output operations. Hence, the minimum length of an equivalent program is \( m + r \). (If there is no output at all, the answer is 0.)
For example, consider the program: [0, 1, 0, 2]. It executes as follows:
- 0: read first input.
- 1: output the first input.
- 0: read second input.
- 2: output the second input.
Here, \( r = 2 \) and \( m = 2 \), so the minimal length is \( 2+2=4 \).
inputFormat
The first line contains a nonnegative integer \( n \) representing the length of the program.
The second line contains \( n \) nonnegative integers \( b_1, b_2, \ldots, b_n \) separated by spaces. If \( n = 0 \), the second line may be omitted.
outputFormat
Output a single integer, the minimum possible length of a program that is functionally equivalent to the given program.
sample
0
0