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 mp make_pair
#define pb push_back
#define st first
#define nd second
typedef long long ll;
typedef pair < int , int > pp;
const int mod = 1e9 + 7;
const int N = 3e5 + 5;
vector < int > V[N];
int sz[N],U[N],T[N+N],A[N],C,n,i,x,y;
char s[N];
ll ans;
void f(int x, int p, int n){
sz[x] = 1; int h=1;
for(auto y : V[x]){
if(U[y] || y == p) continue;
f(y,x,n);
sz[x] += sz[y];
if(sz[y] > n/2) h=0;
}
if(h && n-sz[x] <= n/2) C=x;
}
vector < int > v[N];
int node;
void g(int x, int p, int t, int mn, int mx){
sz[x] = 1;
t += A[x];
mn = min(mn , t);
mx = max(mx , t);
if(!node && t == mx && A[x] == 1) ans += T[t];
if(node && t == mn && t <= 0) { v[node].pb(-t); T[-t]++; }
for(auto y : V[x]){
if(U[y] || y == p) continue;
g(y,x,t,mn,mx);
sz[x] += sz[y];
}
}
void slv(int x, int n){
f(x,0,n);
x = C;
U[x] = 1;
if(A[x] == -1) T[1]++;
for(auto y : V[x]){
if(U[y]) continue;
node = y;
g(y,x,A[x],A[x],A[x]);
}
node = 0;
if(A[x] == 1) ans += T[0];
for(auto y : V[x]){
if(U[y]) continue;
for(auto t : v[y]) T[t]--;
g(y,x,0,0,0);
for(auto t : v[y]) T[t]++;
}
if(A[x] == -1) T[1]--;
for(auto y : V[x]){
if(U[y]) continue;
for(auto t : v[y]) T[t]--;
v[y].clear();
}
//cout << x << " " << ans << " ss\n";
//exit(0);
for(auto y : V[x]) if(!U[y]) slv(y,sz[y]);
}
int main(){
scanf("%d %s",&n,s+1);
for(i=1;i<=n;i++) A[i] = s[i] == '(' ? 1 : -1;
for(i=2;i<=n;i++){
scanf("%d%d",&x,&y);
V[x].pb(y); V[y].pb(x);
}
slv(1,n);
printf("%lld",ans);
return 0;
}
Compilation message (stderr)
zagrade.cpp: In function 'int main()':
zagrade.cpp:79:10: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %s",&n,s+1);
~~~~~^~~~~~~~~~~~~~~~
zagrade.cpp:82:14: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&x,&y);
~~~~~^~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |