This page is still under construction.

Parts of this page are still being built. What you see may change.

Necklaces

Time limit1sMemory limit128 MB

Summary
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 nn, the number of patterns (1≤n≤10001 \le n \le 1000), followed by nn pattern blocks. The ii-th block has three tokens: an integer lil_i, the length of the pattern (1≤li≤100001 \le l_i \le 10000); the pattern sis_i, a string of exactly lil_i lowercase letters; and an integer kik_i, the number of times the pattern repeats (1≤ki≤1000001 \le k_i \le 100000). For each description, the sum of all lil_i is at most 1000010000.

Output

Print a single line: TAK (Polish for "yes") if the two descriptions encode the same necklace, or NIE (Polish for "no") otherwise.

Examples3

  1. Example 1

    Input
    3 3 abc 2 3 xyz 1 3 axc 3
    4 4 cabc 1 4 xyza 1 3 xca 3 1 b 1
    
    Expected output
    TAK
    
  2. Example 2

    Input
    1 3 abc 2
    1 3 abc 1
    
    Expected output
    NIE
    
  3. Example 3

    Input
    1 2 ab 2
    1 2 ba 2
    
    Expected output
    TAK