题意:求一个字符串有多少个不同的子串满足出现了至少两次,且没有重叠。
去年作的时候用后缀数组过的,现在写了个后缀自动机。因为一个很脑残的bug(忘了按拓扑序递推)调了两个小时。不过也有收获,在纸上画了10多次建自动机过程之后理解的更清晰了。
做法是维护每个状态的最左出现的位置和最右出现的位置(逆拓扑序递推),如果这两个位置之间能放下某些该状态表示的字符串,这些子串加入我们的解中。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define lng long long
using namespace std;
const int maxn = 5000 + 10;
char s[maxn];
int str[maxn], len;
struct suffixautomaton
{
int ch[maxn][30], pre[maxn], val[maxn], top[maxn];
int c[maxn];
int l[maxn], r[maxn];
int sz, last;
void init() { pre[0] = -1; last = 0; sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
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] = -1; }
for(int i = 0; ; i = ch[i][str[val[i]]])
{
l[i] = r[i] = val[i];
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]);
}
lng ans = 0;
for(int i = 0; i < sz; ++i)
{
if(r[i] - l[i] > val[pre[i]])
{
lng tmp = min(val[i], r[i] - l[i]);
ans += (tmp - val[pre[i]]);
}
}
printf("%I64d\n", ans);
}
}sam;
int main()
{
freopen("in.txt", "r", stdin);
while(~scanf("%s", s) && s[0] != '#')
{
len = strlen(s);
sam.init();
for(int i = 0; s[i]; ++i)
{
str[i] = s[i] - 'a';
sam.insert(str[i]);
}
sam.solve();
}
return 0;
}