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
| #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define maxn 2000005 #define put() putchar('\n') #define Tp template<typename T> #define Ts template<typename T,typename... Ar> using namespace std; Tp void read(T &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; #define fi first #define se second #define mk make_pair const int mod=1e9+7; int power(int x,int y=mod-2) { int sum=1; while (y) { if (y&1) sum=sum*x%mod; x=x*x%mod;y>>=1; } return sum; } int a[maxn]; int buff[maxn*2],*f[maxn],*fp=buff; int bt[maxn*2],*t[maxn],*tp=bt; int deep[maxn],son[maxn],top[maxn]; vector<int>to[maxn]; void dfs1(int x,int pre) { deep[x]=1; for (auto y:to[x]) if (y^pre) { dfs1(y,x); deep[x]=max(deep[x],deep[y]+1); if (deep[x]==deep[y]+1) son[x]=y; } } int ans,n; void update(int x,int p) { p=min(deep[x],p); int s=0,i; for (i=top[x];i<=p;i++) { s+=t[x][i]; if (f[x][i]) f[x][i]+=s; t[x][i]=0; } if (p+1<=deep[x]) t[x][p+1]+=s; top[x]=p+1; } void dfs2(int x,int pre) { int i; if (son[x]) { int y=son[x],i; f[y]=f[x]+a[x]; t[y]=t[x]+a[x]; dfs2(y,x); if (a[x]==-1) { update(son[x],1); f[y][0]=0; } } for (auto y:to[x]) if (y!=son[x]&&y!=pre) { f[y]=fp+deep[y]+2,fp+=deep[y]*2+4; t[y]=tp+deep[y]+2,tp+=deep[y]*2+4; dfs2(y,x); update(y,deep[y]); update(x,deep[y]+1); if (a[x]==1) { for (i=0;i<=deep[y];i++) f[x][i+1]+=f[y][i]; } else { for (i=1;i<=deep[y];i++) f[x][i-1]+=f[y][i]; } } if (a[x]==1&&!f[x][1]) { update(x,1); f[x][1]=1; if (f[x][0]) f[x][0]++; if (deep[x]>=2) t[x][2]++,top[x]=0; } else t[x][0]++,top[x]=0; if (f[x][0]) ans=max(ans,f[x][0]+t[x][0]); } signed main(void){ int i,x,y;char ch; read(n); for (cin>>ch,i=1;i<=n;i++) { if (ch==')') a[i]=1; else a[i]=-1; ch=getchar(); } for (i=1;i<n;i++) { read(x),read(y); to[x].push_back(y); to[y].push_back(x); } dfs1(1,0); f[1]=fp+deep[1]+2,fp+=deep[1]*2+4; t[1]=tp+deep[1]+2,tp+=deep[1]*2+4; dfs2(1,0); printf("%d\n",ans); return 0; }
|