离线版本
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
using namespace std;
typedef long long LL;
const int maxn = 100005;
struct SAM{
int fa[maxn<<1], // 后缀链接
//ch[maxn<<1][ch_size],
len[maxn<<1], //该节点最长串的长度
tot, // 节点总数
last; // 代表当前的整个串
map<int,int> ch[maxn<<1];
void init(){
tot = last = 0;
fa[0] = -1;
len[0] = 0;
ch[0].clear();
}
void extend( int x ){
int p = last;
int cur = ++tot;
ch[cur].clear();
len[cur] = len[last]+1;
while( p != -1 && ch[p].find(x)==ch[p].end() ){
ch[p][x] = cur;
p = fa[p];
}
if( p == -1 ){
fa[cur] = 0;
}else {
int q = ch[p][x];
if (len[q] == len[p] + 1) {
fa[cur] = q;
} else {
int clone = ++tot;
len[clone] = len[p] + 1;
ch[clone] = ch[q];
fa[clone] = fa[q];
fa[q] = fa[cur] = clone;
while (p != -1) {
if (ch[p][x] == q)ch[p][x] = clone;
else break;
p = fa[p];
}
}
}
last = cur;
}
}g;
int b[maxn<<1],c[maxn];
void radix( int len ){
memset( c,0,sizeof(c) );
for( int i = 1;i <= g.tot;i++ ) c[ g.len[i] ]++;
for( int i = 2;i <= len;i++ ) c[ i ] += c[i-1];
for( int i = 1;i <= g.tot;i++ ) b[ c[ g.len[i] ]-- ] = i;
}
int a[maxn],vis[maxn<<1];
LL solve( int p ){
LL res = 0;
while( p && !vis[p] ){
res += g.len[p] - g.len[ g.fa[p] ];
vis[p] = 1;
p = g.fa[p];
}
return res;
}
int main(){
int n;
scanf("%d",&n);
g.init();
for (int i = 1; i <= n; i++) {
scanf("%d",&a[i]);
g.extend( a[i] );
}
int p = 0;
LL ans = 0;
for( int i = 1;i <= n;i++ ){
int c = a[i];
p = g.ch[p][ c ];
ans += solve(p);
printf("%lld\n",ans);
}
return 0;
}
在线版本(记得更新vis标记)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
using namespace std;
typedef long long LL;
const int maxn = 100005;
int a[maxn],vis[maxn<<1];
struct SAM{
int fa[maxn<<1], // 后缀链接
//ch[maxn<<1][ch_size],
len[maxn<<1], //该节点最长串的长度
tot, // 节点总数
last; // 代表当前的整个串
map<int,int> ch[maxn<<1];
void init(){
tot = last = 0;
fa[0] = -1;
len[0] = 0;
ch[0].clear();
}
void extend( int x ){
int p = last;
int cur = ++tot;
ch[cur].clear();
len[cur] = len[last]+1;
while( p != -1 && ch[p].find(x)==ch[p].end() ){
ch[p][x] = cur;
p = fa[p];
}
if( p == -1 ){
fa[cur] = 0;
}else {
int q = ch[p][x];
if (len[q] == len[p] + 1) {
fa[cur] = q;
} else {
int clone = ++tot;
len[clone] = len[p] + 1;
ch[clone] = ch[q];
fa[clone] = fa[q];vis[clone] = vis[q];
fa[q] = fa[cur] = clone;
while (p != -1) {
if (ch[p][x] == q)ch[p][x] = clone;
else break;
p = fa[p];
}
}
}
last = cur;
}
}g;
LL solve( int p ){
LL res = 0;
while( p && !vis[p] ){
res += g.len[p] - g.len[ g.fa[p] ];
vis[p] = 1;
p = g.fa[p];
}
return res;
}
int main(){
int n;
scanf("%d",&n);
g.init();
LL ans = 0;
for (int i = 1; i <= n; i++) {
scanf("%d",&a[i]);
g.extend( a[i] );
ans += solve( g.last );
printf("%lld\n",ans);
}
return 0;
}