Decide whether a repeated i/j/k string splits into three nonempty parts reducing to i, j, and k under quaternion multiplication.
Medium5SimulationBrute forceMathNo attempts yetTime limit5sMemory limit512 MBThe Dutch computer scientist Edsger Dijkstra left many results behind, among them the shortest path algorithm that carries his name. This problem is not about that algorithm.
You lost one point on an algorithms exam for misspelling "Dijkstra". Between D and stra you wrote some number of characters, each of which was i, j, or k. To win the point back you appeal to quaternions, a number system extended from the complex numbers. Quaternion multiplication follows this table.
| a×b | 1 | i | j | k |
|---|---|---|---|---|
| 1 | 1 | i | j | k |
| i | i | −1 | k | −j |
| j | j | −k | −1 | i |
| k | k | j | −i | −1 |
Look up the first quaternion in the rows and the second one in the columns, then read the cell where they meet. For example, in a×b with a=i and b=j the cell holds k, and with a=j and b=i the cell holds −k.
As those examples show, quaternion multiplication is not commutative: there are a and b with a×b=b×a. It is associative, so a×(b×c)=(a×b)×c holds for all a, b, and c.
Signs behave the usual way. For all quaternions a and b, (−a)×(−b)=a×b, and (−a)×b=a×(−b)=−(a×b).
To argue that your misspelling equals the correct spelling ijk, cut the string in two places into three substrings so that the leftmost one reduces to i, the middle one reduces to j, and the rightmost one reduces to k. None of the three substrings may be empty. For example, jij is evaluated as j×i×j. Here j×i=−k and −k×j=i, so jij reduces to i. Decide whether the given string admits such a split.
The first line contains the number of test cases T. T test cases follow. Each test case has two lines. The first line contains two space separated integers L and X, and the second line contains a string of L characters, each of which is i, j, or k. The string never contains a minus sign, a 1, or any other character. The string you must evaluate is the given string repeated X times. For example, with L=4, X=3, and the given string kiij, the string to evaluate is kiijkiijkiij.
For each test case, print one line in the form Case #x: y, where x is the test case number starting from 1 and y is YES if the evaluated string can be split into three parts under the rule above, and NO otherwise.
The test cases of the first example work out as follows.
i, j, and k.k, j, i, and it does not meet the condition.jijijijijiji. It splits into jij, which reduces to i, then iji, which reduces to j, then jijiji, which reduces to k.