제출 #209711

#제출 시각아이디문제언어결과실행 시간메모리
209711alishahali1382Zagrade (COI17_zagrade)C++14
100 / 100
1018 ms43712 KiB
#include <bits/stdc++.h> #pragma GCC optimize ("O2") #pragma GCC optimize ("unroll-loops") //#pragma GCC optimize("no-stack-protector,fast-math") using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<pii, int> piii; typedef pair<ll, ll> pll; #define debug(x) cerr<<#x<<'='<<(x)<<endl; #define debugp(x) cerr<<#x<<"= {"<<(x.first)<<", "<<(x.second)<<"}"<<endl; #define debug2(x, y) cerr<<"{"<<#x<<", "<<#y<<"} = {"<<(x)<<", "<<(y)<<"}"<<endl; #define debugv(v) {cerr<<#v<<" : ";for (auto x:v) cerr<<x<<' ';cerr<<endl;} #define all(x) x.begin(), x.end() #define pb push_back #define kill(x) return cout<<x<<'\n', 0; const ld eps=1e-7; const int inf=1000000010; const ll INF=10000000000000010LL; const int mod = 1000000007; const int MAXN = 300010, LOG=20; int n, m, k, u, v, x, y, t, a, b; ll ans; int A[MAXN]; int sz[MAXN]; bool dead[MAXN]; int cnt[MAXN]; vector<int> G[MAXN]; int dfs1(int node, int par){ sz[node]=1; for (int v:G[node]) if (v!=par && !dead[v]) sz[node]+=dfs1(v, node); return sz[node]; } int Centroid(int node, int par, int n){ for (int v:G[node]) if (v!=par && !dead[v] && 2*sz[v]>n) return Centroid(v, node, n); return node; } void dfs2(int node, int par, int sum, int mn){ mn=min(mn, sum+=A[node]); //cerr<<"dfs2 "<<node<<" : "<<sum<<' '<<mn<<endl; if (mn==sum) ans+=cnt[-sum]; for (int v:G[node]) if (!dead[v] && v!=par) dfs2(v, node, sum, mn); } void dfs3(int node, int par, int sum, int mn){ sum+=A[node]; mn=min(A[node], mn+A[node]); mn=min(mn, 0); if (!mn) cnt[sum]++; for (int v:G[node]) if (!dead[v] && v!=par) dfs3(v, node, sum, mn); } void Decompose(int node){ int root=Centroid(node, node, dfs1(node, node)); dead[root]=1; fill(cnt, cnt+sz[node]+1, 0); cnt[0]=1; for (int v:G[root]) if (!dead[v]){ dfs2(v, root, A[root], min(0, A[root])); dfs3(v, root, 0, 0); } if (A[root]==-1) ans+=cnt[1]; reverse(all(G[root])); fill(cnt, cnt+sz[node]+1, 0); for (int v:G[root]) if (!dead[v]){ dfs2(v, root, A[root], min(0, A[root])); dfs3(v, root, 0, 0); } for (int v:G[root]) if (!dead[v]) Decompose(v); } int main(){ ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); cin>>n; for (int i=1; i<=n; i++){ char ch; cin>>ch; A[i]=(ch=='('?+1:-1); } for (int i=1; i<n; i++){ cin>>u>>v; G[u].pb(v); G[v].pb(u); } Decompose(1); cout<<ans<<'\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...