Windy Path
InterviewTime limit2sMemory limit512 MB
Given N points and a string of L/R turns, build the non-crossing path by repeatedly picking the unused point that is extreme (leftmost or rightmost) relative to the last point.
- Level
Medium6 of 10
- Topics
- Geometry, Greedy, Sorting, Implementation
- Solved
- No attempts yet
Problem

The path in the figure starts at (4, 4) and goes to (2, 5). There it turns right toward (1, 6), then makes a sharp left to (5, 0), then one more left to (4, 2). Writing L for a left turn and R for a right turn, the turn directions along this path are RLL. The path does not cross itself. The only place where two segments meet is a point of the path.
Now solve the reverse problem. points are given in an arbitrary order. Find an order that visits every point exactly once so that the path does not cross itself and the string of its turn directions equals a given string. For example, with the points (2, 5), (1, 6), (4, 4), (5, 0), (4, 2) given in that order and the turn string RLL, the order 3 1 2 4 5 traces the path in the figure. It starts at the third point (4, 4), then takes the first, second, fourth, and fifth points.
For three consecutive points , , , the turn at is decided by the sign of the cross product . A positive sign is L and a negative sign is R. The input never contains three points on one line, so the sign is never 0.
Several orders usually satisfy the same string. The order 3 1 2 4 5 above is one of them, and it can differ from the answer that the output rule below selects.
Input
The first line contains the number of points (). Each of the next lines contains the coordinates and of one point, separated by a space (). The points are distinct and no three of them lie on one line. The last line contains a string of length made only of the characters L and R.
Output
Print, on one line, the permutation that the following procedure builds. The points are numbered 1 to in the order they are given, and the numbers are separated by single spaces.
- Start at the point with the smallest coordinate. If several points share that , start at the one with the smallest coordinate among them.
- Repeat the following for to . Let be the last point of the path built so far and let be the -th character of the turn string. Among the unused points, take the point with this property. If is L, every other unused point lies strictly to the left of the directed line from to . If is R, every other unused point lies strictly to the right. Exactly one such exists. Append to the path.
- Append the single point that is still unused.
The path built this way does not cross itself, and its turn directions equal the given string.