码迷,mamicode.com
首页 > 其他好文 > 详细

Mike and strings

时间:2020-02-23 16:29:53      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:for   ecif   exce   暴力   stat   testcase   follow   else   can   

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

 

 


 

数据量小,暴力解决

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <numeric>
#include <cmath>
#include <unordered_set>
#include <unordered_map>
#include <xfunctional>
#define ll long long
#define mod 998244353
using namespace std;
int dir[4][2] = { {0,1},{0,-1},{-1,0},{1,0} };
const int maxn = 16;
const long long inf = 0x7f7f7f7f7f7f7f7f;

int main()
{
    int n;
    cin >> n;
    vector<string> s(n);
    for (int i = 0; i < n; i++)
        cin >> s[i];
    int len = s[0].size();
    int dp=1e9;
    for (int i = 0; i < n; i++)
    {
        int cnt = 0;
        for (int j = 0; j < n; j++)
        {
            string t=s[j];
            if (j != i)
            {
                for (int k = 0; k < len; k++)
                {    
                    if (k == len - 1 && t != s[i])
                    {
                        cout << -1;
                        return 0;
                    }
                    if (t == s[i])
                        break;
                    else
                    {
                        char first=t[0];
                        t.erase(0,1);
                        t += first;
                        cnt++;
                    }
                }
            }
        }
        dp = min(dp, cnt);
    }
    cout << dp;
    return 0;
}

 

Mike and strings

标签:for   ecif   exce   暴力   stat   testcase   follow   else   can   

原文地址:https://www.cnblogs.com/dealer/p/12350111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!