Find the Shortest Common Superstring(hdu1841,KMP)

73 篇文章 0 订阅
18 篇文章 0 订阅

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值