\(trie\)树建广义后缀自动机:

\(dfs\)遍历\(trie\)树,将树上的一个节点插入\(sam\)时,将他的\(fa\)在\(sam\)上所在的节点作为\(last\)

#include<map>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=2e5+100,maxm=4e6+100;
struct SAM{
int son[maxm][11],len[maxm],fa[maxm];
int last,tot,head[maxn],num,nex[maxn],v[maxn],c[maxn],du[maxn];
SAM(){last=tot=0,fa[0]=-1,num=1;}
void add(int x,int y){
v[++num]=y;
nex[num]=head[x];
head[x]=num;
v[++num]=x;
nex[num]=head[y];
head[y]=num;
du[x]++,du[y]++;
}
int insert(int x,int last){
int p=last,np=son[p][x];
if(np&&len[np]==len[p]+1) return np;
np=++tot;
len[np]=len[p]+1;
while(~p&&!son[p][x])
son[p][x]=np,p=fa[p];
if(p==-1)
fa[np]=0;
else{
int q=son[p][x];
if(len[q]==len[p]+1)
fa[np]=q;
else{
int nq=++tot;
memcpy(son[nq],son[q],sizeof(son[q]));
fa[nq]=fa[q];
len[nq]=len[p]+1;
fa[q]=fa[np]=nq;
while(~p&&son[p][x]==q)
son[p][x]=nq,p=fa[p];
}
}
return np;
}
void dfs(int x,int fa,int last){
last=insert(c[x],last);
for(int i=head[x];i;i=nex[i])
if(v[i]!=fa)
dfs(v[i],x,last);
}
void query(){
ll ans=0;
for(int i=1;i<=tot;i++)
ans+=1ll*(len[i]-len[fa[i]]);
printf("%lld\n",ans);
}
}sam;
int n,m,a,b;
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&sam.c[i]);
for(int i=1;i<n;i++)
scanf("%d%d",&a,&b),sam.add(a,b);
for(int i=1;i<=n;i++)
if(sam.du[i]==1)
sam.dfs(i,i,0);
sam.query();
return 0;
}

最新文章

  1. vmware workstation9.0 RHEL5.8 oracle 10g RAC安装指南及问题总结
  2. POJ 2312Battle City(BFS-priority_queue 或者是建图spfa)
  3. 【Solr】copy字段的应用
  4. 巧用translate设置元素垂直水平居中
  5. Linq专题之集合初始化器
  6. win7系统扩展双屏幕时,如何在两个屏幕下都显示任务栏
  7. 【T_SQL】 基础 视图、存储过程、触发器
  8. C++ CheckMenuItem
  9. 1.Basic Structure
  10. Js实现select联动,option从数据库中读取
  11. Eclipse:The selection cannot be launched,and there are no recent launches
  12. 《深入浅出设计模式》读书笔记 C#版(第一章)
  13. (NO.00001)iOS游戏SpeedBoy Lite成形记(十五)
  14. 禁用 urllib3 的安全请求警告
  15. WCF的练习。
  16. 绕过安全狗狗的WebShell for PHP
  17. svn 回退/更新/取消至某个版本命令详解【转】
  18. 生活随记[All]
  19. 20155225 实验二《Java面向对象程序设计》实验报告
  20. Laravel中的信息验证 和 语言包

热门文章

  1. PHP中常用的字符串函数?
  2. Laravel5.1 Migration数据库迁移文件
  3. Andriod - 创建自定义控件
  4. ZOJ1311(Network)
  5. 使用RestTemplate post方式提交表单数据
  6. Super Resolution
  7. CSS3随意记录
  8. C#中的自定义控件中的属性、事件及一些相关特性的总结(转)
  9. T-SQL利用笛卡尔积累计、累加
  10. vloatile总结与synchronized对比