81 lines
2.3 KiB
C++
81 lines
2.3 KiB
C++
#include <algorithm>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#include <iostream>
|
|
#include <queue>
|
|
using namespace std;
|
|
typedef long long LL;
|
|
typedef long double LDB;
|
|
const int kMaxN = 4e3 + 10;
|
|
struct Point {
|
|
int a, b, c;
|
|
};
|
|
int ch[2][2][kMaxN][26], fa[2][kMaxN], len[2][kMaxN];
|
|
bool vis[kMaxN][kMaxN];
|
|
int tot[2] = {1, 1}, last[2] = {1, 1};
|
|
char A[kMaxN], B[kMaxN];
|
|
void InitSequenceMachine(char *s, int flag) {
|
|
for (int i = strlen(s + 1); i; --i) {
|
|
memcpy(ch[flag][0][i - 1], ch[flag][0][i], 104);
|
|
ch[flag][0][i - 1][s[i] - 'a'] = i;
|
|
}
|
|
}
|
|
void AddChar(int character, int string_flag) {
|
|
int p = last[string_flag], np = last[string_flag] = ++tot[string_flag];
|
|
len[string_flag][np] = len[string_flag][p] + 1;
|
|
for (; p && !ch[string_flag][1][p][character]; p = fa[string_flag][p])
|
|
ch[string_flag][1][p][character] = np;
|
|
if (!p)
|
|
fa[string_flag][np] = 1;
|
|
else {
|
|
int q = ch[string_flag][1][p][character];
|
|
if (len[string_flag][q] == len[string_flag][p] + 1)
|
|
fa[string_flag][np] = q;
|
|
else {
|
|
int nq = ++tot[string_flag];
|
|
len[string_flag][nq] = len[string_flag][p] + 1;
|
|
fa[string_flag][nq] = fa[string_flag][q];
|
|
fa[string_flag][q] = fa[string_flag][np] = nq;
|
|
memcpy(ch[string_flag][1][nq], ch[string_flag][1][q], 104);
|
|
for (; p && ch[string_flag][1][p][character] == q; p = fa[string_flag][p])
|
|
ch[string_flag][1][p][character] = nq;
|
|
}
|
|
}
|
|
}
|
|
void Solve(int flag1, int flag2) {
|
|
memset(vis, 0, sizeof(vis));
|
|
queue<Point> q;
|
|
q.push((Point){flag1, flag2, 0});
|
|
vis[flag1][flag2] = 1;
|
|
while (!q.empty()) {
|
|
Point now = q.front();
|
|
q.pop();
|
|
for (int i = 0; i < 26; ++i)
|
|
if (ch[0][flag1][now.a][i]) {
|
|
if (ch[1][flag2][now.b][i]) {
|
|
int a = ch[0][flag1][now.a][i], b = ch[1][flag2][now.b][i];
|
|
if (!vis[a][b]) vis[a][b] = 1, q.push((Point){a, b, now.c + 1});
|
|
} else {
|
|
printf("%d\n", now.c + 1);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
printf("-1\n");
|
|
}
|
|
int main() {
|
|
#ifdef local
|
|
freopen("pro.in", "r", stdin);
|
|
#endif
|
|
scanf("%s", A + 1);
|
|
scanf("%s", B + 1);
|
|
InitSequenceMachine(A, 0);
|
|
InitSequenceMachine(B, 1);
|
|
for (char *p = A + 1; *p; p++) AddChar(*p - 'a', 0);
|
|
for (char *p = B + 1; *p; p++) AddChar(*p - 'a', 1);
|
|
Solve(1, 1);
|
|
Solve(1, 0);
|
|
Solve(0, 1);
|
|
Solve(0, 0);
|
|
return 0;
|
|
} |