题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1867
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

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

Problem solving report:

Description: 求最长相同的串A后串和串B的前串(或者是最长相同的串B后串和串A的前串),然后进行合并,得到长度最短的A+B,且字典序最小。
Problem solving: KMP的运用,利用KMP求出最长相同的串A缀串和串B的缀串和最长相同的串B后缀和串A的前缀,然后按较长的前缀进行输出(越长消的越多)。

Accepted Code:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int nex[MAXN];
char sa[MAXN], sb[MAXN];
void Next(char str[], int len) {
    nex[0] = -1;
    int i = 0, j = -1;
    while (i < len) {
        if (~j && str[i] != str[j])
            j = nex[j];
        else nex[++i] = ++j;
    }
} 
int KMP(char sa[], char sb[], int la, int lb) {
    Next(sb, lb);
    int i = 0, j = 0;
    while (i < la) {
        if (~j && sa[i] != sb[j])
            j = nex[j];
        else i++, j++;
    }
    return j;
}
int main() {
    int la, lb, len1, len2;
    while (~scanf("%s%s", sa, sb)) {
        la = strlen(sa);
        lb = strlen(sb);
        len1 = KMP(sa, sb, la, lb);
        len2 = KMP(sb, sa, lb, la);
        if (len1 > len2)
            printf("%s%s\n", sa, sb + len1);
        else if (len1 < len2)
            printf("%s%s\n", sb, sa + len2);
        else {
            if (strcmp(sa, sb) < 0)
                printf("%s%s\n", sa, sb + len1);
            else printf("%s%s\n", sb, sa + len2);
        }
    }
    return 0;
}