This page is still under construction.

Parts of this page are still being built. What you see may change.

Expressions

Time limit1sMemory limit128 MB

Summary
Given a postfix expression, produce another postfix expression that the same algorithm evaluates to the same value when a queue replaces the stack.
Level

Medium7 of 10

Topics
Stack, Queue, Tree, Recursion
Solved
No attempts yet

Problem

Arithmetic expressions are usually written with the operator between its two operands, which is called infix notation. For example, (x+y)∗(z−w)(x + y) * (z - w) is an arithmetic expression in infix notation. It is easier, however, to write a program that evaluates an expression when the expression is given in postfix notation (also known as reverse Polish notation). In postfix notation, an operator is written after its two operands, each of which may itself be an expression. For example, x y + z w - * is the postfix form of the expression above. Note that parentheses are not needed.

A postfix expression can be evaluated with an algorithm based on a stack. A stack supports two operations:

  1. push: insert a number at the top of the stack.
  2. pop: remove the number from the top of the stack.

We scan the expression from left to right. When we meet a number, we push it onto the stack. When we meet an operator, we pop the top two numbers, apply the operator to them, and push the result back. Concretely, when we meet an operator OO:

a := pop();
b := pop();
push(b O a);

After the whole expression has been processed, the single number left on the stack is the result.

Now suppose we use a queue instead of a stack. A queue also has push and pop, but their meaning differs:

  1. push: insert a number at the back of the queue.
  2. pop: remove the number from the front of the queue.

Rewrite the given postfix expression so that running the same algorithm with a queue yields the same result as the original expression evaluated with a stack.

Input

The first line contains an integer TT (T≤200T \le 200). Each of the following TT lines contains one expression in postfix notation. Operators are written as uppercase letters and numbers as lowercase letters. The length of each expression is less than 1000010000 characters.

Output

For each expression, print an expression that produces the same result when evaluated with the queue-based algorithm instead of the stack-based one. To keep the answer unique, you may not assume that the operators are associative or commutative.

Examples3

  1. Example 1

    Input
    2
    xyPzwIM
    abcABdefgCDEF
    
    Expected output
    wzyxIPM
    gfCecbDdAaEBF
    
  2. Example 2

    Input
    1
    x
    
    Expected output
    x
    
  3. Example 3

    Input
    1
    xyP
    
    Expected output
    yxP