【LOJ】 #2033. 「SDOI2016」生成魔咒

题解

就是字符集较大需要离散化和建边表的后缀自动机水题

每次会加入i个新的串,其中重复的就是i的父亲节点所在节点的长度,减掉即可

代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#define enter putchar('
')
#define space putchar(' ')
#define MAXN 1000005
//#define ivorysi
#define pb push_back
#define mo 1000007
#define pii pair<int,int>
#define mp make_pair
using namespace std;
typedef long long int64;
template<class T>
void read(T &res) {
    res = 0;char c = getchar();T f = 1;
    while(c < '0' || c > '9') {
	if(c == '-') f = -1;
	c = getchar();
    }
    while(c >= '0' && c <= '9') {
	res = res * 10 - '0' + c;
	c = getchar();
    }
    res = res * f;
}
template<class T>
void out(T x) {
    if(x < 0) {x = -x;putchar('-');}
    if(x >= 10) out(x / 10);
    putchar('0' + x % 10);
}
struct node {
    int to,next,v;
}E[MAXN * 4];
int head[MAXN * 2],sumE,rt,last,Ncnt,par[MAXN * 2],len[MAXN * 2];
int find_Edge(int u,int v) {
    for(int i = head[u] ; i ; i = E[i].next) {
	if(E[i].v == v) return E[i].to;
    }
    return 0;
}
void add(int u,int v,int c) {
    E[++sumE].to = v;E[sumE].v = c;E[sumE].next = head[u];
    head[u] = sumE;
}
void build_SAM(int L,int v) {
    int nowp = ++Ncnt,p;
    len[nowp] = L;
    for(p = last ; p && !find_Edge(p,v) ; p = par[p]) {
	add(p,nowp,v);
    }
    if(!p) par[nowp] = rt;
    else {
	int q = find_Edge(p,v);
	if(len[q] == len[p] + 1) par[nowp] = q;
	else {
	    int copyq = ++Ncnt;
	    len[copyq] = len[p] + 1;par[copyq] = par[q];
	    for(int i = head[q] ; i ; i = E[i].next) {
		add(copyq,E[i].to,E[i].v);
	    }
	    par[q] = copyq;par[nowp] = copyq;
	    for( ; p && find_Edge(p,v) == q ; p = par[p]) {
		for(int i = head[p] ; i ; i = E[i].next) {
		    if(E[i].v == v) {E[i].to = copyq;break;}
		}
	    }
	}
    }
    last = nowp;
}
int N,a[MAXN],num[MAXN],tot;
void Solve() {
    read(N);
    for(int i = 1 ; i <= N ; ++i) {
	read(a[i]);num[i] = a[i];
    }
    sort(num + 1,num + N + 1);
    int tot = unique(num + 1,num + N + 1) - num - 1;
    for(int i = 1 ; i <= N ; ++i) {
	a[i] = lower_bound(num + 1,num + tot + 1,a[i]) - num;
    }
    rt = last = ++Ncnt;
    int64 ans = 0;
    for(int i = 1 ; i <= N ; ++i) {
	build_SAM(i,a[i]);
	ans += i - len[par[last]];
	out(ans);enter;
    }
}
int main() {
#ifdef ivorysi
    freopen("f1.in","r",stdin);
#endif
    Solve();
}
原文地址:https://www.cnblogs.com/ivorysi/p/9181840.html