bzoj4516: [Sdoi2016]生成魔咒

传送门

用阿伏伽德罗的话来说,典型的人类进化还不完全的时候的题。

一个裸的sam。

写sam总是一不小心把np写成p。。。

//Achen
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<queue>
#include<cmath>
#include<map>
#define For(i,a,b) for(int i=(a);i<=(b);i++)
#define Rep(i,a,b) for(int i=(a);i>=(b);i--)
const int N=200007;
typedef long long LL;
using namespace std;
int n,x;
LL ans;

template<typename T>void read(T &x)  {
    char ch=getchar(); x=0; T f=1;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') f=-1,ch=getchar();
    for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0'; x*=f;
}

int p,np,tot,last,fa[N],l[N];
map<int,int>ch[N];
void insert(int c) {
    np=++tot; p=last; last=np;
    l[np]=l[p]+1;
    for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
    if(!p) fa[np]=1;
    else {
        int q=ch[p][c];
        if(l[p]+1==l[q]) fa[np]=q;
        else {
            int nq=++tot; l[nq]=l[p]+1;
            ch[nq]=ch[q]; fa[nq]=fa[q];
            fa[q]=fa[np]=nq;
            for(;p&&ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
        }
    }
    ans+=(LL)l[np]-l[fa[np]];
    printf("%lld\n",ans);
}

int main() {
#ifdef DEBUG
    freopen(".in","r",stdin);
    freopen(".out","w",stdout);
#endif
    last=++tot;
    read(n);
    For(i,1,n) {
        read(x);
        insert(x);
    }
    return 0;
}
/*
7
1 2 3 3 3 1 2
*/
View Code

 

posted @ 2018-03-12 18:35  啊宸  阅读(180)  评论(0编辑  收藏  举报