Can't stop playing
Time limit10sMemory limit256 MB
Stick each arriving power-of-two block to the left or right end, merge equal neighbours, and report if one block can remain with the smallest direction string.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Bit manipulation, Simulation, Backtracking
- Solved
- No attempts yet
Problem
You are given one dimensional blocks, each of a length that is a power of two. The blocks arrive one at a time in the given order. When a block arrives you must stick it either to the far left or to the far right of the blocks placed so far. The first block gives the same row on both sides.
Whenever two neighbouring blocks have the same length, they merge into one block of twice that length. If the merged block again has the same length as a neighbour, merging continues until no two neighbours have the same length. At most one mergeable pair exists at any moment, so the result of the merging is decided by the directions you choose.
For example, if the current row is 2, 4, 16 and you stick a block of length 2 to the left, then 2, 2, 4, 16 becomes 4, 4, 16 and then 8, 16. Sticking the same block to the right gives 2, 4, 16, 2 with no pair to merge.
You win when a single block is left after all blocks are placed. Decide whether the given order can be won, and print the directions when it can.
Input
The first line contains the number of test cases ().
Each test case takes two lines. The first line contains the number of blocks (). The second line contains the block lengths in arrival order, separated by spaces. Each length is a power of two, and the lengths of one test case add up to at most .
Output
Print one line for each test case.
If a single block cannot be reached, print no.
Otherwise print a string of characters. The th character is l if the th block goes to the left and r if it goes to the right. Several strings can win, so print only the lexicographically smallest one. l comes before r, and the first block gives the same row on both sides, so this string always starts with l.