题意:求出一个字符串的所有不同子串出现的次数ni,求所有 ni * (ni + 1) / 2 的和。
对这个串建后缀自动机,拓扑排序之后通过pre指针更新出所有的状态所代表的子串在字符串中出现的次数。而每个状态所表示的不同子串的个数为val[s] - val[pre[s]]。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define lng long long
using namespace std;
const int maxn = 200000 + 10;
char str[maxn];
int r[maxn], len;
struct suffixautomaton
{
int ch[maxn][30], pre[maxn], val[maxn], num[maxn], top[maxn];
int c[maxn];
int sz, last, cnt;
void init() { pre[0] = -1; last = cnt = 0; sz = 1; 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]; }
}
}
}
lng slove()
{
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 = ch[i][r[val[i]]])
{
num[i] = 1;
if(val[i] == len) break;
}
for(int i = sz - 1; i > 0; --i)
{
num[pre[top[i]]] += num[top[i]];
}
lng res = 0;
for(int i = 1; i < sz; ++i)
{
res += (num[i] * 1LL * (num[i] + 1) / 2) * (val[i] - val[pre[i]]);
}
return res;
}
}sam;
int main()
{
freopen("in", "r", stdin);
cin >> str; len = strlen(str);
sam.init();
for(int i = 0; i < len; ++i)
{
r[i] = str[i] - 'a';
sam.insert(r[i]);
}
cout << sam.slove() << "\n";
return 0;
}