#include <iostream>
#include <cstring>
using namespace std;
const int N = 5e4 + 9;
int extend[N], fail[N];
void get_fail(char x[], int m) {
fail[0] = m;
int j = 0;
while (j + 1 < m && x[j] == x[j + 1]) {
++j;
}
fail[1] = j;
int k = 1;
for (int i = 2; i < m; ++i) {
int p = fail[k] + k - 1;
int len = fail[i - k];
if (i + len < p + 1) {
fail[i] = len;
} else {
int j = max(0, p - i + 1);
while (i + j < m && x[i + j] == x[j]) {
++j;
}
fail[i] = j;
k = i;
}
}
}
void get_extend(char x[], int m, char y[], int n) {
get_fail(x, m);
int j = 0;
while (j < n && j < m && x[j] == y[j]) {
++j;
}
extend[0] = j;
int k = 0;
for (int i = 1; i < n; ++i) {
int p = extend[k] + k - 1;
int len = fail[i - k];
if (i + len < p + 1) {
extend[i] = len;
} else {
j = max(0, p - i + 1);
while (i + j < n && j < m && y[i + j] == x[j]) {
++j;
}
extend[i] = j;
k = i;
}
}
}
char a[N], b[N];
int main() {
int n, m, ma = -1;
cin >> a >> b;
get_extend(a, n = strlen(a), b, m = strlen(b));
for (int i = 0; i < m; ++i) {
if (i + extend[i] == m) {
ma = max(ma, extend[i]);
}
}
for (int i = 0; i < ma; ++i) {
cout << a[i];
}
if (ma == -1) {
cout << 0 << endl;
} else {
cout << ' ' << ma << endl;
}
return 0;
}
计蒜客习题:首尾相接
最新推荐文章于 2022-01-26 21:45:25 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)