// ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- fn run() { input! { n: usize, s: bytes, e: [(usize1, usize1, bytes); n - 1], } let mut g = vec![vec![]; n]; for (a, b, c) in e { let c = c[0]; g[a].push((b, c)); g[b].push((a, c)); } let mut topo = vec![0]; for i in 0..n { let v = topo[i]; for (u, _) in g[v].clone() { let x = g[u].iter().position(|p| p.0 == v).unwrap(); g[u].remove(x); topo.push(u); } } let mut ans = 0; let w = s.len(); let mut up = vec![vec![]; n]; let mut down = vec![vec![]; n]; for &v in topo.iter().rev() { if g[v].is_empty() { up[v] = vec![0; w + 1]; down[v] = vec![0; w + 1]; continue; } for _ in 0..2 { let mut a = vec![0; w + 1]; let mut memo = vec![vec![0; w + 1]]; for &(u, c) in g[v].iter() { for (i, &s) in s.iter().enumerate().rev() { if s == c { a[i] = a[i + 1].max(down[u][i]).max(down[u][i + 1] + 1); } else { a[i] = a[i + 1].max(down[u][i]); } } memo.push(a.clone()); } down[v] = memo.last().unwrap().clone(); let mut b = vec![0; w + 1]; for &(u, c) in g[v].iter().rev() { memo.pop(); let tl = memo.last().unwrap(); for (i, &s) in s.iter().enumerate() { if s == c { b[i + 1] = b[i].max(up[u][i + 1]).max(up[u][i] + 1); } else { b[i + 1] = b[i].max(up[u][i + 1]); } } ans = ans.max(b.iter().zip(tl.iter()).map(|p| *p.0 + *p.1).max().unwrap()); } up[v] = b.clone(); g[v].reverse(); } } ans = ans.max(*down.iter().flatten().chain(up.iter().flatten()).max().unwrap()); println!("{}", ans); } fn main() { run(); }