Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one…
- User
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal? Input
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings.
This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
Output
Print the minimal number of moves Mike needs in order to make all the strings equal or print - 1 if there is no solution.
Examples
Input
4 xzzwo zwoxz zzwox xzzwo
Output
5
Input
2 molzv lzvmo
Output
2
Input
3 kc kc kc
Output
0
Input
3 aa aa ab
Output
-1
Note
In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Assistant
n = int(input()) strings = [input().strip() for _ in range(n)] # Check if all strings have the same length m = len(strings[0]) for s in strings[1:]: if len(s) != m: print(-1) exit() min_total = float('inf') # Generate all possible rotations of the first string for k in range(m): candidate = strings[0][k:] + strings[0][:k] current_sum = k valid = True for s in strings[1:]: found = False for l in range(m): rotated = s[l:] + s[:l] if rotated == candidate: current_sum += l found = True break if not found: valid = False break if valid: if current_sum < min_total: min_total = current_sum print(min_total if min_total != float('inf') else -1)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.