Untangling Chain
Time limit0.5sMemory limit512 MB
Given edge turn directions, rebuild the chain by always extending the current bounding box by one in the heading direction and print the resulting edge lengths.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation
- Solved
- No attempts yet
Problem
A rectilinear chain is an ordered sequence of segments that alternates between horizontal and vertical. Its first segment starts at the origin and goes to the right. A rectilinear chain of edges is described by pairs , where is the length of the -th edge and is the turning direction from to . For , if the chain turns left and if it turns right. For , marks as the last edge. For example, the chain in figure (a) is described by (4, 1), (5, -1), (2, -1), (2, -1), (4, 1), (5, 0).

Figure. (a) A chain that is not simple. (b) An untangled simple chain.
A chain is simple if no two of its edges share a point, apart from the endpoint that two adjacent edges share. The chain in figure (a) is not simple. Keeping every turning direction and changing only the length of each edge untangles the chain into a simple one. In the untangled chain each length must be between and . Figure (b) shows one untangling of (a), described by (4, 1), (5, -1), (2, -1), (2, -1), (1, 1), (2, 0).
A chain usually has many untanglings. To pin the answer down to one, only the chain built by the rule in the output section counts as correct.
Input
The first line contains an integer (), the number of edges of the chain. Each of the next lines contains two integers separated by a single space: the length of () and the turning direction from to . For , is for a left turn and for a right turn, and .
Output
Print the edge lengths of the chain built by the rule below, in the input order, on one line separated by single spaces. The turning directions match the input, so do not print them.
Start at the origin , which is the only visited point at the beginning. For up to in order, fix the endpoint of as follows. The visited points are the origin together with the endpoints of through .
- If goes right, the x coordinate of its endpoint is more than the largest x coordinate among the visited points.
- If goes left, the x coordinate of its endpoint is less than the smallest x coordinate among the visited points.
- If goes up, the y coordinate of its endpoint is more than the largest y coordinate among the visited points.
- If goes down, the y coordinate of its endpoint is less than the smallest y coordinate among the visited points.
The length of is the distance between its start point and its endpoint. The chain built this way is always simple, and every length is between and . The rule does not use the lengths given in the input.