Shift String

3

2 votes
Breadth-first search, Algorithms, Dynamic Programming and Bit Masking, Brute-force search, String, Dynamic Programming, Bitmask
Problem

Given a string, , of length, , and a list of  strings, .  All strings in the list are distinct and have length  i.e , and none of the given strings is equal to .

You can perform any number of operations .

In an operation you are allowed to choose one position in the string, , and change the character at the position to the next or previous character in the English alphabet cyclically ('a' -> 'b', 'b' -> 'c', 'c' -> 'd', ..., 'z' -> 'a', 'b' -> 'a', ...).

What is the minimum number of operations that you have to perform on, , so for all the given  strings,  becomes at least once after one of the performed operations. 

 

INPUT FORMAT 

The first line of the input contains an integer,     - denoting the length of the string

The second line of the input contains a string,  - denoting the string which you can perform operations on. Each character in  is a lowercase English alphabet ('a' - 'z'). 

The next line of the input contains an integer,  - denoting the number of strings that will be in the list.

The next  lines distinct strings,  (, )   - denoting a string in the list. Each character in  is a lowercase english alphabet ('a' - 'z')

 

OUTPUT FORMAT 

The output should contain one line denoting the minimum amount of operations that need to be performed on , to reach each of the strings at least once. 

Sample Input
3
abc
3
zbe
zbc
abd
Sample Output
5
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

In the sample input,  = abc, and we have 3 strings zbe, zbc, and abd, that  must become at least once, in one of the operations. 

One way of reaching all strings using the minimum number of operations is: 

  • OPERATION 1: shift index 2 (0-indexed) in s forward, s becomes = "abd" (s has now become )
  • OPERATION 2: shift index 0 (0-indexed) in s backward, s becomes = "zbd".
  • OPERATION 3: shift index 2 (0-indexed) in s forward, s becomes = "zbe" (s has now become ).
  • OPERATION 4: shift index 2 (0-indexed) in s backward, s becomes "zbd".
  • OPERATION 5: shift index 2 (0-indexed) in s backward, s becomes "zbc" (s has now become ).

It is not possible to reach all  strings using less than  operations. Hence, the answer to this input is .

Editor Image

?