您的位置:首页 > 其它

Find the Shortest Common Superstring(hdu1841,KMP)

2013-08-23 17:24 573 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1841

解析:

题意:

找到一个最短的串s,含有子串s1,s2

思路:两次KMP匹配

求出,s1后缀和s2前缀的最长公共串长度m1,

s2后缀和s1前缀的最长公共串长度m2;

ans=strlen(s1)+strlen(s2)-max(m1,m2);

6096 KB 359 ms C++ 956 B

*/

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn=1000000+10;
char s1[maxn],s2[maxn];
int next[maxn];
int max(int a,int b)
{
return a>b? a:b;
}
void get_next(char s[])
{
next[0]=-1;
int j=-1;
int i=0;
while(s[i]!='\0')
{
if(j==-1||s[i]==s[j])//这里要注意一下
{  i++;
j++;
if(s[i]!=s[j])next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
}
int KMP(char a[],char b[],int m1,int m2)
{
int j=0,i=0;
get_next(a);
while(i<m2&&j<m1)
{
if(j==-1||a[j]==b[i])
{
i++;
j++;
}
else
j=next[j];
if(j==m1)
return j;
}
return j;
}
int main()
{
int n,i,j;
int len1,len2,ans;
scanf("%d",&n);
while(n--)
{
scanf("%s",s1);
scanf("%s",s2);
int t1,t2;
len1=strlen(s1);
len2=strlen(s2);
t1=KMP(s1,s2,len1,len2);
t2=KMP(s2,s1,len2,len1);
ans=len1+len2-max(t1,t2);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: