제출 #586772

#제출 시각아이디문제언어결과실행 시간메모리
586772MilosMilutinovicZagrade (COI17_zagrade)C++14
100 / 100
1052 ms57668 KiB
/** * author: wxhtzdy * created: 30.06.2022 10:05:38 **/ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; string s; cin >> s; vector<vector<int>> g(n); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; --u; --v; g[u].push_back(v); g[v].push_back(u); } vector<bool> was(n); vector<int> sz(n); function<void(int, int)> Dfs = [&](int v, int pr) { sz[v] = 1; for (int u : g[v]) { if (u == pr || was[u]) { continue; } Dfs(u, v); sz[v] += sz[u]; } }; function<int(int, int, int)> Find = [&](int v, int pr, int n) { for (int u : g[v]) { if (u == pr || was[u] || sz[u] * 2 < n) { continue; } return Find(u, v, n); } return v; }; map<int, int> cnt; long long ans = 0; function<void(int, int, int, int, int)> Go = [&](int v, int pr, int bal, int mn, int f) { int me = (s[v] == '(' ? 1 : -1); bal += me; mn = min(me, me + mn); if (mn >= 0) { cnt[bal] += f; } for (int u : g[v]) { if (u == pr || was[u]) { continue; } Go(u, v, bal, mn, f); } }; function<void(int, int, int, int)> Run = [&](int v, int pr, int bal, int mn) { bal += (s[v] == '(' ? +1 : -1); mn = min(mn, bal); if (mn == 0 && bal == 0) { ans += 1; } if (-bal + mn >= 0) { ans += cnt[-bal]; } for (int u : g[v]) { if (u == pr || was[u]) { continue; } Run(u, v, bal, mn); } }; function<void(int)> Solve = [&](int v) { Dfs(v, v); v = Find(v, v, sz[v]); was[v] = true; cnt.clear(); for (int u : g[v]) { if (was[u]) { continue; } Go(u, v, 0, 1, +1); } if (s[v] == ')') { ans += cnt[1]; } for (int u : g[v]) { if (was[u]) { continue; } int me = (s[v] == '(' ? +1 : -1); Go(u, v, 0, 1, -1); Run(u, v, me, me); Go(u, v, 0, 1, +1); } for (int u : g[v]) { if (!was[u]) { Solve(u); } } }; Solve(0); cout << ans << '\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...