首页 > 其他 > 详细

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

时间:2019-08-19 12:34:59      阅读:87      评论:0      收藏:0      [点我收藏+]

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 10^5 and won’t be empty.

Output

Print the ultimate string by the book.

Sample Input

asdf sdfg
asdf ghjk

Sample Output

asdfg
asdfghjk

题目大意:
A+B,指的是 A的字符串 B的字符串;
例如:AAA: asdf;  BBB: sdfg;

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

但是如果是 Aabcda ;B: bcdef;
因为 A的最大后缀与 B 的最大前缀不相同;所以最终结果为 abcdabcdef
也就是说求出 A前缀和 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;
}

 

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

原文:https://www.cnblogs.com/dwj-2019/p/11375665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!