Submission #232340

#TimeUsernameProblemLanguageResultExecution timeMemory
232340amoo_safarZagrade (COI17_zagrade)C++14
100 / 100
663 ms42224 KiB
#include <bits/stdc++.h> #define pb push_back #define F first #define S second #define all(x) x.begin(), x.end() #define debug(x) cerr << #x << " : " << x << '\n' using namespace std; typedef long long ll; typedef long double ld; typedef string str; typedef pair<ll, ll> pll; const ll Mod = 1000000007LL; const int N = 3e5 + 10; const ll Inf = 2242545357980376863LL; const ll Log = 30; int n, a[N], mk[N]; vector<int> G[N]; ll ans = 0; int sz[N]; int DFS(int u, int p){ sz[u] = 1; for(auto adj : G[u]) if(adj != p && !mk[adj]) sz[u] += DFS(adj, u); return sz[u]; } vector<int> V2, V3; void DFS2(int u, int p, int sm, int mn){ sm += a[u]; mn = min(mn, sm); if(sm == mn){ if(mn == 0) ans ++; V2.pb(mn); } for(auto adj : G[u]) if(adj != p && !mk[adj]) DFS2(adj, u, sm, mn); } int tr; void DFS3(int u, int p, int sm, int mn){ sm -= a[u]; mn = min(mn, sm); if(sm == mn){ if(tr && mn == -1) ans ++; V3.pb(mn); } for(auto adj : G[u]) if(adj != p && !mk[adj]) DFS3(adj, u, sm, mn); } int cnt2[N], cnt3[N]; void Centroid(int u){ int m = DFS(u, -1); int fl = 1; int cen = u; while(fl){ fl = 0; for(auto adj : G[cen]){ if(!mk[adj] && sz[adj] < sz[cen] && sz[adj] + sz[adj] >= m){ cen = adj; fl = 1; break; } } } //debug(cen); for(int i = 0; i <= m; i++) cnt2[i] = 0, cnt3[i] = 0; mk[cen] = 1; for(auto adj : G[cen]){ if(mk[adj]) continue; V2.clear(); V3.clear(); DFS2(adj, cen, a[cen], min(a[cen], 0)); if(a[cen] == -1) tr = 1; else tr = 0; DFS3(adj, cen, 0, 0); for(auto &x : V2) ans += cnt3[-x]; for(auto &x : V3) ans += cnt2[-x]; for(auto &x : V2) cnt2[-x] ++; for(auto &x : V3) cnt3[-x] ++; } //debug(ans); for(auto adj : G[cen]){ if(mk[adj]) continue; Centroid(adj); } return ; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; char c; for(int i = 1; i <= n; i++){ cin >> c; a[i] = (c == '(' ? 1 : -1); } int u, v; for(int i = 1; i < n; i++){ cin >> u >> v; G[u].pb(v); G[v].pb(u); } Centroid(1); cout << ans << '\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...