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
inputCopy
4
xzzwo
zwoxz
zzwox
xzzwo
outputCopy
5
inputCopy
2
molzv
lzvmo
outputCopy
2
inputCopy
3
kc
kc
kc
outputCopy
0
inputCopy
3
aa
aa
ab
outputCopy
-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”.
题意:对于某个字符串,将前面字符删除添加到末尾,问最少几步可以将这 n 个字符串都变成相同的?如果不行则输出-1.
思路:当然是找这n个字符串中匹配度最大的那部分,然后将相互匹配的左部分移去右边即可。看上去似乎很麻烦,但其实有了 string.find 就很好解决了,如果对于某个字符串,在剩下的字符串中没找到,即 string::npos, 此时输出-1.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define maxn 200005
const int mod=1e9+7;
#define eps 1e-6
#define pi acos(-1.0)
ll quickpow(ll a,ll b,ll m)
{
ll ans=1;
while(b){
if(b&1){
ans=ans*a%m;
}
a=a*a%m;
b>>=1;
}
return ans;
}
string s[100];
int main()
{
ios::sync_with_stdio(false);
int n;
cin>>n;
int i,j;
for(i=0;i<n;i++)cin>>s[i];
int len=s[0].length();
int cnt=0;
int ans=inf;
int flag=0;
for(i=0;i<n;i++){
int sum=0;
for(j=0;j<n;j++){
string temp=s[j]+s[j];
if(temp.find(s[i])==string::npos)flag=1;
sum+=temp.find(s[i]);
}
ans=min(ans,sum);
}
if(flag)cout<<-1<<endl;
else cout<<ans<<endl;
}