【题目链接】
【思路要点】
- 用可持久化字典树维护每个点到根路径上字符串的字典树。
- 询问时分别查询\(x\),\(y\)和\(Lca(x,y)\)即可。
- 时间复杂度\(O((N+Q)(|S|+LogN))\)。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 5; const int MAXLOG = 18; const int MAXP = 1e6 + 5; const int MAXL = 15; const int MAXC = 26; template <typename T> void chkmax(T &x, T y) {x = max(x, y); } template <typename T> void chkmin(T &x, T y) {x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } struct Trie { struct Node { int child[MAXC]; int size; } a[MAXP]; int size; int extend(int root, char *s) { int now = ++size, ans = size, len = strlen(s + 1); a[now] = a[root]; a[now].size++; for (int i = 1; i <= len; i++) { int tmp = s[i] - 'a'; a[now].child[tmp] = ++size; root = a[root].child[tmp]; a[size] = a[root]; now = a[now].child[tmp]; a[now].size++; } return ans; } int query(int root, char *s) { int now = root, len = strlen(s + 1); for (int i = 1; i <= len; i++) now = a[now].child[s[i] - 'a']; return a[now].size; } } Trie; struct edge {int dest, home; }; int n, m, root[MAXN]; char s[MAXL], st[MAXN][MAXL]; int depth[MAXN], father[MAXN][MAXLOG]; vector <edge> a[MAXN]; void dfs(int pos, int fa, int from) { depth[pos] = depth[fa] + 1; father[pos][0] = fa; if (fa != 0) root[pos] = Trie.extend(root[fa], st[from]); for (int i = 1; i < MAXLOG; i++) father[pos][i] = father[father[pos][i - 1]][i - 1]; for (unsigned i = 0; i < a[pos].size(); i++) if (a[pos][i].dest != fa) dfs(a[pos][i].dest, pos, a[pos][i].home); } int lca(int x, int y) { if (depth[x] < depth[y]) swap(x, y); for (int i = MAXLOG - 1; i >= 0; i--) if (depth[father[x][i]] >= depth[y]) x = father[x][i]; if (x == y) return x; for (int i = MAXLOG - 1; i >= 0; i--) if (father[x][i] != father[y][i]) { x = father[x][i]; y = father[y][i]; } return father[x][0]; } int main() { read(n); for (int i = 1; i <= n - 1; i++) { int x, y; read(x), read(y); a[x].push_back((edge) {y, i}); a[y].push_back((edge) {x, i}); scanf(" %s", st[i] + 1); } dfs(1, 0, 0); read(m); for (int i = 1; i <= m; i++) { int x, y; read(x), read(y); scanf("%s", s + 1); int Lca = lca(x, y); writeln(Trie.query(root[x], s) + Trie.query(root[y], s) - 2 * Trie.query(root[Lca], s)); } return 0; }