A + B for you again
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
分析:题目要求:1、求和字符串最短;2、字典序最小;
由题,串一的最长的后缀匹配串二的最长前缀或整个串二,这两个串可以交换位置; 比如 abc abc = abc 、 aaaa aa =aaaa 、abcd cd = abcd 、abcd cb= abcdcb
用kmp算法求解,分别以串1为模式串、串2为文本串 ;串1 为文本串、串2为模式串;找到两字符的最长匹配。
AC代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+10;
char s1[maxn],s2[maxn];
int next[maxn];
void get_next(char* s){
int len=strlen(s);
next[0]=0;
int k=0;
for(int p=1;p<len;p++){
while(k>0 && s[p]!=s[k]){
k=next[k-1];
}
if(s[k]==s[p]) k++;
next[p]=k;
}
}
int KMP(char* s1,char *s2){//模式串、文本串
get_next(s1);
int l1=strlen(s1);
int l2=strlen(s2);
int i=0,j=0;
while(i<l1 && j<l2){
if(s1[i]==s2[j]) {
i++;j++;
}
else if(i==0) j++;
else i=next[i-1];
}
if(j==l2&&i==l1 || i<l1)return i;
return 0;
}
int main(){
while(scanf("%s%s",s1,s2)==2){
int la=KMP(s1,s2); //s1做模式串、s2做文本串
int lb=KMP(s2,s1);
if(la>lb || (la==lb && strcmp(s2,s1)<0)){
printf("%s",s2);
strcpy(s2,s1+la);
printf("%s\n",s2);
}
else {
printf("%s",s1);
strcpy(s1,s2+lb);
printf("%s\n",s1);
}
}
return 0;
}