考虑建立 广义 SAM, 然后看节点 是否满足 :
如果满足, 可以考虑 : , 然后直接对其 取 即可。
时间复杂度 :
CODE :
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int ans = N;
struct SAM {
char s[N];
int n, tot = 1, lst = 1, cnt = 0;
int fa[N], ll[N], ch[N][27], siz[N][2], hd[N];
inline void insert (int pos, char c, int MODE) {
int v = lst, u = ++ tot, x = v, y, idx = c - 'a';
lst = u, siz[u][MODE] = 1, ll[u] = pos;
for ( ; x && ! ch[x][idx]; x = fa[x]) ch[x][idx] = u;
y = ch[x][idx];
if (! x) {
fa[u] = 1; return ;
}
else if (ll[y] == ll[x] + 1) { fa[u] = y; return ; }
else {
int p = ++ tot;
ll[p] = ll[x] + 1, fa[p] = fa[y], fa[u] = fa[y] = p;
for (int i = 0; i < 26; i ++) ch[p][i] = ch[y][i];
for ( ; x && ch[x][idx] == y; x = fa[x]) ch[x][idx] = p;
}
return ;
}
struct EDGE {
int v, nxt;
} e[N * 2];
inline void link_edge (int u, int v) { e[++ cnt] = {v, hd[u]}, hd[u] = cnt; }
inline void init () {
n = 0, tot = 1, lst = 1, cnt = 0;
memset(ch, 0, sizeof(ch)), memset(ll, 0, sizeof(ll));
memset(fa, 0, sizeof(fa)), memset(hd, 0, sizeof(hd));
memset(siz, 0, sizeof(siz));
}
inline void build_sam () {
init();
scanf("%s", s + 1), n = strlen(s + 1);
for (int i = 1; i <= n; i ++) insert(i, s[i], 0);
scanf("%s", s + 1), n = strlen(s + 1), lst = 1;
for (int i = 1; i <= n; i ++) insert(i, s[i], 1);
for (int i = 2; i <= tot; i ++) link_edge(fa[i], i);
}
inline void dfs (int u) {
for (int i = hd[u]; i; i = e[i].nxt) {
dfs(e[i].v);
siz[u][0] += siz[e[i].v][0], siz[u][1] += siz[e[i].v][1];
}
if (siz[u][1] == 1 && siz[u][0] == 1 && fa[u] != 0) ans = min(ans, (ll[fa[u]] + 1));
return ;
}
} sam;
int main() {
sam.build_sam(), sam.dfs(1);
if (ans == N) cout << -1;
else cout << ans;
return 0;
}