HDU 1867 A+B for you again(简单kmp)

本文介绍了一个关于字符串处理的问题,即如何根据特定规则合并两个字符串。文章详细解释了问题背景及输入输出要求,并提供了一段C++代码实现,通过构建临时字符串并使用后缀数组的方法来确定合并后的最短字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8938    Accepted Submission(s): 2166


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
 

Author
Wang Ye
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1711  1866  1277  1865  1869 
 
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string>
#include<cmath>
using namespace std;
typedef long long LL;
#define maxn (100001*2)
int Next[maxn];
/*
题意很简单,
几个点就是如何判断字典序,
还有就是截取的问题,,,

这题该打::;我竟然忽略了最大前缀后缀可以覆盖其中一个串的情况,
处理方法是在中间添加一个分割符,,就可以了
*/
void getNext(string t)
{
    int k=-1,sz=t.size();
    Next[0]=-1;
    for(int i=1;i<sz;i++)
    {
        while(k>-1&&t[k+1]!=t[i])
            k=Next[k];
        if(t[k+1]==t[i])
            k++;
        Next[i]=k;//i-k
    }
}
int main()
{
    ios::sync_with_stdio(false);
    string s1,s2;
    while(cin>>s1>>s2)
    {
        string tmp1=s2+"#"+s1,tmp2=s1+"#"+s2;
        int len=tmp1.size();
        getNext(tmp1);
        int re1=Next[len-1]+1;
        getNext(tmp2);
        int re2=Next[len-1]+1;
        tmp1=s1+s2.substr(re1,s2.size()-re1);
        tmp2=s2+s1.substr(re2,s1.size()-re2);
        if(re1>re2)  cout<<tmp1;
        else if(re2>re1) cout<<tmp2;
        else
        {
            if(tmp1<tmp2) cout<<tmp1;
            else cout<<tmp2;
        }
        cout<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值