#define _USE_MATH_DEFINES #include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define MT make_tuple #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)<; using vi = vector; using vll = vector; using Graph = vector>>; using vvi = vector; int f(int k, int u, int p, vvi &X, const string &S, const Graph &G) { int& res = X[k][u]; if (res != -1)return res; res = 0; if (k < sz(S))smax(res, f(k + 1, u, p, X, S, G)); each(e, G[u]) { if (e.first != p) { smax(res, f(k, e.first, u, X, S, G)); if (k < sz(S) && S[k] == e.second) { smax(res, f(k + 1, e.first, u, X, S, G) + 1); } } } return res; } int g(int u, int p, vvi& toL, vvi& toR, Graph& G) { int res = 0; int n = sz(toL) - 1; // [0, i), [i, n) FOR(i, 1, n) { vector L, R; each(e, G[u]) if (e.first != p) { L.emplace_back(toL[n - i][e.first], e.first); R.emplace_back(toR[i][e.first], e.first); } if (sz(L) < 2)break; sort(rbegin(L), rend(L)); sort(rbegin(R), rend(R)); rep(j, 2)rep(k, 2) { if (L[j].second != R[k].second) { smax(res, L[j].first + R[k].first); } } } each(e, G[u])if (e.first != p) { smax(res, g(e.first, u, toL, toR, G)); } return res; } void solve() { int N; string S; cin >> N >> S; Graph G(N); rep(i, N - 1) { int u, v; char c; cin >> u >> v >> c; --u; --v; G[u].emplace_back(v, c); G[v].emplace_back(u, c); } vvi toR(sz(S) + 1, vi(N, -1)), toL = toR; f(0, 0, -1, toR, S, G); reverse(all(S)); f(0, 0, -1, toL, S, G); int ans = smax(toR[0][0], g(0, -1, toL, toR, G)); cout << ans << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); solve(); return 0; }