Find the Shortest Common Superstring
Problem Description
The shortest common superstring of 2 strings S
1 and S
2 is a string S with the minimum number of characters which contains both S
1 and S
2 as a sequence of consecutive characters. For instance, the shortest common superstring of “alba” and “bacau” is “albacau”.
Given two strings composed of lowercase English characters, find the length of their shortest common superstring.
Given two strings composed of lowercase English characters, find the length of their shortest common superstring.
Input
The first line of input contains an integer number T, representing the number of test cases to follow. Each test case consists of 2 lines. The first of these lines contains the string S
1 and the second line contains the string S
2. Both of these strings contain at least 1 and at most 1.000.000 characters.
Output
For each of the T test cases, in the order given in the input, print one line containing the length of the shortest common superstring.
Sample Input
2 alba bacau resita mures
Sample Output
7 8
题目大意:求两个字符串的最短公共父串的长度。
解题思路:分别将这两个字符串当做模式与目标,进行两次KMP匹配,用两个串的长度减去两次匹配的最大值。(另一种思路是串A和串B链接成AB与BA的形式,然后求出next数组种的最大值,再用两个字符串的总长度减去那个最大值,感觉这种方法应该没有问题,但是又好像不对。。话说这道题WA了不下30次,花了2个多小时。。)
代码如下:
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define EPS 1e-6
#define INF INT_MAX / 10
#define LL long long
#define MOD 100000000
#define PI acos(-1.0)
const int maxn = 1000015;
char s1[maxn],s2[maxn];
int next[maxn];
void get_next(char* s,int len)
{
memset(next,-1,sizeof(next));
next[1] = 0;
for(int i = 2,j = 0;i <= len;i++){
while(j > 0 && s[j + 1] != s[i])
j = next[j];
if(s[j + 1] == s[i])
j++;
next[i] = j;
}
}
int kmp(char* s,int lens,char* t,int lent)
{
get_next(s,lens);
int j = 0;
for(int i = 1;i <= lent;i++){
while(j > 0 && s[j + 1] != t[i])
j = next[j];
if(s[j + 1] == t[i])
j++;
if(j == lens)
break;
}
return j;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%s",s1 + 1);
scanf("%s",s2 + 1);
int l1 = strlen(s1 + 1);
int l2 = strlen(s2 + 1);
int ans = 0;
ans = std::max(kmp(s2,l2,s1,l1),kmp(s1,l1,s2,l2));
printf("%d\n",l1 + l2 - ans);
}
return 0;
}