题意:找到一个字符串的最长的子串满足同时为该串的前缀,中缀和后缀。
按逆拓扑序更新每个状态最左出现和最右出现的位置和出现的次数,满足r[s] == len && l[s] - val[s] == 0 && num[s] > 2的所有状态中最长的为我们要的解。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define lng long long
using namespace std;
const int maxn = 2000000 + 10;
char str[maxn / 2];
int len;
struct suffix_automaton
{
int ch[maxn][26], pre[maxn], val[maxn];
int l[maxn], r[maxn], num[maxn], c[maxn / 2], top[maxn];
int sz, last;
void init()
{
pre[0] = -1; last = 0; sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(num, 0, sizeof(num));
}
void insert(int x)
{
int p = last, np = sz++;
last = np;
memset(ch[np], 0, sizeof(ch[np]));
val[np] = val[p] + 1;
while(p != -1 && ch[p][x] == 0)
{
ch[p][x] = np;
p = pre[p];
}
if(p == -1) pre[np] = 0;
else
{
int q = ch[p][x];
if(val[q] == val[p] + 1) pre[np] = q;
else
{
int nq = sz++;
memcpy(ch[nq], ch[q], sizeof(ch[q]));
val[nq] = val[p] + 1;
pre[nq] = pre[q];
pre[q] = pre[np] = nq;
while(p != -1 && ch[p][x] == q) { ch[p][x] = nq; p = pre[p]; }
}
}
}
void solve()
{
memset(c, 0, sizeof(c));
for(int i = 0; i < sz; ++i) c[val[i]] += 1;
for(int i = 1; i <= len; ++i) c[i] += c[i - 1];
for(int i = 0; i < sz; ++i) top[--c[val[i]]] = i;
for(int i = 0; i < sz; ++i) { l[i] = len + 1; r[i] = 0; }
for(int i = 0; ; i = ch[i][str[val[i]] - 'a'])
{
l[i] = r[i] = val[i];
num[i] = 1;
if(val[i] == len) break;
}
for(int i = sz - 1; i > 0; --i)
{
int u = top[i];
l[pre[u]] = min(l[pre[u]], l[u]);
r[pre[u]] = max(r[pre[u]], r[u]);
num[pre[u]] += num[u];
}
int ans = 0;
for(int i = 1; i < sz; ++i)
if(num[i] > 2 && r[i] == len)
if(l[i] - val[i] == 0) ans = max(ans, val[i]);
if(ans != 0)
for(int i = len - ans; i < len; ++i)
printf("%c", str[i]);
else printf("Just a legend");
printf("\n");
}
}sam;
int main()
{
freopen("in.txt", "r", stdin);
scanf("%s", str); len = strlen(str); sam.init();
for(int i = 0; i < len; ++i) { sam.insert(str[i] - 'a'); }
sam.solve();
return 0;
}