Necklaces
Time limit1sMemory limit128 MB
Decide whether two run-length compressed string descriptions encode the same circular necklace up to rotation.
- Level
Hard8 of 10
- Topics
- String, String matching, Implementation, Brute force
- Solved
- No attempts yet
Problem
Byteland is famous for the beautiful necklaces crafted by the jeweler Byteman. Each necklace is a loop of gemstones strung together. There are 26 kinds of stones, written as the lowercase Latin letters a to z (stones of the same kind are indistinguishable). Byteman never makes two identical necklaces, so he keeps a description of every necklace he has ever produced.
Because some necklaces are very long, their descriptions are stored in a compressed form. A description is a sequence of fragments. Each fragment is a pattern (a string of letters) together with an integer telling how many times that pattern repeats, and the necklace is obtained by concatenating the fragments in order. For example, a description whose patterns are abc repeated 2 times, xyz repeated 1 time, and axc repeated 3 times encodes the necklace abcabcxyzaxcaxcaxc.
The difficulty is that a necklace is a loop: there is no fixed starting stone, so the loop may be read starting from any position (the necklace can be rotated). Two descriptions therefore represent the same necklace when one loop can be rotated into the other. For instance, the necklace above can also be written as cabcxyzaxcaxcaxcab or xcaxcaxcabcabcxyza.
Given two descriptions, decide whether they encode the same necklace.
Input
The input has two lines, one description per line. A description is a list of tokens separated by single spaces. It starts with an integer , the number of patterns (), followed by pattern blocks. The -th block has three tokens: an integer , the length of the pattern (); the pattern , a string of exactly lowercase letters; and an integer , the number of times the pattern repeats (). For each description, the sum of all is at most .
Output
Print a single line: TAK (Polish for "yes") if the two descriptions encode the same necklace, or NIE (Polish for "no") otherwise.