Codeforces 798B Mike and strings

来源:互联网 发布:淘宝衣服店铺排名查询 编辑:程序博客网 时间:2024/06/07 07:08

题意:

          给出 N 个串,问最少能移动几次使 N 个串都相等。

          移动的规则是,每次只能将一个串首的字符移到串尾。

          N 最大 50,串长最大 50。

思路:

          竟然是暴力题。 50^4 并不超时……

代码:

#include <iostream>#include <cstring>#include <map>#include <string>#include <cstdio>using namespace std;string str[51];int n;int tans,ans,fans,len;int judge(int id){    bool flag;    for(int i=0;i<len;i++){        flag=1;        for(int j=0;j<len&&flag;j++){            if(str[0][j]!=str[id][(i+j)%len])                flag=0;        }        if(flag)            return i;    }    return -1;}int solve(){    fans=99999999;    string temp;    temp=str[1];    temp+=str[1];    len=str[1].size();    for(int i=0;i<len;i++){        str[0]=temp.substr(i,len);        tans=0;        for(int j=1;j<=n;j++){            ans=judge(j);            if(ans==-1)                return -1;            else                tans+=ans;        }        if(fans>tans) fans=tans;    }    return fans;}int main(){    ios::sync_with_stdio(false);    while(cin>>n){        for(int i=1;i<=n;i++)            cin>>str[i];        cout<<solve()<<endl;    }}

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
4xzzwozwoxzzzwoxxzzwo
output
5
input
2molzvlzvmo
output
2
input
3kckckc
output
0
input
3aaaaab
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".




0 0
原创粉丝点击