1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cmath>5#include <algorithm>6 #defineMAXN 1000057 #defineMaxl 2000058 #defineMAXM 40000059 using namespacestd;Ten OnetypedefLong Longll; A intN,C,CNT,TOT,ROOT,LAST,FA[MAXM],DU[MAXN],DIST[MAXM],SON[MAXL],PREP[MAXL],NOW[MAXN],V[MAXN]; - ll ans; - voidAddintXinty) { thecnt++,prep[cnt]=now[x],now[x]=cnt,son[cnt]=y; - } - structtsegment{ - intson[maxm][Ten]; + voidPrepare () {tot=last=root=1; Memset (Dist,0,sizeof(Dist));} - intNewNodeintx) {dist[++tot]=x;returntot;} + intAddintXintp) { A intq=Son[p][x]; at if(q==0){ - intNp=newnode (dist[p]+1); last=NP; - for(;p &&!son[p][x];p =fa[p]) son[p][x]=NP; - if(p==0) fa[np]=Root; - Else{ -q=Son[p][x]; in if(dist[p]+1==DIST[Q]) fa[np]=Q; - Else{ to intNq=newnode (dist[p]+1); +memcpy (Son[nq],son[q],sizeof(Son[q])); -fa[nq]=fa[q],fa[q]=fa[np]=NQ; the for(;p &&son[p][x]==q;p=fa[p]) son[p][x]=NQ; * } $ }Panax Notoginseng}Else{ - if(dist[p]+1==DIST[Q]) last=Q; the Else{ + intNq=newnode (dist[p]+1); last=NQ; Amemcpy (Son[nq],son[q],sizeof(Son[q])); thefa[nq]=fa[q],fa[q]=NQ; + for(;p &&son[p][x]==q;p=fa[p]) son[p][x]=NQ; - } $ } $ returnLast ; - } - }sam; the voidDfsintXintPaintgoal) { - intp=Sam.add (v[x],goal);Wuyi for(inti=now[x],so=son[i];i;i=prep[i],so=Son[i]) { the if(SO==PA)Continue; - DFS (so,x,p); Wu } - } About intMain () { $scanf"%d%d",&n,&c); -Memset (Du,0,sizeof(du)); -cnt=tot=ans=0, Memset (now,0,sizeof(now)); - for(intI=1; i<=n;i++) scanf ("%d",&v[i]); A for(intU,v,i=1; i<n;i++) scanf ("%d%d", &u,&v), add (U,v), add (v,u), du[u]++,du[v]++; + Sam.prepare (); the for(intI=1; i<=n;i++){ - if(du[i]>1)Continue; $DFS (I,0, root); the } theans=0; thedist[root]=0; the for(intI=1; i<=tot;i++) ans+= (dist[i]-Dist[fa[i]]); -printf"%lld\n", ans); in return 0; the}
View Code
Procedure: Generalized suffix automata.
dfs+ suffix automaton.
bzoj3926: [Zjoi2015] Fantasy Township of the Gods