A + B for you again
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.
asdf sdfg
asdf ghjk
asdfg
asdfghjk
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int Next[100100];
char s1[100100],s2[100100];
void getNext(char s[]){
int i,j;
i = -1;
j = 0;
memset(Next,0,sizeof(Next));//先初始化一下Next数组
Next[0] = -1;
int lens = strlen(s);
while(j < lens){
if(i==-1||s[i]==s[j]){
i++,j++;
if(s[i]==s[j]) Next[j] = Next[i];
else Next[j] = i;
}
else i = Next[i];
}
}
int Kmp(char s[],char m[]){//s是目标字符串,m是模板字符串
int i = 0,j = 0;
int lens = strlen(s);
getNext(m);
while(j < lens){
if(i==-1||m[i]==s[j]){
i++,j++;
}
else i = Next[i];
}
return i;//实际上这道题并不是让我们找目标字符串中是否含有模板串,而是在后缀中找到相匹配的,所以一路循环到最后得到的i就是相应的目标串中后缀和模板相匹配的长度
}
int main(){
while(~scanf("%s%s",s1,s2)){
//分别求两边,看谁当目标串的时候后缀能匹配的最长
int str1 = Kmp(s1,s2);//s1当目标,s2当模板
int str2 = Kmp(s2,s1);//s2当目标,s1当模板
if(str1==str2){//如果相同,那么按字典序顺序
if(strcmp(s1,s2)<0)printf("%s%s\n",s1,str1+s2);//s2字符串字典序大,先输出s1,然后从str1位置开始输出字符串s2,因为前面的是匹配的
else printf("%s%s\n",s2,str1+s1);//同理
}
else if(str1>str2){
printf("%s%s\n",s1,str1+s2);//s1后缀匹配的长,先输出s1,然后从s2的str1位置开始输出s2
}
else printf("%s%s\n",s2,str2+s1);//s2后缀匹配长,先输出s2,然后从s1的str2位置开始输出s1
}
return 0;
}