B. Mike and strings
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".

题意:

将所有字符串变成相等,只允许将最左边的字符移到最右,问最少要移多少步。

若不能使所有相等,则输出-1、

分别以每一个字符串为模板,将其他的字符串移成和当前字符串相等的情况,再找出步数最少的方案。

附AC代码:

 #include<bits/stdc++.h>
using namespace std; const int inf=<<; string s[]; int main(){
int n,i,j,k,m;
cin>>n;
for(i=;i<n;i++){
cin>>s[i];
}
int len=s[].size();
int ans=inf;
for(i=;i<n;i++){
int cnt=;
for(j=;j<n;j++){
for(m=;m<len;m++){
for(k=;k<len;k++){
if(s[i][k]!=s[j][(k+m)%len])
break;
}
if(k==len)//只有len个都相等才表明移动m个字符后两字符串相等
break;
}
if(m==len){//若m==len则表明不能匹配。
cnt=inf;
break;
}
cnt+=m;
}
ans=min(ans,cnt);
}
if(ans==inf)
cout<<-<<endl;
else
cout<<ans<<endl;
return ;
}

最新文章

  1. topshelf和quartz内部分享
  2. fuser 命令小结
  3. zookeeper启动错误 transaction type: 2 error: KeeperErrorCode = NoNode for /hbase
  4. POJ3613 Cow Relays(矩阵快速幂)
  5. poj3292-Semi-prime H-numbers(筛法打表)
  6. android linux shell 日期设置
  7. c++对象模型之Data布局
  8. 母函数&amp;&amp;排列(模板)
  9. [Swift]LeetCode638. 大礼包 | Shopping Offers
  10. Elasticsearch 集群和索引健康状态及常见错误说明
  11. python网络爬虫笔记(六)
  12. SpringCloud无废话入门04:Hystrix熔断器及监控
  13. 高级数据类型--字典(dict)
  14. openssl交叉编译记录
  15. 修改placeholder样式
  16. codevs 1131 统计单词数
  17. redis介绍(6)集群(ruby)
  18. 用C#实现对MSSqlServer数据库的增删改查---Server层(WaterLevelSetServer.cs、DeviceSetServer.cs)
  19. Overflow sort stage buffered data usage of 33554495 bytes exceeds internal limit of 33554432 bytes
  20. step5: 编写spider爬取

热门文章

  1. C#自定义类型数组排序
  2. enter键触发的函数
  3. docker安全最佳实践概述
  4. angular.js 入门
  5. Kubernetes对象之Pod
  6. kubernetes之初始容器(init container)
  7. JSON和JSONP 傻傻分不清楚?
  8. 九度OJ 1121:首字母大写 (字符串处理)
  9. AndroidSlideTest.java
  10. LVS项目介绍