Codeforces Round #410 (Div. 2) B. Mike and strings(字符串匹配)

来源:互联网 发布:java patternlayout 编辑:程序博客网 时间:2024/06/01 07:41
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".

题目大意:给n个字符串要求使之都相同,问一共最小操作次数,要是无法相同输出-1
解题思路:由于给的数据比较小,所以可以暴力的去做,同时要在匹配中找出来那些虽然每个字符串出现的字母相同,但是顺序导致无法匹配的情况
#include<iostream>    #include<cstdio>  #include<stdio.h>  #include<cstring>    #include<cstdio>    #include<climits>    #include<cmath>   #include<vector>  #include <bitset>  #include<algorithm>    #include <queue>  #include<map>  #include<stack>using namespace std;int i, n, k, j, sum, ans, ss, l, s;bool a[30];string str[55];int main(){cin >> n;for (i = 1; i <= n; i++){cin >> str[i];}k = str[1].length();memset(a, false, sizeof(a));for (i = 0; i < k; i++){a[str[1][i] - 'a'] = true;}for (i = 1; i <= n; i++){for (j = 0; j < k; j++){if (a[str[i][j] - 'a'] == false){cout << -1 << endl;return 0;}}}sum = 1000000;ans = 0;for (i = 1; i <= n; i++){for (j = 1; j <= n; j++){if (j != i){for (l = 0,s=0;s<k, l < k; l++){if (str[i][s] == str[j][l]){if (l == 0)ss = 0;elsess = l;while (str[i][s]==str[j][l]&&s<k){s++;if (l == k - 1){l = 0;}elsel++;}if (s == k){break;}else{s = 0;l = ss;ss = -1;}}}if (ss == -1){cout << -1 << endl;return 0;}ans += ss;}}sum = min(sum, ans);ans = 0;}cout << sum << endl;}


0 0