This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
#define f first
#define s second
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 3e5+5;
vector<pii> up[maxn];
vector<pii> down[maxn];
vector<int> tree[maxn];
int A[maxn];
int sum[maxn], subsz[maxn], col[maxn], vis[maxn], mx[maxn];
vector<int> csum[maxn];
int n;
void predfs(int x, int p){
subsz[x]=1;
for(auto v: tree[x]){
if(v == p || vis[v])continue;
predfs(v, x);
subsz[x]+=subsz[v];
}
}
int gtcen(int x, int p, int tot){
int re = 0;
mx[x]=0;
for(auto v: tree[x]){
if(v == p || vis[v])continue;
int tmp = gtcen(v, x, tot);
if(mx[tmp] < mx[re])re = tmp;
mx[x] = max(mx[x], subsz[v]);
}
mx[x]=max(mx[x], tot-subsz[x]);
if(mx[x] < mx[re])re=x;
return re;
}
void dfs(int x, int p, int ss, int mn, int mn2, int color, int rr){
//cout << x << " " << ss << endl;
if(mn2 >= 0){
up[ss+A[rr]].push_back({color, rr});
//cout << "up " << ss+A[rr] << " " << x << " " << rr << endl;
}
if(ss == mn && ss <= 0){
down[-ss].push_back({color, rr});
//cout << "down " << -ss << " " << x << " " << rr << endl;
}
for(auto v: tree[x]){
if(v == p || vis[v])continue;
dfs(v, x, ss+A[v], min(ss+A[v], mn), min(0, mn2 + A[v]), color, rr);
}
}
int build(int x){
predfs(x, 0);
x = gtcen(x, 0, subsz[x]);
vis[x]=1;
int cc = 0;
if(A[x] > 0)up[1].push_back({-1, x});
down[0].push_back({-1, x});
for(auto v: tree[x]){
if(vis[v])continue;
dfs(v, x, A[v], min(0, A[v]), min({0, A[v], A[v]+A[x]}), cc++, x);
}
csum[x].assign(cc, 0);
for(auto v: tree[x]){
if(!vis[v]){
int tmp = build(v);
//cout << x << " " << tmp << endl;
}
}
return x;
}
int main(){
ll ans = 0;
cin >> n;
mx[0]=n;
for(int i = 1; i <= n; i++){
char c;
cin >> c;
if(c == '(')A[i]=1;
else A[i]=-1;
}
for(int i = 1; i < n; i++){
int a, b;
cin >> a >> b;
tree[a].push_back(b);
tree[b].push_back(a);
}
build(1);
for(int i = 0; i <= n; i++){
for(auto v: down[i]){
sum[v.s]++;
if(v.f >= 0)csum[v.s][v.f]++;
}
for(auto v: up[i]){
ans += sum[v.s];
if(v.f >= 0)ans-=csum[v.s][v.f];
}
for(auto v: down[i]){
sum[v.s] = 0;
if(v.f >= 0)csum[v.s][v.f]=0;
}
}
cout << ans;
}
Compilation message (stderr)
zagrade.cpp: In function 'int build(int)':
zagrade.cpp:74:17: warning: unused variable 'tmp' [-Wunused-variable]
74 | int tmp = build(v);
| ^~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |