結果
| 問題 |
No.1494 LCS on Tree
|
| コンテスト | |
| ユーザー |
沙耶花
|
| 提出日時 | 2021-04-30 22:43:35 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 1,474 ms / 2,000 ms |
| コード長 | 2,566 bytes |
| コンパイル時間 | 4,511 ms |
| コンパイル使用メモリ | 265,576 KB |
| 最終ジャッジ日時 | 2025-01-21 04:04:13 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 47 |
ソースコード
#include <stdio.h>
#include <atcoder/all>
#include <bits/stdc++.h>
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<vector<pair<int,char>>> E;
void dfs(int cur,int p,vector<vector<int>> &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<S.size();j++){
if(S[j]==c){
dp[cur][i+1] = min(dp[cur][i+1],j+1);
break;
}
}
}
}
}
int ans = 0;
using P = pair<int,int>;
using PP = pair<P,P>;
PP op(PP a,PP b){
PP ret;
array<P,5> 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<vector<int>> &dp,vector<vector<int>> &rdp){
segtree<PP,op,e> 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<int>(S.size()+1,Inf));
vector rdp(N,vector<int>(S.size()+1,Inf));
dfs(0,-1,dp);
/*
rep(i,N){
rep(j,S.size()+1){
cout<<dp[i][j]<<',';
}
cout<<endl;
}*/
reverse(S.begin(),S.end());
dfs(0,-1,rdp);
/*
rep(i,N){
rep(j,S.size()+1){
cout<<rdp[i][j]<<',';
}
cout<<endl;
}*/
dfs(0,-1,dp,rdp);
cout<<ans<<endl;
return 0;
}
沙耶花