/* I LOVE CATTUONG */
//
#include <bits/stdc++.h>
#define CatTuong ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
#define int long long
const int N=5e4+5;
const int base=311;
const int MOD=1e9+7;
int sz[N],n,H,h[N],preH[N],suffH[N],powB[N],mx_h,ans;
char a[N];
bool is_cen[N];
map<int,bool>mp[N];
vector<int>g[N];
//abc cba
//palin H abc*powb[H-sz(len)]-cba
int add(int x,int y){return (x+y)%MOD;}
int mul(int x,int y){return (x*y)%MOD;}
int sub(int x,int y){return ((x-y)+MOD)%MOD;}
void DFS(int u,int p){
sz[u]=1;
for(auto v:g[u]){
if(v!=p && !is_cen[v]){
DFS(v,u);
sz[u]+=sz[v];
}
}
}
int find_cen(int u,int p,int tree_sz){
for(auto v:g[u]){
if(v!=p && !is_cen[v] && sz[v]>tree_sz/2){
return find_cen(v,u,tree_sz);
}
}
return u;
}
int get(int u,int p){
h[u]=h[p]+1;
if(h[u]>H)
return 0;
mx_h=max(mx_h,h[u]);
preH[h[u]]=add(mul(preH[h[u]-1],base),a[u]);
suffH[h[u]]=add(suffH[h[u]-1],mul(a[u],powB[h[u]-1]));
int tmp=sub(mul(suffH[h[u]],powB[H-h[u]]),preH[h[u]]);
if(preH[h[u]]==suffH[h[u]] && h[u]==H)
return 1;
if(mp[H-h[u]].find(tmp)!=mp[H-h[u]].end())
return 1;
for(auto v:g[u]){
if(v!=p && !is_cen[v]){
if(get(v,u))
return 1;
}
}
return 0;
}
void update(int u,int p){
h[u]=h[p]+1;
if(h[u]>H)
return;
mx_h=max(mx_h,h[u]);
preH[h[u]]=add(mul(preH[h[u]-1],base),a[u]);
suffH[h[u]]=add(suffH[h[u]-1],mul(a[u],powB[h[u]-1]));
int tmp=sub(mul(suffH[h[u]],powB[H-h[u]]),preH[h[u]]);
mp[h[u]][tmp]=1;
for(auto v:g[u]){
if(v!=p && !is_cen[v])
update(v,u);
}
}
bool build_cen(int u){
DFS(u,-1);
int cen=find_cen(u,-1,sz[u]);
is_cen[cen]=true;
for(auto v:g[cen]){
if(v!=cen && !is_cen[v]){
h[cen]=1;
suffH[1]=preH[1]=a[cen];
if(get(v,cen))
return 1;
h[cen]=preH[0]=suffH[0]=0;
update(v,cen);
}
}
for(int i=0;i<=mx_h;++i){
mp[i].clear();
}
mx_h=0;
for(auto v:g[cen]){
if(!is_cen[v]){
if(build_cen(v))
return 1;
}
}
return 0;
}
bool check(int x){
for(int i=1;i<=n;++i){
mp[i].clear();
is_cen[i]=false;
}
H=x;
return build_cen(1);
}
signed main(){
#define Tuong "LAMPICE"
// freopen(Tuong".inp","r",stdin);
// freopen(Tuong".out","w",stdout);
CatTuong
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
}
for(int i=1;i<n;++i){
int u,v;cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
powB[0]=1;
for(int i=1;i<=n;++i)
powB[i]=mul(powB[i-1],base);
int lo=0,hi=n;
while(hi>=lo){
int mid=(hi+lo)>>1;
if(check(2*mid) && 2*mid<=n){
ans=2*mid;
lo=mid+1;
}
else
hi=mid-1;
}
lo=0,hi=n;
while(hi>=lo){
int mid=(hi+lo)>>1;
if(check(2*mid+1) && 2*mid+1<=n){
ans=max(ans,2*mid+1);
lo=mid+1;
}
else
hi=mid-1;
}
cout<<ans;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |