跳到正文

个人记录

P4070 [SDOI2016]生成魔咒

Sunny_r约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年2月5日
更新
2026年2月5日
篇幅
约 2 分钟

版本

  1. v1当前

这题很显然就是求本质不同的子串的数量,那么有两种方法。

显然dp是不优的啦,所以我们考虑另一种方法。

所以我们需要求出∑len(i)−len(fa[i])\sum len(i)-len(fa[i])就好啦。

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#define ll long long
using namespace std;
const int N = 200005;
map<int, int> tr[N];
int n, len[N], fa[N], cnt = 1, last = 1;
ll ans;
inline int read()
{
	int x = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') {x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar();}
	return x * f;
}
void insert(int x)
{
	int np = ++ cnt, p = last, q, nq; len[last = np] = len[p] + 1;
	for(; p && !tr[p][x]; p = fa[p]) tr[p][x] = np;
	if(!p) fa[np] = 1;
	else
	{
		q = tr[p][x];
		if(len[q] == len[p] + 1) fa[np] = q;
		else
		{
			len[nq = ++ cnt] = len[p] + 1; fa[nq] = fa[q]; fa[q] = fa[np] = nq;
			tr[nq] = tr[q];
			for(; p && tr[p][x] == q; p = fa[p]) tr[p][x] = nq;
		}
	}
	ans += len[np] - len[fa[np]];
}
void work()
{
	n = read();
	for(int i = 1, x; i <= n; i ++)
	{
		x = read(); insert(x);
		printf("%lld\n", ans);
	}
}
int main() {return work(), 0; }
原文