您的位置:首页 > 其它

【CodeFores 798B】 Mike and strings(模拟+string)

2017-05-03 21:08 603 查看

[align=center]B. Mike and strings[/align]

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard 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个字符串,将第i个字符串移动xi位,使得最终所有字符串相等,求最小的移动步数和,若无法相等输出-1思路:n最大50个,枚举每一个字符串作为基础串,求得每种情况的移动步数和,取最小值。string find大发好,比赛时忘了用这个,结果没怼出来。果然还是不太熟悉
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

int main()
{
int n,ans;
string s,t,p;
while(~scanf("%d",&n)){
vector<string>v;
ans=INF;
for (int i=0; i<n; i++){
cin>>s;
v.push_back(s);
}
for (int i=0; i<n; i++){
int sum=0;
t=v[i];
for (int j=0; j<n; j++){
if (i!=j){
p=v[j];
p+=p;
int k=p.find(t); //返回下标
if (k==-1){
sum=-1;
break;
}
sum+=k;
}
}
if (sum != -1) ans=min(ans,sum);
}
if (ans==INF) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: