A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4723 Accepted Submission(s): 1211
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
#include <cstdio>
#include <cstring>
int next[100010];
void getnext(char *s1){
int j=0,k=-1;
int len =strlen(s1);
next[0]=-1;
while(j<len){
if(k==-1 || s1[j]==s1[k]){
++j;
++k;
next[j]=k;
}
else k=next[k];
}
return ;
}
int kmp(char *s1,char *s2){
int len=strlen(s2);
getnext(s1);
int i=0,j=0;
while(i<len){
if(j==-1 || s1[j]==s2[i]){
++i;
++j;
}
else j=next[j];
}
return j;//代表子串中最大有前j个字符在母串中有匹配的。
}
int main (){
char s1[100010],s2[100010];
while(scanf("%s%s",s1,s2)!=EOF){
int l1=kmp(s1,s2);
int l2=kmp(s2,s1);
//printf("%d %d\n",l1,l2);
if(l1==l2){
if(strcmp(s1,s2)<0)
printf("%s%s\n",s1,s2+l1);
else
printf("%s%s\n",s2,s1+l1);
}
if(l1<l2)
printf("%s%s\n",s1,s2+l2);
if(l1>l2)
printf("%s%s\n",s2,s1+l1);
}
return 0;
}