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?
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.
Print the minimal number of moves Mike needs in order to make all the strings equal or print - 1 if there is no solution.
4 xzzwo zwoxz zzwox xzzwo
5
2 molzv lzvmo
2
3 kc kc kc
0
3 aa aa ab
-1
In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
题意:给个 n 个串,每次我们能将一个串的第一个字符移到该串末尾,问我们至少要移动多少次,才能使所有串相同。
思路:
如图所示,我们只需找到所有串的最长连续公共子串,将串左边的移到右边即可,一开始用 DP 的方法敲了很久,发现自己实现不了,就找了波题解,题解用 C++自带 find ( ) 函数做的,真是长姿势了!
#include<bits/stdc++.h>
using namespace std;
const int N = 100 + 10;
string a[N];
int main()
{
int n;
while(scanf("%d", &n) == 1)
{
for(int i = 0; i < n; i++)
cin >> a[i];
int ans = 0x3f3f3f, flag = 0;
for(int i = 0; i < n; i++)
{
int sum = 0;
for(int j = 0; j < n; j++)
{
string tmp = a[j] + a[j];
if(tmp.find(a[i]) == string::npos) flag = 1;
else sum += tmp.find(a[i]) ;
}
ans = min(ans, sum);
}
printf("%d\n", flag ? -1 : ans);
}
}