#P5698. [CTSC1998] 算法复杂度

[CTSC1998] 算法复杂度

Background

CTSC1998 D1T3.

When we do programming, the issue we care about most is the time complexity of an algorithm. However, analyzing the complexity of a program is very difficult, and it becomes even harder when the program is not well written.

So, the SERKOI group, which specializes in studying algorithms, decided to develop software to analyze the time complexity of a program. Since this is a brand-new field, the SERKOI group decided to start with simple cases first.

Problem Description

To simplify the problem, the program contains only loops and sequential structures. The program structure is defined as follows:

begin <statement> end\texttt{begin <statement> end}

The structure of a statement block is recursively defined as follows:

loop x <statement> end\texttt{loop x <statement> end}

or op <statement>\texttt{op <statement>}

or break <statement>\texttt{break <statement>}

or continue <statement>\texttt{continue <statement>}

A statement block can be empty.

Notes:

  1. A program starts with begin\texttt{begin} and ends with the corresponding end\texttt{end}.

  2. loop x <statement> end\texttt{loop x <statement> end} means the statements inside are executed repeatedly xx times.

  3. op x\texttt{op x} means performing xx unit operations.

  4. In the above two points, xx can be a positive integer or nn.

  5. The break\texttt{break} statement exits the current loop level, and the continue\texttt{continue} statement skips the remaining statements in the current loop level and directly enters the next iteration. If it (break\texttt{break} or continue\texttt{continue}) is not inside any loop, please ignore them.

You need to write a program to compute the time complexity of the program described above, and output it in polynomial form.

Note that this polynomial is a polynomial in nn, and the constant term and coefficients cannot be omitted.

The testdata guarantees that the time complexity of the program can be determined.

Input Format

The input contains a complete program.
Between every two statements, there is at least one space or newline character.

Output Format

Output the computed time complexity polynomial in descending order of degree.

begin loop n loop 3 loop n
op 20
end end end
loop n op 3 break end
loop n loop n
op 1
break
end end
end

60n^2+n+3
begin
op n
loop 3
op n
break
end
loop n
loop n
op 1
continue
op n
end
end
end 
n^2+2n

Hint

The loop nesting depth is at most 2020 levels.

It is guaranteed that the coefficient of each term in the final time complexity polynomial does not exceed 109{10}^9.

Translated by ChatGPT 5