Codeforces #410(div2) 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

#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int mod = 1e9+7;
const int N = 1010;
char q[100], a[100],w[100];
char str[N][N];
int n, len;
void f(char aa[],char b[], int x)
{
    for(int i = 0;i < len; i++) {
        aa[i] = b[(i+x)%len];
    }
//  aa[len] = '\0';
}
int main()
{
    scanf("%d",&n);
    getchar();
    scanf("%s",a);
    for(int i = 1;i < n; i++) scanf("%s",str[i]);
    len = strlen(a);
    int ans = inf;
    for(int i = 0;i <= len-1; i++) {
        int tmp = i;
        f(q,a,i);
        int go = 0;
        for(int j = 1; j < n; j++) {
            int low = inf;
            for(int k = 0;k <= len-1; k++) {
                f(w,str[j],k);
                if(strcmp(q,w)==0) {
                    tmp += k;
                    go++;
                    break;
                }
            }
        }
        if(go == n-1) ans = min(ans,tmp);
    }
    if(ans == inf) puts("-1");
    else    printf("%d\n",ans);
return 0;
}


















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值