#include typedef struct List { struct List *next; int v; char c; } list; void chmin(int* a, int b) { if (*a > b) *a = b; } void chmax(int* a, int b) { if (*a < b) *a = b; } int main() { int i, N, s, u, w, x; char S[2001], c; list *adj[2001] = {}, e[4001], *p, *pp; scanf("%d", &N); scanf("%s", S); for (s = 0; S[s] != 0; s++); for (i = 0; i < N - 1; i++) { scanf("%d %d %c ", &u, &w, &c); e[i*2].v = w; e[i*2+1].v = u; e[i*2].c = c; e[i*2+1].c = c; e[i*2].next = adj[u]; e[i*2+1].next = adj[w]; adj[u] = &(e[i*2]); adj[w] = &(e[i*2+1]); } int par[2001] = {}, q[2001], head, tail; par[1] = 1; q[0] = 1; for (head = 0, tail = 1; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (par[w] == 0) { par[w] = u; q[tail++] = w; } } } int j, k, l, r, m, LCS[2][2001] = {}, LCS_pos[2][2001][2001], tmp[2001], ans = 0; for (u = 1; u <= N; u++) { for (i = 1, LCS_pos[0][u][0] = -1, LCS_pos[1][u][0] = s; i <= s; i++) { LCS_pos[0][u][i] = s; LCS_pos[1][u][i] = -1; } } for (head--; head >= 0; head--) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; c = p->c; if (w == par[u]) continue; for (i = s - 1; i >= 0; i--) { if (S[i] != c) continue; l = 0; r = LCS[0][w] + 1; while (l < r) { m = (l + r) / 2; if (LCS_pos[0][w][m] < i) l = m + 1; else r = m; } LCS_pos[0][w][l] = i; if (l == LCS[0][w] + 1) LCS[0][w]++; } for (i = 1; i <= LCS[0][w]; i++) chmin(&(LCS_pos[0][u][i]), LCS_pos[0][w][i]); chmax(&(LCS[0][u]), LCS[0][w]); for (i = 0; i < s; i++) { if (S[i] != c) continue; l = 0; r = LCS[1][w] + 1; while (l < r) { m = (l + r) / 2; if (LCS_pos[1][w][m] > i) l = m + 1; else r = m; } LCS_pos[1][w][l] = i; if (l == LCS[1][w] + 1) LCS[1][w]++; } for (i = 1; i <= LCS[1][w]; i++) chmax(&(LCS_pos[1][u][i]), LCS_pos[1][w][i]); chmax(&(LCS[1][u]), LCS[1][w]); } chmax(&ans, LCS[0][u]); chmax(&ans, LCS[1][u]); for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (w == par[u]) continue; for (pp = adj[u]; pp != NULL; pp = pp->next) { x = pp->v; if (x == par[u] || x == w) continue; for (i = 0, j = LCS[1][x]; i <= LCS[0][w]; i++) { for (; LCS_pos[1][x][j] <= LCS_pos[0][w][i]; j--); chmax(&ans, i + j); } } } } printf("%d\n", ans); fflush(stdout); return 0; }