Description
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substrings2, and the third requires too much memory if the input data contains the substrings3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?
Input
There are exactly 3 lines in the input data. The i-th line contains stringsi. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed105.
Output
Output one number — what is minimal length of the string, containing s1, s2 ands3 as substrings.
Sample Input
ab bc cd
4
abacaba abaaba x
11
题意:将3个字符串连接起来,重复的可以重叠不用计算,输出最短的长度
思路:首先我们可以想到KMP模式匹配,然后就是枚举排列,求出最短的长度
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100050;
char str[3][maxn];
int next[3][maxn], len[3];
void get_next(int x) {
int k = -1, j = 0;
next[x][0] = -1;
while (j < len[x]) {
if (k == -1 || str[x][k] == str[x][j]) {
++k;
++j;
next[x][j] = k;
}
else k = next[x][k];
}
}
int kmp(int x, int y) {
int j = 0, k = 0;
while (j < len[y] && k < len[x]) {
if (j == -1 || str[x][k] == str[y][j]) {
j++, k++;
}
else j = next[y][j];
}
return j;
}
int main() {
while (scanf("%s%s%s", str[0], str[1], str[2]) != EOF) {
len[0] = strlen(str[0]);
len[1] = strlen(str[1]);
len[2] = strlen(str[2]);
for (int i = 0; i < 3; i++)
get_next(i);
int ans = -10;
for (int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++) {
if (i == j)
continue;
for (int k = 0; k < 3; k++) {
if (k == j || k == i)
continue;
int z = kmp(i, j);
int tmp = z;
if (len[j] == z)
tmp += kmp(i, k);
else tmp += kmp(j, k);
ans = max(ans, tmp);
}
}
printf("%d\n", (len[0] + len[1] + len[2]) - ans);
}
return 0;
}