# hdu 1867 A + B for you again【KMP】【判断前后缀】

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

abcd   bcd

aaa b

abcd bc

abcd

aaab

abcd bc

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 100010;
#define inf 0x3f3f3f3f
char str1[maxn],str2[maxn];
int next1[maxn],next2[maxn];
int l1,l2;
void get_next(int *next,char s[])
{
int i,j;
next[0] = j = -1;
i = 0;
while(s[i]!='\0')
{
while(j!=-1&&s[i]!=s[j])
j = next[j];
next[++i] = ++j;
}
return;
}

int KMP(char *s1,char *s2,int length,int *next)
{
int i,j;
i = j = 0;
while(s1[i]!='\0')
{
while(j!=-1&&s1[i]!=s2[j])
j = next[j];
i++;
j++;
if(s1[i]=='\0')
return j;

}
return 0;
}

int main()
{
int dis1,dis2;
//	freopen("in.txt","r",stdin);
while(scanf("%s%s",str1,str2)!=EOF)
{
memset(next1,0,sizeof(next1));
memset(next2,0,sizeof(next2));
l1 = strlen(str1);
l2 = strlen(str2);
get_next(next1,str1);
get_next(next2,str2);
dis1 = KMP(str1,str2,l2,next2);
dis2 = KMP(str2,str1,l1,next1);
if(dis1 > dis2||(dis1==dis2&&strcmp(str1,str2)<0))
{
printf("%s%s\n",str1,str2+dis1);
}
else if(dis1 < dis2||(dis1==dis2&&strcmp(str1,str2)>=0))
printf("%s%s\n",str2,str1+dis2);
}
return 0;
}

• 评论

• 上一篇
• 下一篇