We will denote generators as a and b and their reverses as A and B respectively. The group can be described as a set of words consisting of a, b, A and B, the operation of concatentation, and the generating relations aA = Aa = Bb = bB = ε.
In other words, we say that two words are equivalent if one can be transformed to another by successively performing the following operations:
For example, words abAaBBabbA and aAaBabaAbA are equivalent:
abAaBBabbA → abBBabbA → aBabbA → aAaBabbA → aAaBabaAbA;
but words abAB and baBA are not.
Equivalence classes of words are exactly the elements of the group.
It is interesting to note that for each word α and each word β there is such word γ equivalent to that α contains β as a subword. Your task in this problem is to find the shortest such word