A + B for you again HDU - 1867(最大前缀&最大后缀的公共子缀&kmp删除法)

Problem Description

Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.

Input

For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 1 0 5 10^{5} 105 and won’t be empty.

Output

Print the ultimate string by the book.

Sample Input

asdf sdfg
asdf ghjk

Sample Output

a s d f g {\color{Magenta} asdfg} asdfg
a s d f g h j k {\color{Magenta} asdfghjk} asdfghjk

题目大意:
A + B A+B A+B,指的是 A A A 的字符串 B B B 的字符串;
例如: A A A: a s d f asdf asdf;   B B B: s d f g sdfg sdfg;

因为 a s d f asdf asdf s d f g sdfg sdfg 中有相同最大后缀,和最大前缀 s d f sdf sdf ;所以最终结果为 a s d f g asdfg asdfg

但是如果是 A A A: a b c d a abcda abcda ;  B B B: b c d e f bcdef bcdef;
因为 A A A 的最大后缀与 B B B 的最大前缀不相同;所以最终结果为 a b c d a b c d e f abcdabcdef abcdabcdef
也就是说求出 A A A 前缀和 B B B 后缀的最大公共子缀,即可;可用 kmp 算法;

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxx=100100;
int p[maxx];
char a[maxx],b[maxx];
void pre(char b[])
{
    int m=strlen(b);
    int i=1,j=0;
    p[0]=-1;
    while(i<m)
    {
        if(j==-1||b[i]==b[j])
        {
            i++,j++;
            p[i]=j;
        }
        else
            j=p[j];
    }
}
int kmp(char a[],char b[])
{
    int n=strlen(a);
    int m=strlen(b);
    pre(b);
    int i=0,j=0;
    while(i<n&&j<m)
    {
        if(j==-1||a[i]==b[j])
        {
            i++,j++;
        }
        else j=p[j];
    }
    if(i==n)
        return j;
    else
        return 0;
}
int main()
{
    while(~scanf("%s%s",a,b))
    {
        int x=kmp(a,b);
        int y=kmp(b,a);
        if(x==y)
        {
            if(strcmp(a,b)>0)
            {
                printf("%s",b);
                printf("%s",a+x);
            }
            else
            {
                printf("%s",a);
                printf("%s",b+x);
            }
        }
        else if(x>y)
        {
            printf("%s",a);
            printf("%s",b+x);
        }
        else
        {
            printf("%s",b);
            printf("%s",a+y);
        }
        printf("\n");
    }
    return 0;
}

实践是检验真理的唯一标准

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值