Instant Complexity
Time limit1sMemory limit128 MB
Parse a small nested-loop program, compute its running time as a polynomial in n, and print the collected polynomial from highest degree down.
- Level
Medium6 of 10
- Topics
- Implementation, Stack, Recursion, Math
- Solved
- No attempts yet
Problem
Analyzing the running-time complexity of an algorithm is an essential tool for designing efficient programs. An algorithm that runs in linear time is usually much faster than one that takes quadratic time for the same task, so it should be preferred.
Usually the running time is expressed in terms of the size of the input — the number of items to sort, the number of vertices of a polygon, and so on. Finding a formula in for the running time is generally hard, so it would be convenient to automate it. In general this is impossible, but here we consider programs of a very simple form for which it can be done. Our programs follow the grammar below (in BNF), where < number > is any non-negative integer:
< Program > ::= "BEGIN" < Statementlist > "END"
< Statementlist > ::= < Statement > | < Statement > < Statementlist >
< Statement > ::= < LOOP-Statement > | < OP-Statement >
< LOOP-Statement > ::= < LOOP-Header > < Statementlist > "END"
< LOOP-Header > ::= "LOOP" < number > | "LOOP n"
< OP-Statement > ::= "OP" < number >
The running time of such a program is computed as follows. Executing an OP statement costs as many time units as its parameter. The statement list enclosed by a LOOP statement is executed as many times as the loop parameter indicates: a fixed constant number of times when a number is given, or times when n is given. The running time of a statement list is the sum of the running times of its parts. The total running time therefore depends, in general, on .
Input
The first line contains the number of programs. It is followed by programs built according to the grammar above. Whitespace and newlines may appear anywhere in a program, but never inside the keywords BEGIN, END, LOOP, OP, or inside an integer value. The nesting depth of LOOP operators is at most .
Output
For each program, first print a line Program #i, where is the program's number starting from . Then print its running time as a polynomial in ; this polynomial has degree at most . Print it in the form
Runtime = a*n^10+b*n^9+...+i*n^2+j*n+k
Collect like terms, list them from the highest degree down to the lowest, and join them with + (no spaces). Omit any term whose coefficient is , and omit a coefficient of (write n^2, not 1*n^2; write n, not 1*n). The degree- term is written as n, not n^1, and the constant term is always written as its value (even when it is ). If the whole running time is , print Runtime = 0.
Print a blank line between the outputs of consecutive programs.