Tree Hugging
Time limit2sMemory limit512 MB
Given 2(n-1) edges on n points, decide whether they can be split into a left-rooted increasing tree and a right-rooted decreasing tree, and output one such labeling.
- Level
Hard8 of 10
- Topics
- Graph, Greedy, DFS, Implementation
- Solved
- No attempts yet
Problem
Once, two trees forgot their place and started to grow into each other. One of the trees grew from the left, and the other from the right. They collided on points.
Numbering the points from left to right, the left tree connected all of them in a single subtree rooted at node 1, such that every node's children had larger numbers than the node itself. We can describe this subtree with a list of edges.
Similarly, the right tree also connected all nodes in a single subtree rooted at node , with every node's children having smaller numbers than the node itself. This yields another edges.
Now, given the full list of edges, it is not necessarily easy to tell which edge belongs to which tree. Can you find a possible assignment, or determine that this collection could not have been the union of two trees?
Input
The first line of input contains the integer (). The next lines each contain two integers () indicating an edge joining the two nodes and . A pair may be connected by more than one edge.
Output
If the edges can be the union of two trees that grow left-to-right and right-to-left, output a string of length , where the th character is L if the th edge comes from the left tree, or R if it comes from the right tree. Otherwise, output the word "impossible" on a single line. If there are multiple solutions, you may output any one of them.
Notes
In the first example, there are two solutions: LLRRRRLL and LLRLRRLR.
In the second example, there are no solutions. Note that LRLR is not valid, because it would involve the right tree growing backward, from left to right.