eolymp
bolt
Try our new interface for solving problems
Problems

Shuffling Strings

Shuffling Strings

Suppose \textbf{S_1} and \textbf{S_2} are two strings of size \textbf{n} consisting of characters \textbf{A} through \textbf{H} (capital letters). We plan to perform the following step several times to produce a given string \textbf{S}. In each step we shuffle \textbf{S_1} and \textbf{S_2} to get string \textbf{S_\{12. \}}Indeed, \textbf{S_12} is obtained by scanning \textbf{S_1} and \textbf{S_2} from left to right and putting their characters alternatively in \textbf{S_\{12 \}}from left to right. The shuffling operation always starts with the leftmost character of \textbf{S_2}. After this operation, we set \textbf{S_1} and \textbf{S_2} to be the first half and the second half of \textbf{S_12}, respectively. For instance, if \textbf{S_1 = ABCHAD} and \textbf{S_2 = DEFDAC}, then \textbf{S_\{12 \}= DAEBFCDHAACD}, and for the next step \textbf{S_1 = DAEBFC} and \textbf{S_2 = DHAACD}. For the given string \textbf{S} of size \textbf{2n}, the goal is to determine whether \textbf{S_12 = S} at some step. \InputFile There are multiple test cases in the input. Each test case starts with a line containing a non-negative integers \textbf{0} ≤ \textbf{n} ≤ \textbf{100} which is the length of \textbf{S_1} and \textbf{S_2}. The remainder of each test case consists of three lines. The first and the second lines contain strings \textbf{S_1} and \textbf{S_2} with size \textbf{n}, respectively, and the last line contains string \textbf{S} with size \textbf{2n}. The input terminates with "\textbf{0}" which should not be processed. \OutputFile For each test case, output \textbf{-1} if \textbf{S} is not reachable. Otherwise, output the minimum number of steps to reach \textbf{S}. To make your life easier, we inform you that the output is not greater than \textbf{50} for the given input.
Time limit 1 second
Memory limit 64 MiB
Input example #1
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC
0
Output example #1
2
-1
Source 11th Iran Internet Programming Contest, 28 November, 2013 (7 Azar, 1392)