#include #include #include using namespace std; using namespace atcoder; using mint = modint1000000007; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000000 int N; string S; vector>> E; void dfs(int cur,int p,vector> &dp){ dp[cur][0] = 0; char c = '0'; rep(i,E[cur].size()){ int to = E[cur][i].first; if(to==p){ c = E[cur][i].second; continue; } dfs(to,cur,dp); rep(j,S.size()+1){ dp[cur][j] = min(dp[cur][j],dp[to][j]); } } if(c!='0'){ for(int i=S.size()-1;i>=0;i--){ if(dp[cur][i]==Inf)continue; for(int j=dp[cur][i];j; using PP = pair; PP op(PP a,PP b){ PP ret; array A = {a.first,a.second,b.first,b.second,make_pair(-Inf,-1)}; sort(A.rbegin(),A.rend()); ret.first = A[0]; for(int i=1;i<5;i++){ if(A[0].second!=A[i].second){ ret.second = A[i]; break; } } return ret; } PP e(){ return make_pair(make_pair(-Inf,-1),make_pair(-Inf,-1)); } void dfs(int cur,int p,vector> &dp,vector> &rdp){ segtree seg(S.size()+1); rep(i,E[cur].size()){ int to = E[cur][i].first; if(to==p)continue; dfs(to,cur,dp,rdp); } rep(i,E[cur].size()){ int to = E[cur][i].first; if(to==p)continue; rep(j,dp[to].size()){ if(dp[to][j]==Inf)continue; auto ret = seg.get(dp[to][j]); ret = op(ret,make_pair(make_pair(j,to),make_pair(-Inf,-1))); seg.set(dp[to][j],ret); ans = max(ans,j); } } rep(i,E[cur].size()){ int to = E[cur][i].first; if(to==p)continue; rep(j,dp[to].size()){ if(rdp[to][j]==Inf)continue; ans = max(ans,j); auto ret = seg.prod(0,(int)S.size() - rdp[to][j]+1); if(ret.first.second != to){ ans = max(ans,j + ret.first.first); } if(ret.second.second != to){ ans = max(ans,j + ret.second.first); } } } } int main(){ cin>>N>>S; E.resize(N); rep(i,N-1){ int u,v; char c; cin>>u>>v>>c; u--;v--; E[u].emplace_back(v,c); E[v].emplace_back(u,c); } vector dp(N,vector(S.size()+1,Inf)); vector rdp(N,vector(S.size()+1,Inf)); dfs(0,-1,dp); /* rep(i,N){ rep(j,S.size()+1){ cout<