麦克有 n 个字符串 s1, s2, ..., sn 都只包含小写字母。一次操作可以删除 si, 的第一个字母并将它加到字符串的末尾。 举个例子,字符串 "coolmike" 经过一次操作后会变成 "oolmikec".
现在麦克想知道:最少多少次操作后可以把所有字符串变相同。
Input
第一行包含一个整数 n (1 ≤ n ≤ 50) — 字符串的数量。
之后 n 行,每行包含一个字符串。 第 i 行为字符串 si。每个字符串长度相等,并且长度不超过 50.
Output
输出将所有字符串变相同所需的最小步数。如果不存在合法方案,输出 - 1 。
Example
Input
4 xzzwo zwoxz zzwox xzzwo
Output
5
Input
2 molzv lzvmo
Output
2
Input
3 kc kc kc
Output
0
Input
3 aa aa ab
Output
-1
身为一只蒟蒻······这种程度的题都不会做,最终还是在题解的帮助下把程序写出来的。
这题的思路:
对于每个字符串,最多移动n次,所以我们可以把某一字符串作为主串扩大2倍,然后查找各个子串是否能与主串匹配。这里的匹配功能是利用C++的find()函数实现的。最后用min不断更新最小值即可。
find()函数:
- 返回str在字符串中第一次出现的位置(从index开始查找)。如果没找到则返回string::npos
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<functional>
#include<map>
using namespace std;
const int maxn = 1e5+10;
const double pi = 3.1415926;
typedef long long ll;
int n;
string s[100];
string a[100];
int main()
{
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> s[i];
a[i] = s[i] + s[i];
}
//cout << a[1];
int sum = 0;
int ans = maxn;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (a[j].find(s[i]) == string::npos) {//没找到子串
cout << -1 << endl;
return 0;
}
else {
sum += a[j].find(s[i]);//找到子串,就把第一个匹配的位置加进去
}
}
ans = min(ans, sum);
sum = 0;
}
cout << ans << endl;
return 0;
}