B. Mike and strings

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".


一开始是没考虑到还有循环节的情况,然后直接暴力过就行了QAQ,:-(又是一波掉分,快上1200了QAQ。

#include <bits/stdc++.h>

using namespace std;
const int MAXN=3e5+7;
const int inf=1e9;
char s[60][60];
char s1[60];
int l;
int n;
int num[60];
int check(char *s)
{
    for(int i=0; i<l; ++i)
    {
        int j;
        for(j=0; j<l; ++j)
        {
            if(s1[j]!=s[(j+i)%l])break;
        }
        if(j>=l)return i;
    }
    return -1;
}
int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; ++i)scanf("%s",s[i]);
    l=strlen(s[0]);
    int ans=inf;
    for(int i=0; i<l; ++i)
    {
        int sum=0;
        for(int j=0; j<l; ++j)s1[j]=s[0][(j+i)%l];
        for(int j=0; j<n; ++j)
        {
            int t=check(s[j]);
            if(t==-1)
            {
                puts("-1");
                return 0;
            }
            sum+=t;
        }
        ans=min(ans,sum);
    }
    printf("%d\n",ans);
    return 0;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值