CCCGuide

Problem J5: Rule of Three

2019 · J5 · Original problem · DMOJ

Problem Description

A substitution rule describes how to take a sequence of symbols and convert it into a different sequence of symbols. For example, ABA →\rightarrow BBB, is a substitution rule which means that ABA can be replaced with BBB. Using this rule, the sequence AABAA would be transformed into the sequence ABBBA (the substituted symbols are in bold).

In this task, you will be given three substitution rules, a starting sequence of symbols and a final sequence of symbols. You are to use the substitution rules to convert the starting sequence into the final sequence, using a specified number of substitutions.

For example, if the three substitution rules were:

  1. AA →\rightarrow AB

  2. AB →\rightarrow BB

  3. B →\rightarrow AA

we could convert the sequence AB into AAAB in 4 steps, by the following substitutions:

AB →\rightarrow BB →\rightarrow AAB →\rightarrow AAAA →\rightarrow AAAB,

where the symbols to be replaced are shown in bold. More specifically, from the initial sequence AB, substitute rule 2 starting at position 1, to get the result BB. From BB, substitute rule 3, starting at position 1, to get the result AAB. From AAB, substitute rule 3, starting at position 3, to get the result AAAA. From AAAA, substitute rule 1, starting at position 3, to get the result AAAB, which is the final sequence.

Input Specification

The first three lines will contain the substitution rules. Each substitution rule will be a sequence of A’s and B’s, followed by a space following by another sequence of A’s and B’s. Both sequences will have between one and five symbols.

The next line contains three space separated values, SS, II and FF. The value SS (1≤S≤151 \leq S \leq 15) is an integer specifying the number of steps that must be used, and the values II (the initial sequence) and FF (the final sequence) are sequences of A’s and B’s, where there are at least one and at most 5 symbols in II and at least one and at most 50 symbols in FF.

For 7 of the 15 marks available, S≤6S \le 6.

For an additional 7 of the 15 available marks, S≤12S \le 12.

Output Specification

The output will be SS lines long and describes the substitutions in order.

Line ii of the output will contain three space-separated values, RiR_i, PiP_i, and WiW_i:

There will always be at least one sequence of SS substitutions that will convert II into FF. If there is more than one possible sequence of substitutions, any valid sequence will be accepted.

Sample Input

AA AB
AB BB
B AA
4 AB AAAB

Possible Output for Sample Input

2 1 BB
3 1 AAB
3 3 AAAA
1 3 AAAB

Explanation of Output for Sample Input

This is the example outlined in the problem description. Note that the following is another possible valid substitution sequence:

2 1 BB
3 2 BAA
1 2 BAB
3 1 AAAB

Specifically, showing the substitutions in bold, we get

AB →\rightarrow BB →\rightarrow BAA →\rightarrow BAB →\rightarrow AAAB.