E-Circuit Is Now on Sale!
InterviewTime limit2sMemory limit2048 MB
Given a grid of units that form a formula tree, compute the integer value that the printer unit displays.
- Level
Easy3 of 10
- Topics
- Tree, DFS, Implementation
- Solved
- No attempts yet
Problem
Are you looking for math education tools for your children? Then, why not try this amazing product, E-circuit? This is the best toy to learn two-dimensional geometry, logic, and arithmetic!
The E-circuit consists of a grid space with a bunch of square blocks, called units. Each unit fits exactly into one grid cell. Units have input and/or output terminals that transfer integer values. When several units are appropriately placed in the grid, they form a tree that represents a mathematical formula.
Each unit has one of the following functions, shown by a single character.
- Digit (
0to9): Has one output terminal. Sends the integer indicated by the digit to its output. - Connector (
#): Has one input terminal and one output terminal. Passes the value from its input to its output without changes. - Operator (
+,-,*,/): Has two input terminals and one output terminal. Computes on the two input values and sends the result to its output.+computes the sum of the two inputs.-computes the difference of the two inputs, the larger one minus the smaller one.*computes the product of the two inputs./computes the quotient, the larger input divided by the smaller one, with the fraction truncated.
- Printer (
P): Has one input terminal and displays the input value. There must be exactly one printer unit on the grid.
Two cells are adjacent if they share an edge. When two units sit on adjacent cells, they connect by using an input terminal of one and an output terminal of the other.
The placement you receive is appropriate: the units form a single tree that represents a formula. The exact format is given in the Input section. Find the value the printer displays.
Input
The input is a single test case in the following format.
The first two integers and (, ) give the grid size, rows by columns. The next lines describe the placement. The character (, ) is the unit in the cell in row from the top and column from the left. Each character is either a unit symbol from the problem statement or ., which means the cell is empty.
The placement is guaranteed to be appropriate:
- each unit has as many adjacent units as it has input and output terminals,
- the total number of input terminals equals the total number of output terminals across all units, and
- every unit belongs to the printer tree. A unit belongs to the printer tree if and only if it is the printer or is adjacent to another unit in the printer tree.
Also, the input values of every / operator are not zero, and no unit outputs a value larger than .
Output
Output a line containing the value the printer displays.