[Ahoi2013]差异(后缀自动机)

/*
前面的那一坨是可以O1计算的
后面那个显然后缀数组单调栈比较好写??? 两个后缀的lcp长度相当于他们在后缀树上的lca的深度
那么我们就能够反向用后缀自动机构造出后缀树然后统计每个点作为lca的情况和即可 */ #include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#define ll long long
#define mmp make_pair
#define M 1000100
using namespace std;
int read()
{
int nm = 0, f = 1;
char c = getchar();
for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
return nm * f;
}
int ch[M][26], sz[M], len[M], fa[M], tim[M], a[M], cnt = 1, lst = 1;
char s[M];
void insert(int c)
{
int p = ++cnt, f = lst;
lst = p;
sz[p] = 1;
len[p] = len[f] + 1;
while(f && !ch[f][c]) ch[f][c] = p, f = fa[f];
if(!f) fa[p] = 1;
else
{
int q = ch[f][c];
if(len[q] == len[f] + 1) fa[p] = q;
else
{
int nq = ++cnt;
memcpy(ch[nq], ch[q], sizeof(ch[q]));
fa[nq] = fa[q];
len[nq] = len[f] + 1;
fa[q] = fa[p] = nq;
while(f && ch[f][c] == q) ch[f][c] = nq, f = fa[f];
}
}
}
ll ans = 0;
int main()
{
scanf("%s", s + 1);
int l = strlen(s + 1);
for(int i = l; i >= 1; i--) insert(s[i] - 'a');
for(int i = 1; i <= cnt; i++) tim[len[i]]++;
for(int i = 1; i <= cnt; i++) tim[i] += tim[i - 1];
for(int i = 1; i <= cnt; i++) a[tim[len[i]]--] = i;
for(int i = cnt; i >= 1; i--) sz[fa[a[i]]] += sz[a[i]];
ans = 1ll * l * (l - 1) * (l + 1) / 2;
for(int i = 2; i <= cnt; i++) ans -= 1ll * sz[i] * (sz[i] - 1) * (len[i] - len[fa[i]]);
cout << ans << "\n";
return 0;
}
上一篇:Python xlrd、xlwt、xlutils修改Excel文件


下一篇:Python -- xlrd,xlwt,xlutils 读写同一个Excel