Word Equalizing
Time limit1sMemory limit128 MB
Append the given words to x and y any number of times to make them equal, and output the minimum total number of appends, or NIE if impossible.
- Level
Medium7 of 10
- Topics
- String, Graph, BFS, String matching
- Solved
- No attempts yet
Problem
You are given two words and , together with a series of words . The operation appends the series word () to the end of the word (concatenation): it writes immediately after .
By appending series words to the ends of and (using any word as many times as you like, on either word), decide whether the two words can be made identical. If it is possible, output the minimum number of operations required; otherwise output NIE ("no" in Polish).
For example, the words abba and ab can be equalized using the series baaabad, aa, badccaa, cc: append aa and badccaa to abba, and append baaabad, then cc, then aa to ab. Both become abbaaabadccaa, using operations in total.
Input
The first line contains a positive integer (), the length of the series. The second and third lines contain the descriptions of and . The next lines contain the descriptions of , one per line. Each description consists of the word's length (a natural number) and the word itself, separated by a single space. Every word consists only of lowercase letters a to z and has length at most 2,000. The total length of all given words is at most 5,000.
Output
If and can be equalized, output the minimum number of operations (a nonnegative integer). Otherwise, output NIE.