Turtle Graphics
Time limit1sMemory limit128 MB
Simulate the direction-digit moves, erasing each loop or overlap as it forms, then report the remaining segment count and total length.
- Level
Medium6 of 10
- Topics
- Simulation, Stack, Hash map, Geometry
- Solved
- No attempts yet
Problem
You will draw a figure on a computer monitor using the keyboard. The figure is a polygonal chain (a polyline) made only of horizontal and vertical line segments. To draw it you press keys one after another, and the presses come in pairs of a direction key followed by a digit key. The four direction keys are labeled N, S, E, and W, standing for North, South, East, and West. The ten digit keys are labeled 0 through 9.
Initially the cursor sits at the center of the screen. For example, pressing S4 draws a vertical segment of length 4 going south from the current cursor position and moves the cursor to the far end of that segment. Pressing E3 next draws a horizontal segment of length 3 going east from the new cursor position. So the input S4E3 draws an L-shaped chain.
The program always keeps the chain simple: it never contains a cycle or a pair of overlapping segments. Whenever a cycle or an overlap appears while drawing, the program removes it immediately.
For example, in E6S2W5S2E2N7 the last segment meets the existing chain at two points. In the order the segment is drawn it first crosses at point , then at point (see Figure 1). The program first removes the cycle formed at , then the cycle formed at , so the remaining chain is the same as the one drawn by E3N3. In E4S2W3S2E6N6W4S7, removing the cycle formed at the first crossing also erases the other crossings (see Figure 2(a)), leaving the same chain as E3S5. As in Figure 2(b), N5S9 leaves the same chain as S4, and N9S5 leaves the same chain as N4.

Figure 1: the input E6S2W5S2E2N7 (a is the center of the screen)

Figure 2: drawing examples (a is the center of the screen)
Given a sequence of key presses, compute the resulting chain. You may assume the screen is large enough to hold the whole figure.
Input
Input is read from standard input. The first line contains the number of test cases . Each of the next lines holds one test case as a string , where each is one of N, S, E, W, each is a single digit from 0 to 9, and .
Output
For each test case, print one line with two integers and : is the number of line segments in the resulting chain, and is its total length (the sum of the lengths of all its segments). Adjacent pieces that lie on the same straight line count as a single segment.