链接
题解
前置技能:广义后缀自动机
从每个叶子出发 ,建立字典树
然后在字典树上建
然后直接用经典方法求出本质不同的字串个数即可
代码
#include <bits/stdc++.h>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 2000010
#define maxe 4000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(_,__) for(_=1;_<=(__);_++)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct Trie
{
int tot, ch[maxn][10];
void init(){while(tot--)cl(ch[tot+1]);tot=1;}
int* operator[](int index){return ch[index];}
int id(char c){return c-'a';}
int append(int pos, int c)
{
int &t=ch[pos][c];
return t?t:t=++tot;
}
int insert(char* s, int n)
{
int pos=1, i;
for(i=1;i<=n;i++)pos=append(pos,s[i]);
return pos;
}
}trie;
struct EXSAM
{
int tot, ch[maxn<<1][10], fa[maxn<<1], len[maxn<<1], pref[maxn<<1];
int* operator[](int u){return ch[u];}
void init()
{
int i;
rep(i,tot)cl(ch),fa[i]=len[i]=pref[i]=0;
tot=1;
}
int append(int las, int c)
{
int p(las);
len[las=++tot]=len[p]+1;
pref[las]=1;
for(;p and !ch[p][c];p=fa[p])ch[p][c]=las;
if(!p)fa[las]=1;
else
{
int q=ch[p][c];
if(len[q]==len[p]+1)fa[las]=q;
else
{
int qq=++tot;
memcpy(ch[qq],ch[q],sizeof(ch[q]));
fa[qq]=fa[q];
len[qq]=len[p]+1;
fa[q]=fa[las]=qq;
for(;ch[p][c]==q;p=fa[p])ch[p][c]=qq;
}
}
return las;
}
void bfs_build(Trie& trie)
{
queue<pii> q;
q.em(pii(1,1));
while(!q.empty())
{
auto pr=q.front(); q.pop();
int pos=pr.first, u=pr.second;
for(int i=0;i<10;i++)
if(trie[pos][i])
{
int to=trie[pos][i], v=ch[u][i]?ch[u][i]:append(u,i);
q.em(pii(to,v));
}
}
}
int mov(int p, int c){return max(1,ch[p][c]);}
}exsam;
struct Graph
{
int etot, head[maxn], to[maxe], next[maxe], w[maxe];
void clear(int N)
{
for(int i=1;i<=N;i++)head[i]=0;
etot=0;
}
void adde(int a, int b, int c=0){to[++etot]=b;w[etot]=c;next[etot]=head[a];head[a]=etot;}
#define forp(pos,G) for(auto p=G.head[pos];p;p=G.next[p])
}G;
int deg[maxn], col[maxn];
void dfs(int pos, int pre, int trie_pos)
{forp(pos,G)if(G.to[p]!=pre)dfs(G.to[p],pos,trie.append(trie_pos,col[G.to[p]]));}
int main()
{
int i, n, u, v, m;
n=read(), m=read();
rep(i,n)col[i]=read();
rep(i,n-1)
{
u=read(), v=read();
G.adde(u,v), G.adde(v,u);
deg[u]++, deg[v]++;
}
trie.init();
rep(i,n)if(deg[i]==1)
{
dfs(i,0,trie.append(1,col[i]));
}
exsam.init();
exsam.bfs_build(trie);
ll ans=0;
rep(i,exsam.tot)ans+=exsam.len[i]-exsam.len[exsam.fa[i]];
printf("%lld",ans);
return 0;
}