hdu1841 Find the Shortest Common Superstring 两遍KMP

hdu1841 Find the Shortest Common Superstring 两遍KMP

关于KMP 可以看我另一篇文章:
传送门

问题描述 :

The shortest common superstring of 2 strings S1 and S2 is a string S with the minimum number of characters which contains both S1 and S2 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.

输入:

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 S1 and the second line contains the string S2. Both of these strings contain at least 1 and at most 1.000.000 characters.

输出:

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.
样例输入:

2
alba
bacau
resita
mures
样例输出:
7
8

题目大意:给你一个s1,s2,求出一个串 s’ ,s’是s1s2的子串,求s’的最短长度。

可以用kmp来写,我们知道kmp中的j的值表当前的最大前缀,我们对s1s2跑两次KMP 让 KMP 返回 s1的最大前缀,s2的最大后缀。注意一点的是,如果 s1串包含s2串或者 s2串包含s1串,这种情况需要特判 输出 s1 s2 中 最大串的长度即可。 重点理解 “两次kmp,每次调用kmp算法返回的都是串s1的最大后缀和s2的最大前缀”。!

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define CLR(a,b) memset(a,(b),sizeof a)
using namespace std;
const int maxx = 1e6+5;
int nex[maxx];
void getNex(char *b){
    int len = strlen(b+1);
    CLR(nex, 0);
    int j = 0;
    for(int i = 2 ;i <= len ;i++){
        while(j&&b[j+1]!=b[i]) j = nex[j];
        if(b[j+1]==b[i]) j++;
        nex[i] = j;
    }

}

int KMP(char *a,char *b){
    int l1 = strlen(a+1),l2 = strlen(b+1);
    getNex(b);
    int j = 0;
    for(int i = 1; i <= l1;i++){
        while(j&&b[j+1]!=a[i]) j = nex[j];
        if(b[j+1]==a[i]) j++;
        if(j==l2)
            return -1;
    }
    return j;

}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        char s1[maxx],s2[maxx];
        scanf("%s%s",s1+1,s2+1);
        int r = KMP(s1,s2);
        int l = KMP(s2,s1);
        if(r==-1||l==-1)
            cout << max(strlen(s1+1),strlen(s2+1))<<endl;
        else
            cout << strlen(s1+1)+strlen(s2+1)-max(r,l)<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值