-
Notifications
You must be signed in to change notification settings - Fork 439
/
Persistent-Trie.cpp
137 lines (123 loc) · 2.04 KB
/
Persistent-Trie.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <cstdio>
#include <cstring>
#include <algorithm>
#define NIL 0
using namespace std;
struct node
{
node *next[26];
int cnt;
node() : cnt(0) { memset(next, 0, sizeof(next)); }
};
struct vertex
{
int first, depth;
node *root;
}V[100010];
struct edge
{
int endp, next;
}E[200010];
int n, ec = 2, q, fa[100010][18], k;
char str[100010][12];
inline void add_edge(int u, int v)
{
E[ec].next = V[u].first;
V[u].first = ec;
E[ec].endp = v;
ec++;
}
void insert(node *&u, node *old, char *s, int len, int p)
{
u = new node;
if (old != NIL) *u = *old;
u->cnt++;
if (p == len) return;
int x = s[p] - 'a';
u->next[x] = NIL;
insert(u->next[x], old == NIL ? NIL : old->next[x], s, len, p + 1);
}
int query(node *u, char *s, int len, int p)
{
if (u == NIL) return 0;
if (p == len) return u->cnt;
int x = s[p] - 'a';
return query(u->next[x], s, len, p + 1);
}
int query(int u, char *s)
{
return query(V[u].root, s, strlen(s), 0);
}
void dfs(int u, int fa, int depth)
{
::fa[u][0] = fa;
V[u].depth = depth;
for (int cur = V[u].first; cur != 0; cur = E[cur].next)
{
if (E[cur].endp != fa)
{
insert(V[E[cur].endp].root, V[u].root, str[cur >> 1], strlen(str[cur >> 1]), 0);
dfs(E[cur].endp, u, depth + 1);
}
}
}
void init()
{
V[1].root = new node;
dfs(1, 0, 0);
for (k = 1; (1 << k) <= n; k++)
{
for (int i = 1; i <= n; i++)
{
fa[i][k] = fa[fa[i][k - 1]][k - 1];
}
}
k--;
}
int lca(int x, int y)
{
if (V[x].depth < V[y].depth)
{
swap(x, y);
}
for (int i = k; i >= 0; i--)
{
if (V[x].depth - (1 << i) >= V[y].depth)
{
x = fa[x][i];
}
}
if (x == y)
{
return x;
}
for (int i = k; i >= 0; i--)
{
if (fa[x][i] != fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main()
{
scanf("%d", &n);
int u, v;
for (int i = 1; i < n; i++)
{
scanf("%d%d%s", &u, &v, str[i]);
add_edge(u, v);
add_edge(v, u);
}
init();
scanf("%d", &q);
char s[12];
while (q--)
{
scanf("%d%d%s", &u, &v, s);
printf("%d\n", query(u, s) + query(v, s) - query(lca(u, v), s) * 2);
}
return 0;
}