1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
| #include<bits/stdc++.h> using namespace std; typedef long long LL; typedef vector<int> VI; const int N=3e5+5; const int NN=6e5+5; LL dp[N][4][4]; int ss[4],n,m,C;char st[10]; int vis[300]; struct node{ int y,next; }a[NN];int len,las[N]; void ins(int x,int y){a[++len]={y,las[x]};las[x]=len;} bool pd(int x,int y){ assert(m==2); return (x==ss[1] && y==ss[2]) || (x==ss[2] && y==ss[1]); } bool pd(int x,int y,int z){ assert(m==3); return (x==ss[1] && y==ss[2] && z==ss[3]) || (x==ss[3] && y==ss[2] && z==ss[1]); } LL count(LL c1,LL c2,int fc){ assert(C>1); LL tmp=0; if(C==2){ if(pd(1,ss[2],1)==1)tmp+=c1*(c1-1)/2; if(pd(1,ss[2],2)==1)tmp+=c1*c2; if(pd(1,ss[2],fc)==1)tmp+=c1; if(pd(2,ss[2],fc))tmp+=c2; } else{ if(fc==1 || fc==3){ LL c3=(c1+1)/2; tmp+=c3*(c1-c3)+c3; } else{ LL c3=c1/2; tmp+=c3*(c1-c3); } } return tmp; } LL sta[N];int top; VI son[N]; void dfs(int x,int fa){ for(int k=las[x];k;k=a[k].next){ int y=a[k].y;if(y==fa)continue; son[x].push_back(y); dfs(y,x); } if(m==2){ for(int i=1;i<=C;i++){ LL now=0; for(auto y:son[x]){ LL tmp=0; for(int j=1;j<=C;j++){ tmp=max(dp[y][i][j],tmp); } now+=tmp; } for(int fc=1;fc<=C;fc++){ if(x!=1 && pd(i,fc))dp[x][fc][i]=now+1; else dp[x][fc][i]=now; } } } else{ assert(m==3); for(int i=1;i<=C;i++){ if(i!=ss[2]){ LL now=0; for(auto y:son[x]){ LL tmp=0; for(int j=1;j<=C;j++){ tmp=max(tmp,dp[y][i][j]); } now+=tmp; } for(int fc=1;fc<=C;fc++){ dp[x][fc][i]=now; } } else if(C==1){ LL siz=son[x].size(); for(auto y:son[x]) dp[x][1][1]+=dp[y][1][1]; dp[x][1][1]+=siz*(siz-1)/2; if(x!=1)dp[x][1][1]+=siz; } else{ top=0; LL ini=0; for(auto y:son[x]){ sta[++top]=dp[y][i][2]-dp[y][i][1]; assert(C!=3 || dp[y][i][1]==dp[y][i][3]); ini+=dp[y][i][1]; } sort(sta+1,sta+top+1,[](LL x,LL y){return x>y;}); for(int fc=1;fc<=C;fc++){ LL now=0,tmp=ini; for(int j=0;j<=top;j++){ if(x!=1)now=max( now , tmp+count(top-j,j,fc) ); else now=max( now , tmp+count(top-j,j,0) ); if(j!=top) tmp+=sta[j+1]; } dp[x][fc][i]=now; } } } } }
LL work(){ scanf("%d",&n); scanf("%s",st+1);m=strlen(st+1); for(int i=2;i<=n;i++){ int x,y;scanf("%d%d",&x,&y); ins(x,y);ins(y,x); } for(int i=1;i<=m;i++){ if(!vis[st[i]])vis[st[i]]=++C; ss[i]=vis[st[i]]; } if(m==1)return n; dfs(1,0);
LL ans=0; for(int i=1;i<=C;i++)ans=max(ans,dp[1][1][i]);
if(ss[1]==ss[m])ans*=2;
return ans; } int main(){ printf("%lld\n",work()); return 0; }
|