【题目链接】
【思路要点】
- 补档博客,无题解。
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 100005 #define MAXP 4000005 #define MAXC 10 struct Suffix_Automaton { int child[MAXP][MAXC]; int father[MAXP], depth[MAXP]; vector <int> a[MAXP]; int root, size; int new_node(int dep) { depth[size] = dep; father[size] = 0; memset(child[size], 0, sizeof(child[size])); return size++; } void init() { size = 0; root = new_node(0); } int Extend(int ch, int last) { int np = child[last][ch]; if (np) { if (depth[np] == depth[last] + 1) return np; else { int nq = new_node(depth[last] + 1); father[nq] = father[np]; father[np] = nq; memcpy(child[nq], child[np], sizeof(child[np])); for (int p = last; child[p][ch] == np; p = father[p]) child[p][ch] = nq; return nq; } } else { np = new_node(depth[last] + 1); int p = last; for (; child[p][ch] == 0; p = father[p]) child[p][ch] = np; if (child[p][ch] == np) { father[np] = root; return np; } int q = child[p][ch]; if (depth[p] + 1 == depth[q]) { father[np] = q; return np; } else { int nq = new_node(depth[p] + 1); father[nq] = father[q]; father[q] = father[np] = nq; memcpy(child[nq], child[q], sizeof(child[q])); for (; child[p][ch] == q; p = father[p]) child[p][ch] = nq; return np; } } } void build() { for (int i = 1; i < size; i++) a[father[i]].push_back(i); } long long get(int pos) { long long ans = depth[pos] - depth[father[pos]]; for (unsigned i = 0; i < a[pos].size(); i++) ans += get(a[pos][i]); return ans; } } SAM; vector <int> a[MAXN]; int n, m, value[MAXN], d[MAXN]; void work(int pos, int fa, int last) { last = SAM.Extend(value[pos], last); for (unsigned i = 0; i < a[pos].size(); i++) if (a[pos][i] != fa) work(a[pos][i], pos, last); } int main() { SAM.init(); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%d", &value[i]); for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); a[x].push_back(y); a[y].push_back(x); d[x]++; d[y]++; } for (int i = 1; i <= n; i++) { if (d[i] > 1) continue; work(i, 0, SAM.root); } SAM.build(); printf("%lld\n", SAM.get(SAM.root)); return 0; }