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”.
解题思路:如果字符串ch[0],ch[1],ch[2]…ch[n-2],ch[n-1]能通过题中所给字符转移方式达到目的,则存在所有字符串的最终形式c,满足ch[i]+ch[i]包含c(例如:ch[i]=“bca”,c=“abc”,str=ch[i]+ch[i];则str(“bcabca”)包含c(“abc”),而将字符串ch[i]转化为c的转移次数为c在str中起始位置的下标:2)。
知识点:
find()函数:
str.find(“字符串”)返回值为字符串在母串str中起始位置的下标。假如字符串存在包含关系,其返回值必不等于npos;不存在包含关系则返回值一定为npos。在str中找不到字符串返回-1(找不到也为True),非0为True,0为Flase。
string::npos :
npos是一个常数,用来表示不存在的位置,取值一般是-1。
另外:
解题方法非本人原创,我负责讲题。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n,i,j;string ch[60],c;
cin>>n;
for(i=0;i<n;i++)
{
cin>>ch[i];
}
int s=INT_MAX,m;
for(i=0;i<n;i++)//将n个字符串转化为ch[i]
{
m=0;//m为把所有字符串转移成ch[i]的 转移次数
for(j=0;j<n;j++)
{
c=ch[j]+ch[j];//按照你猜测的顺序把两个ch[j]相连赋给c
if(c.find(ch[i])==string::npos)//在c中没有查找到
{
cout<<"-1\n";return 0;
}
m+=c.find(ch[i]);//加上ch[i]在c的位置(下标)
}
s=min(s,m);//找出最少转移次数
}
cout<<s;
return 0;
}