Bzoj4516: [Sdoi2016]生成魔咒

题面

bzoj

Sol

(sam)
维护一下不同子串的个数就好了
(map)

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
# define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
using namespace std;
typedef long long ll;

IL int Input(){
	RG int x = 0, z = 1; RG char c = getchar();
	for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
	for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
	return x * z;
}

const int maxn(2e5 + 5);

int tot = 1, last = 1, fa[maxn], len[maxn];
map <int, int> trans[maxn];

IL void Extend(RG int c){
	RG int p = last, np = ++tot; last = tot;
	len[np] = len[p] + 1;
	while(p && !trans[p][c]) trans[p][c] = np, p = fa[p];
	if(!p) fa[np] = 1;
	else{
		RG int q = trans[p][c];
		if(len[q] == len[p] + 1) fa[np] = q;
		else{
			RG int nq = ++tot;
			len[nq] = len[p] + 1, fa[nq] = fa[q];
			trans[nq] = trans[q], fa[q] = fa[np] = nq;
			while(p && trans[p][c] == q) trans[p][c] = nq, p = fa[p];
		}
	}
}

int main(RG int argc, RG char* argv[]){
	for(RG ll n = Input(), ans = 0; n; --n)
		Extend(Input()), printf("%lld
", ans += len[last] - len[fa[last]]);
	return 0;
}
原文地址:https://www.cnblogs.com/cjoieryl/p/8900970.html