General Bytor
Time limit1sMemory limit128 MB
Given two permutations of n unit types and m cyclic position-shift orders, find the shortest (then lexicographically smallest) sequence of at most 10 orders that transforms the start into the target.
- Level
Hard8 of 10
- Topics
- Brute force, String, Hash map, BFS
- Solved
- No attempts yet
Problem
The Qbits are coming!
General Bytor, commander-in-chief of Fort Bytemore, suddenly woke up, rushed to headquarters, and checked the battle plan. The situation did not look good. Every important strategic position of the fort held exactly one army unit, but some units were in the wrong place. Worse still, giving orders had become very difficult: the Qbits' secret agents had used quantum teleportation to kidnap every cryptographer in the fort. Now Bytor can issue only the few orders he memorized during recent training.
Each order corresponds to a single line running through a sequence of strategic positions. When an order is given, every army unit on that line advances one step to the next position along the line. Each line is in fact a cycle, so after the movement every strategic position again holds exactly one unit.
About half an hour remains before the battle begins, and in that time Bytor can perform at most 10 orders. Given the initial and requested arrangements, write a program that decides whether a short enough sequence of orders leads from the initial arrangement to the requested one, and if so, finds it.
Input
The first line contains two integers and (, ), separated by a single space. is the number of strategic positions and is the number of lines.
The second line contains a word of lowercase English letters. The -th letter is the type of the unit currently located at the -th strategic position (given by the old Bytean military code). Several units may share the same type.
The third line also contains a word of lowercase letters. It gives the unit types that must occupy strategic positions after the movements. This word is different from the one on the second line.
Each of the next lines describes one line in the form (numbers separated by single spaces). The first number is the number of strategic positions on the line, and () is the -th position on the line. All numbers on a single line are distinct. Issuing this order moves the units as follows: .
Output
If the requested arrangement cannot be reached with at most 10 orders, output the single word NIE (Polish for "no").
Otherwise output at most 10 line numbers (each between and ), separated by spaces, that Bytor should issue in order. If several sequences work, output the one with the fewest orders; if there are still several, output the lexicographically smallest one. (Let be the first position at which two equal-length sequences differ; the sequence whose -th order has the smaller line number is the lexicographically smaller one.)