Mike and strings
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”.
思路:目标字符串是所个字符串其中一个,把所有情况遍历就行了。
#include <iostream>
#include <queue>
#include<cstdio>
#include<cstring>
#include <math.h>
using namespace std;
char a[100][100];
int ans;
void fun(char a[100],char b[100])
{
int n=strlen(a),i,t,f=1;
char c[100],d;
ans=0,t=n;
for(i=0;i<n;i++)
{
c[i]=a[i];
}
c[n]='\0';
while(t--)
{
if(strcmp(c,b)==0)
{
f=0;
break;
}
d=c[0];
for(i=0;i<n-1;i++)
{
c[i]=c[i+1];
}
c[n-1]=d;
ans++;
}
if(f)
{
ans=-1;
}
}
int main()
{
int i,j,m,num;
cin>>m;
int sum[m]={0};
for(i=0;i<m;i++)
{
cin>>a[i];
}
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(j!=i)
{
fun(a[j],a[i]);
sum[i]+=ans;
}
}
}
num=sum[0];
for(i=0;i<m;i++)
{
if(num>sum[i])
{
num=sum[i];
}
}
if(num>=0)
printf("%d\n",num);
else printf("-1\n");
}