题目连接
http://acm.hdu.edu.cn/showproblem.php?pid=1867
A + B for you again
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。。。
注意: 字符串A+B也可是B+A反正输出相加之后最短的那个,若相加之后长度相等输出字典序最小的那个。。
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<map>
using std::cin;
using std::cout;
using std::endl;
using std::find;
using std::sort;
using std::map;
using std::pair;
using std::vector;
using std::multimap;
#define pb(e) push_back(e)
#define sz(c) (int)(c).size()
#define mp(a, b) make_pair(a, b)
#define all(c) (c).begin(), (c).end()
#define iter(c) decltype((c).begin())
#define cls(arr,val) memset(arr,val,sizeof(arr))
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i)
const int N = ;
typedef unsigned long long ull;
int next[N];
char str1[N], str2[N];
struct KMP {
int i, j, n, m;
inline void get_next(char *src) {
m = strlen(src);
for (i = , j = next[] = ; i < m; i++) {
while (j > && src[i] != src[j]) j = next[j - ];
if (src[i] == src[j]) j++;
next[i] = j;
}
}
inline int kmp_match(char *text, char *pat) {
n = strlen(text);
for (i = j = ; i < n; i++) {
while (j > && text[i] != pat[j]) j = next[j - ];
if (text[i] == pat[j]) j++;
}
return j;
}
}go;
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int p, q;
while (~scanf("%s %s", str1, str2)) {
go.get_next(str2);
p = go.kmp_match(str1, str2);
go.get_next(str1);
q = go.kmp_match(str2, str1);
if (p > q || (p == q && - == strcmp(str1, str2))) {
printf("%s%s\n", str1, str2 + p);
} else {
printf("%s%s\n", str2, str1 + q);
}
}
return ;
}