B. Mike and strings
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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”.
题目大意:给出n个 字符串,每个进行若干次循环左移,若最后所有字符串相等,问总的最小左移次数,否则输出-1
解题思路:循环左移联想到模运算,取不同的最终串,分别计算,暴力比对即可
#include<bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int MAXN = 100;
string s[MAXN];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for(int i=0;i<n;i++)
cin>>s[i];
int m = s[0].length();
int ans = INF;
for(int k=0;k<m;k++)
{
int t = 0;
for(int i=0;i<n;i++)
{
bool good = false;
for(int j=0;j<m;j++)
{
bool ok = true;
for(int g=0;g<m;g++)
{
ok &= (s[0][(k+g)%m] == s[i][(j+g)%m]);
}
if(ok)
{
good = true;
t += j;
break;
}
}
if(!good)
{
cout << -1 << endl;
return 0;
}
}
ans=min(ans,t);
}
cout << ans << endl;
return 0;
}