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;
}