Codeforces Round #410 (Div. 2) 798 B Mike and strings

1.题目链接

http://codeforces.com/contest/798/problem/B

2.题面

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
Copy
4
xzzwo
zwoxz
zzwox
xzzwo
output
Copy
5
input
Copy
2
molzv
lzvmo
output
Copy
2
input
Copy
3
kc
kc
kc
output
Copy
0
input
Copy
3
aa
aa
ab
output
Copy
-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".


3.题意

给个 n 个串,每次我们能将一个串的第一个字符移到该串末尾,问我们至少要移动多少次,才能使所有串相同。

4.思路

每次选定一个字符串作为目标字符串,然后把其他所有字符串都当做测试字符串,依次计算出总共需要的步数,再在找出的步数中找到最小的那个

5.代码

#include<bits/stdc++.h>
using namespace std;
string s[105];
int main()
{
    int n;
    cin >> n;
    for(int i=0;i<n;i++)
        cin>>s[i];
    int m = s[0].length();
    int ans = 1e9;
    for(int k=0;k<m;k++)
    {
        int t = 0;
        for(int i=0;i<n;i++)
        {
            bool keyi = 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)
                {
                    keyi = true;
                    t += j;
                    break;
                }
            }
            if(!keyi)
            {
                cout << -1 << endl;
                return 0;
            }
        }
        ans=min(ans,t);
    }
    cout << ans << endl;
    return 0;
}

    6.反思

本来觉得这个找到最长子串直接就行了 速度也快 但是后来发现问题很多 根本写不动 有的时候应该估算一下 该暴力直接暴力来

.






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值