Using sed
Time limit1sMemory limit128 MB
Find the minimum number of sed-style leftmost non-overlapping replacement operations needed to turn one small string into another, given up to 10 rewrite rules.
- Level
Hard8 of 10
- Topics
- BFS, String matching, Simulation
- Solved
- No attempts yet
Problem
sed is a Linux utility that replaces occurrences of a string with another string in the strings given as input; here, each input string is a single line of a file. sed performs the following two steps:
- Mark non-overlapping occurrences of in the input string. (Occurrences of may overlap one another in the text, but the marked ones must not overlap.) When there is more than one way to choose a non-overlapping set of occurrences, choose the leftmost ones.
- Replace every marked with simultaneously. All other characters are left unchanged.
For example, if is aa, is bca, and the input string is aaxaaa, then running sed gives bcaxbcaa (it cannot be aaxbcaa or bcaxabca). Running sed again on bcaxbcaa gives bcaxbcbca.
You are given replacement rules for , an initial string , and a target string . Using sed, you want to transform into with the minimum number of replacement operations.
A single rule , as described above, replaces all non-overlapping (leftmost) occurrences of in the current string with at the same time; this counts as one operation. Each rule may be used any number of times, including zero.
Input
The input consists of several test cases. Each test case has the following format:
n
α1 β1
α2 β2
...
αn βn
γ
δ
Here is the number of replacement rules. Each and are separated by a space and satisfy , where denotes the length of the string . For all , . Also and . All strings consist of lowercase letters only. The last line of the input contains a single .
Output
For each test case, output the minimum number of replacement operations needed to transform into . If cannot be transformed into , output .