CodeForces 25E Test KMP

时间:2022-10-31 03:11:39

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 substring s2, and the third requires too much memory if the input data contains the substring s3. 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 string si. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105.

Output

Output one number — what is minimal length of the string, containing s1s2 and s3 as substrings.

Sample Input

Input
ab
bc
cd
Output
4
Input
abacaba
abaaba
x
Output
11

利用kmp匹配算法,在kmp匹配算法稍加修改就ok,因为这里可以只匹配一部分前缀,不用完全匹配。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std; char str[1100000];
char s0[1100000],s1[1100000],s2[1100000];
int next[1100000];
void getnextval(char *p)//求一个字符串的next数组,结果保存在全局变量next[]中。
{
int plen=strlen(p);
next[0]=-1;
int k=-1;
int j=0;
while (j<plen-1)
{
if (k==-1||p[k]==p[j])
{
j++;
k++;
if (p[j]!=p[k])
next[j]=k;
else
next[j]=next[k];
}
else
{
k=next[k];
}
}
} int kmp(char *s,char *p)//以s为匹配串,p为模式串进行匹配,返回匹配后p剩下的字符个数。
{
int l;
int i=0;
int j=0;
int slen=strlen(s);
int plen=strlen(p);
getnextval(p);
while (i<slen&&j<plen)
{
if (j==-1||s[i]==p[j])
{
i++;
j++;
}
else
j=next[j];
}
if (j==plen)//完全匹配的情况,一个字符也不剩,放回0。
l=0;
else if (i==slen) //匹配一部分,也就是p的一个前缀和s的一个后缀完全匹配。
l=plen-j; else
l=plen-(slen-i)-1; return l;
} int cat(char *a,char *b,char *c) //假设a串在最前,b串在中间,c串在最后至少需要多长。
{
str[0]='\0';
int la=strlen(a);
int lb=strlen(b);
int lc=strlen(c);
int len=kmp(a,b);
strcat(str,a);
strcat(str,b+lb-len);
len=kmp(str,c);
return strlen(str)+len;
} int main()
{
while (scanf("%s%s%s",s0,s1,s2)!=EOF)
{
int minn;
int l;
//一下分6种情况讨论。
minn=cat(s0,s1,s2); l=cat(s0,s2,s1);
if (l<minn)
minn=l; l=cat(s1,s2,s0);
if (l<minn)
minn=l; l=cat(s1,s0,s2);
if (l<minn)
minn=l; l=cat(s2,s0,s1);
if (l<minn)
minn=l; l=cat(s2,s1,s0);
if (l<minn)
minn=l; cout <<minn<<endl;
}
return 0;
}

  对于kmp的学习推荐博客:http://blog.csdn.net/v_july_v/article/details/7041827,讲的很好。