This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
#pragma GCC optimize("O2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2,fma")
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int , int> pii;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int maxn = 3e5 + 10;
const ll mod = 1e9+7;
const ld PI = acos((ld)-1);
#define pb push_back
#define endl '\n'
#define dokme(x) cout << x , exit(0)
#define migmig ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define ms(x , y) memset(x , y , sizeof x)
ll pw(ll a, ll b, ll md = mod){ll res = 1;while(b){if(b&1){res=(a*res)%md;}a=(a*a)%md;b>>=1;}return(res);}
int n , op[maxn] , sz[maxn] , cnt[maxn];
vector < int > adj[maxn];
string s;
bool hide[maxn];
ll ans = 0;
void plant(int v ,int p = 0){
sz[v] = 1;
for(auto u : adj[v])if(!hide[u] and u^p)
plant(u , v) , sz[v] += sz[u];
}
int cen(int v , int n , int par = 0 , bool found = 0){
while(!found){
found = 1;
for(auto u : adj[v])if(u ^ par and !hide[u] and sz[u] * 2 > n){
par = v , v = u , found = 0;
break;
}
}
return(v);
}
void add(int v , int h , int mx){
h += op[v];
if(h >= mx)cnt[h] ++ , mx = h;
hide[v] = 1;
for(auto u : adj[v])if(!hide[u])
add(u , h , mx);
hide[v] = 0;
}
void rm(int v , int h , int mx){
h += op[v];
if(h >= mx)cnt[h] -- , mx = h;
hide[v] = 1;
for(auto u : adj[v])if(!hide[u])
rm(u , h , mx);
hide[v] = 0;
}
ll chk(int v , int h = 0 , int mn = 0){
h += op[v];
ll ans = 0;
if(h <= mn)ans += cnt[-h] , mn = h;
hide[v] = 1;
for(auto u : adj[v])if(!hide[u])
ans += chk(u , h , mn);
hide[v] = 0;
return ans;
}
ll solve(int v){
ll ans = 0;
if(op[v] == 1){
cnt[1] ++;
for(auto u : adj[v])if(!hide[u])
add(u , 1 , 1);
for(auto u : adj[v])if(!hide[u])
rm(u , 1 , 1), ans += chk(u) , add(u , 1 , 1);
for(auto u : adj[v])if(!hide[u])
rm(u , 1 , 1);
cnt[1] --;
}
else{
for(auto u : adj[v])if(!hide[u])
add(u , -1 , 0);
ans += cnt[0];
for(auto u : adj[v])if(!hide[u])
rm(u , -1 , 0), ans += chk(u) , add(u , -1 , 0);
for(auto u : adj[v])if(!hide[u])
rm(u , -1 , 0);
}
return(ans);
}
void decomp(int v){
plant(v);
v = cen(v , sz[v]);
hide[v] = 1;
ans += solve(v);
for(auto u : adj[v])
if(!hide[u])decomp(u);
}
int32_t main(){
migmig;
cin >> n >> s;
for(int i = 1 ; i <= n ; i ++)op[i] = (s[i - 1] == '(' ? 1 : -1);
for(int i = 1 ; i < n ; i ++){
int u , v;
cin >> u >> v;
adj[u].pb(v) , adj[v].pb(u);
}
decomp(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... |