UVa 10941 - Words adjustment

10941 - Words Adjustment

 * http://acm.uva.es/p/v109/10941.html

Summary
Given two words $$x$$, $$y$$, and a dictionary with a number of words, it is allowed to append to $$x$$ and $$y$$ any words from the dictionary. Determine the minimum number of words that must be appended to make $$x$$ and $$y$$ equal.

Explanation
The problem can be solved by BFS. The state in BFS is the unadjusted suffix of the longer of the two words.

Trivia
The original problem by Wojciech Rytter was offered at Polish Olympiad in Informatics 1995/1996.

Input
2 abba ab 4 baaabad aa badccaa cc a ab 4 bb ab ba aa

Output
5 -1

More test cases are available here.