A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3073 Accepted Submission(s): 758
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
code:
#include<iostream>
#include<cstring>
using namespace std;
char S[100005],T[100005];
int next[100005];
void get_next(char *t)
{
int i=0,j=-1;
next[0]=-1;
int Lt=strlen(t);
while(i<Lt)
{
if(j==-1||t[i]==t[j])
{
++i,++j;
next[i]=j;
}
else
j=next[j];
}
}
int kmp(char *s,char *t)
{
int lens=strlen(s);
int lent=strlen(t);
int i=0,j=0;
get_next(t);
while(i<lens&&j<lent)
{
if(j==-1||s[i]==t[j])
{
++i,++j;
}
else
j=next[j];
}
if(j<lent||j==lent&&i==lens)
return j;//匹配串的位置 J
return -1;
}
int main()
{
while(cin>>S>>T)
{
int lena=kmp(S,T);
int lenb=kmp(T,S);
int lT=strlen(T);
int lS=strlen(S);
if(lena>lenb||lena==lenb&&strcmp(S,T)<0)
{
cout<<S;
for(int i=lena;i<lT;i++)
{
cout<<T[i];
}
cout<<endl;
}
else
{
cout<<T;
for(int i=lenb;i<lS;i++)
{
cout<<S[i];
}
cout<<endl;
}
}
return 0;
}