Chairs
InterviewTime limit1sMemory limit1024 MB
Find the lexicographically smallest shortest R/D path from the top-left to the bottom-right cell that visits every chair, or report Impossible.
- Level
Medium5 of 10
- Topics
- Sorting, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
Ostap and Kisa are at a chair sale. They have two problems. First, they must leave the sale as soon as possible, because their rival company, represented by father Theodore, is closing in on them. Second, they must collect all the chairs at the sale.
The sale site is a rectangular table with rows and columns. Some cells contain chairs that need to be collected. Ostap and Kisa start at the top-left cell , and the exit is at the bottom-right cell . A single move takes them from their current cell to any cell that shares a side with it. When they pass through a cell with a chair, they take that chair with them. Find a shortest path from the start cell to the exit cell. Among all such paths, find one that passes through every cell with a chair, or determine that no such path exists.
Input
The first line contains three integers , , and , the size of the table and the number of chairs (, ). Each of the following lines contains two integers and , the row and the column of the -th chair (, ). No cell contains more than one chair.
Output
If no shortest path passes through all the chairs, print Impossible on a single line.
Otherwise, print the sequence of moves on a single line. Each move is one symbol: R for moving right, and D for moving down. If several solutions exist, print the lexicographically smallest one.