题目链接:点击打开链接
思路:KMP水题。
// HDU 1876 A + B for you again 运行/限制:46ms/1000ms
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
char s[100005], p[100005];
int Next[100005];
void getNext(char s[], int n) {
int i, j;
i = -1;
j = 0;
Next[0] = -1;
while (j < n) {
if (i == -1 || s[i] == s[j]) {
i++;
j++;
if (s[j] == s[i]) {
Next[j] = Next[i];
}
else {
Next[j] = i;
}
}
else {
i = Next[i];
}
}
}
int kmp(char s[], char p[], int n, int m) {
int i, j;
i = j = 0;
getNext(s, n);
while (j < m) {
if (i == -1 || s[i] == p[j]) {
i++;
j++;
}
else {
i = Next[i];
}
}
return i;
}
int main(){
int n, m, x, y;
while (scanf("%s%s", s, p) != EOF) {
n = strlen(s);
m = strlen(p);
x = kmp(s, p, n, m);
y = kmp(p, s, m, n);
if (x > y || (x == y && strcmp(p, s) < 0)) {
printf("%s%s\n", p, s + x);
}
else {
printf("%s%s\n", s, p + y);
}
}
return 0;
}