Free Willy
Time limit5sMemory limit256 MB
Apply at most L of the given position permutations to turn the start word into the target word with the fewest steps.
Problem
Willy sits in a cage. The guard offers him his freedom if he solves a puzzle.
You are given two words of length and permutations that Willy may use. A permutation is written as a lowercase string that uses each of the first letters of the alphabet exactly once. Applying a permutation to a word produces a new word whose -th letter is the -th letter of , where is the alphabet position of the -th letter of . Count a as 1 and b as 2.
Applying the permutation bcdefaghi to the word KULTURUKE gives ULTURKUKE. The first six letters rotate one place to the left and the rest stay where they are.
Willy may use only the given permutations, and he may use the same permutation more than once. The cage opens if he turns the first word into the second word with at most applications. Find the smallest number of applications.
Input
The first line contains the number of test cases . ()
The first line of each test case contains , , and , separated by spaces. (, , )
The second line contains two words of length , separated by a space. Both words consist of English letters only.
Each of the next lines contains one allowed permutation, a string that uses each of the first lowercase letters of the alphabet exactly once.
Output
Print one line for each test case. Print the smallest number of applications needed to turn the first word into the second word, or whalemeat if it cannot be done with at most applications.