嘟嘟嘟
哈,我竟然一眼秒了,从开始看题到A用了不到15分钟。
SAM每一次求不同子串个数是(O(n))的,所以(O(n ^ 2))自然过不了。
这时我想了想SAM每一次是怎么求不同子串个数的,就是遍历parent树,每一次加上(len[now] - len[link[now]])。
因此我们添加字符的时候,加上新的节点产生的贡献,如果遇到第三种情况,就把原来节点的贡献减去,再加上改过的节点的贡献就好啦~
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e5 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n;
ll ans = 0;
struct Sam
{
int las, cnt;
map<int, int> tra[maxn << 1];
int len[maxn << 1], link[maxn << 1];
In void init() {link[las = cnt = 0] = -1;}
In void insert(int x)
{
int now = ++cnt, p = las;
len[now] = len[las] + 1;
while(~p && !tra[p].count(x)) tra[p][x] = now, p = link[p];
if(p == -1) link[now] = 0, ans += len[now];
else
{
int q = tra[p][x];
if(len[q] == len[p] + 1) link[now] = q, ans += len[now] - len[link[now]];
else
{
int clo = ++cnt;
tra[clo] = tra[q];
len[clo] = len[p] + 1;
ans -= len[q] - len[link[q]];
link[clo] = link[q], link[q] = link[now] = clo;
ans += len[clo] - len[link[clo]];
ans += len[q] - len[link[q]];
ans += len[now] - len[link[now]];
while(~p && tra[p][x] == q) tra[p][x] = clo, p = link[p];
}
}
las = now;
}
}S;
int main()
{
n = read(); S.init();
for(int i = 1; i <= n; ++i)
{
int x = read();
S.insert(x);
write(ans), enter;
}
return 0;
}