HDU1867 A + B for you again KMP应用

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 <cstdio>#include <cstring>const int maxn = 100010;int next[maxn];char s1[maxn],s2[maxn];int len1,len2;void get_next(char *a){int len = strlen(a);int k = -1;int j = 0;next[j] = k;while(a[j] != ‘\0’) {if(k == -1 || a[j] == a[k]) {k++;j++;next[j] = k;}else k = next[k];}}int kmp(char *a,char *b){ //a主串 b模式串get_next(b);int i = 0,j = 0;while(a[i] != ‘\0’) {if(j == -1 || a[i] == b[j]) {i++;j++;}else j = next[j];}return j;}int main(){while(scanf(“%s%s”,s1,s2) != EOF) {len1 = strlen(s1);len2 = strlen(s2);int str1 = kmp(s1,s2);int str2 = kmp(s2,s1);if(str1 == str2) {if(strcmp(s1,s2) < 0) printf(“%s%s\n”,s1,s2+str1);\n”,s2,s1+str1);}else if(str1 < str2) {printf(“%s%s\n”,s2,s1+str2);}\n”,s1,s2+str1);}return 0;}

自信是一个人的胆,有了这个胆,你就会所向披靡!

HDU1867 A + B for you again KMP应用

相关文章:

你感兴趣的文章:

标签云: