Problem:
Problem B: Repeated Substitution with Sed

Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every
occurrence of a string contained in the input string (actually each input line) with another
string β. More precisely, it proceeds as follows.

Within the input string, every non-overlapping (but possibly adjacent) occurrences of α are
marked. If there is more than one possibility for non-overlapping matching, the leftmost
one is chosen.

Each of the marked occurrences is substituted with β to obtain the output string; other
parts of the input string remain intact.

For example, when α is "aa" and β is "bca", an input string "aaxaaa" will produce "bcaxbcaa",
but not "aaxbcaa" nor "bcaxabca". Further application of the same substitution to the string
"bcaxbcaa" will result in "bcaxbcbca", but this is another substitution, which is counted as the
second one.

In this problem, a set of substitution pairs (αi, βi) (i = 1, 2, ... , n), an initial string γ, and a
final string δ are given, and you must investigate how to produce δ from γ with a minimum
number of substitutions. A single substitution (αi, βi) here means simultaneously substituting
all the non-overlapping occurrences of αi, in the sense described above, with βi.

You may use a specific substitution (αi, βi ) multiple times, including zero times.

Input

The input consists of multiple datasets, each in the following format.

n

α1 β1

α2 β2

.

.

.

αn βn

γ

δ

n is a positive integer indicating the number of pairs. αi and βi are separated by a single space.
You may assume that 1 ≤ |αi| < |βi| ≤ 10 for any i (|s| means the length of the string s),

αi ≠ αj for any i ≠ j, n ≤ 10 and 1 ≤ |γ| < |δ| ≤ 10. All the strings consist solely of lowercase
letters. The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output the minimum number of substitutions to obtain δ from γ. If δ cannot
be produced from γ with the given set of substitutions, output -1.

Sample Input

2
a bb
b aa
a
bbbbbbbb
1
a aa
a
aaaaa
3
ab aab
abc aadc
ad dee
abc
deeeeeeeec
10
a abc
b bai
c acf
d bed
e abh
f fag
g abe
h bag
i aaj
j bbb
a
abacfaabe
0

Output for the Sample Input

3
-1
7
4

Solution in JAVA (judge verdict: Accepted)


import java.io.*;
import java.util.*;

public class Main {
	FastScanner in = new FastScanner(System.in);
	PrintWriter out = new PrintWriter(System.out);

	public void run() {
		while (true) {
			int n = in.nextInt();
			if (n == 0) break;
			String[] from = new String[n];
			String[] to = new String[n];
			
			for (int i = 0; i < n; i++) {
				from[i] = in.next();
				to[i] = in.next();
			}
			
			String src = in.next(), dst = in.next();
			
			Queue<String> q = new LinkedList<String>();
			HashMap<String, Integer> hash = new HashMap<String, Integer>();
			q.add(src);
			hash.put(src, 0);
			while (!q.isEmpty()) {
				String next = q.poll();
				int now = hash.get(next);
				
				for (int i = 0; i < n; i++) {
					String after = next.replaceAll(from[i], to[i]);
					if (!hash.containsKey(after) && after.length() <= dst.length()) {
						hash.put(after, now + 1);
						q.add(after);
					}
				}
			}
			System.out.println(hash.containsKey(dst) ? hash.get(dst) : -1);
		}
		out.close();
	}

	public static void main(String[] args) {
		new Main().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}