結果
問題 | No.1494 LCS on Tree |
ユーザー |
![]() |
提出日時 | 2021-05-01 10:15:53 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 1,422 ms / 2,000 ms |
コード長 | 3,131 bytes |
コンパイル時間 | 1,578 ms |
コンパイル使用メモリ | 121,640 KB |
最終ジャッジ日時 | 2025-01-21 05:01:11 |
ジャッジサーバーID (参考情報) |
judge5 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 47 |
ソースコード
#include <iostream>#include <algorithm>#include <string>#include <vector>#include <cmath>#include <map>#include <queue>#include <iomanip>#include <set>#include <tuple>#define mkp make_pair#define mkt make_tuple#define rep(i,n) for(int i = 0; i < (n); ++i)#define all(v) v.begin(),v.end()using namespace std;typedef long long ll;const ll MOD=1e9+7;template<class T> void chmin(T &a,const T &b){if(a>b) a=b;}template<class T> void chmax(T &a,const T &b){if(a<b) a=b;}int main(){cin.tie(0);ios::sync_with_stdio(false);int N;cin>>N;string S;cin>>S;int M=S.size();vector<vector<pair<int,int>>> g(N);rep(i,N-1){int a,b;char c;cin>>a>>b>>c;a--;b--;int d=c-'a';g[a].push_back(mkp(b,d));g[b].push_back(mkp(a,d));}vector<vector<vector<int>>> last(2,vector<vector<int>>(M+1,vector<int> (26,-1)));for(int i=0;i<M;i++){for(int j=0;j<26;j++){last[0][i+1][j]=last[0][i][j];}last[0][i+1][S[i]-'a']=i;}reverse(all(S));for(int i=0;i<M;i++){for(int j=0;j<26;j++){last[1][i+1][j]=last[1][i][j];}last[1][i+1][S[i]-'a']=i;}reverse(all(S));auto solve = [&](vector<vector<int>> last) -> vector<vector<int>> {vector<vector<int>> dp(N,vector<int> (M+1,0));auto dfs = [&](auto &&dfs,int now,int par)->void{for(auto [nex,d]:g[now]){if(nex==par) continue;dfs(dfs,nex,now);for(int k=0;k<=M;k++) chmax(dp[now][k],dp[nex][k]);for(int k=0;k<=M;k++){int lt=last[k][d];if(lt==-1) continue;chmax(dp[now][k],dp[nex][lt]+1);}}for(int k=0;k<M;k++) chmax(dp[now][k+1],dp[now][k]);};dfs(dfs,0,-1);return dp;};vector<vector<int>> sp=solve(last[0]);vector<vector<int>> tp=solve(last[1]);auto calc_ans = [&](auto &&calc_ans,int now,int par)->int{vector<vector<pair<int,int>>> ss(M+1),tt(M+1);rep(i,M+1){ss[i].push_back(mkp(0,-1));tt[i].push_back(mkp(0,-2));}int res=0;for(auto [nex,d]:g[now]){if(nex==par) continue;chmax(res,calc_ans(calc_ans,nex,now));for(int k=0;k<=M;k++){int slt=last[0][k][d];int tlt=last[1][k][d];int sv=sp[nex][k],tv=tp[nex][k];if(slt!=-1) chmax(sv,sp[nex][slt]+1);if(tlt!=-1) chmax(tv,tp[nex][tlt]+1);if(k>0){chmax(sv,ss[k-1].back().first);chmax(tv,tt[k-1].back().first);}ss[k].push_back(mkp(sv,nex));tt[k].push_back(mkp(tv,nex));}}rep(i,M+1){sort(all(ss[i]));reverse(all(ss[i]));sort(all(tt[i]));reverse(all(tt[i]));}for(int k=0;k<=M;k++){auto [f,ft]=ss[k][0];auto [s,st]=tt[M-k][0];if(ft==st){if(tt[M-k].size()>=2) chmax(res,f+tt[M-k][1].first);if(ss[k].size()>=2) chmax(res,s+ss[k][1].first);}else{chmax(res,f+s);}}return res;};int ans=calc_ans(calc_ans,0,-1);cout<<ans<<endl;return 0;}