A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9031 Accepted Submission(s): 2184
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
解题思路
题目大概就是说两个串,放在一起,如过一个串的前缀和另一个串的后缀相同,那么就可以重叠,先后顺序可以随意。
输出放在一起后最短的串,如果长度相同就输出字典序最小的串。
大概就是一个kmp模板题,找到公共前后缀的最大长度。
程序代码
#include <stdio.h>
#include <string.h>
int next[100010];
char p[100010];
char s[100010];
char s0[200010];
char s1[200010];
void get_next(char p[]){
int j=0;
int k=-1;
int l=strlen(p);
next[0]=-1;
while(j<l){
if(p[j]==p[k]||k==-1){
j++;
k++;
next[j]=k;
}
else
k=next[k];
}
return ;
}
int kmp(char s[],char p[]){
memset(next,0,sizeof(next));
get_next(p);
int i=0;
int j=0;
int l1=strlen(s);
int l2=strlen(p);
while(i<l1){
if(p[j]==s[i]||j==-1){
i++;
j++;
}
else
j=next[j];
}
return j;
}
int main()
{
int i,k1,k2;
while(scanf("%s%s",s,p)!=EOF){
k1=kmp(s,p);
k2=kmp(p,s);
if(k1>k2){
printf("%s%s\n",s,p+k1);
}
else if(k1<k2){
printf("%s%s\n",p,s+k2);
}
else{ //k1==k2 两串先后位置合并后长度相同
strcpy(s0,s);
strcat(s0,p+k1);
strcpy(s1,p);
strcat(s1,s+k1);
if(strcmp(s0,s1)>0)
printf("%s\n",s1);
else
printf("%s\n",s0);
}
memset(s,0,sizeof(s));
memset(p,0,sizeof(p));
memset(s0,0,sizeof(s0));
memset(s1,0,sizeof(s1));
}
return 0;
}