#include <bits/stdc++.h>
using namespace std;
int sz[200007];long long all = 0;
int vis[200007];
vector<int> adj[200007];
bool ss = 0;
int zz[200007];
string s;
int bra = 0;
int c = 0;
int ch = 0;
void calc(int no,int pr){
if(ss){
if(s[no-1]=='('){bra++;ch--;ch=max(ch,0);}
if(s[no-1]==')'){bra--;ch++;}
if(bra>=0&&ch==0)zz[bra]++;
}else{
if(s[no-1]=='('){bra++;ch++;}
if(s[no-1]==')'){bra--;ch--;ch=max(ch,0);}
if(bra<=0&&ch==0){
all+=zz[-bra];
//cout<<no<<"pp"<<zz[-bra]<<"\n";
}
if(bra==0&&ch==0)c++;
}
for(auto i:adj[no]){
if(i==pr||vis[i])continue;
calc(i,no);
}
}
int dfs(int no,int pr){
sz[no] = 1;
for(auto i:adj[no]){
if(i==pr||vis[i]!=0)continue;
sz[no]+=dfs(i,no);
}
return sz[no];
}
int get_centroid(int no,int ss,int pr){
for(auto i:adj[no]){
if(pr==i||vis[i]!=0)continue;
if(sz[i]*2>ss){
return get_centroid(i,ss,no);
}
}
return no;
}
void centroid(int no){
int cen = get_centroid(no,dfs(no,-1),-1);
for(int i = 0;i<=sz[no]+5;i++){
zz[i] = 0;
}
vector<int> v;
vis[cen] = 1;
c = 0;
for(auto i:adj[cen]){
if(vis[i])continue;
v.push_back(i);
ss = 0;
ch = (s[cen-1]=='('?1:0);
bra = (s[cen-1]=='('?1:-1);
calc(i,-1);
//cout<<all<<" "<<i<<endl;
bra = 0;
ch = 0;
ss = 1;
calc(i,-1);
}
all+=c;
if(s[cen-1]==')')all+=zz[1];
for(int i = 0;i<=sz[no]+5;i++){
zz[i] = 0;
}
for(int i = v.size()-1;i>=0;i--){
ss = 0;
bra = (s[cen-1]=='('?1:-1);
ch =(s[cen-1]=='('?1:0);
calc(v[i],-1);
bra = 0;
ch = 0;
ss = 1;
calc(v[i],-1);
}
//cout<<cen<<"hh"<<all<<endl;
for(auto i:adj[cen]){
if(vis[i])continue;
centroid(i);
}
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n;
cin>>n>>s;
for(int i = 0;i<n-1;i++){
int a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
centroid(1);
cout<<all<<endl;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
5076 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
80 ms |
34596 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
5076 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |