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>
#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
const int N = 3e5 + 10;
int n, sz[N], big[N], c[N], del[N];
vector <int> g[N];
void dfs(int u, int p) {
sz[u] = 1, big[u] = 0;
for (auto v: g[u]) {
if (v == p || del[v]) continue;
dfs(v, u);
sz[u] += sz[v];
if (sz[v] >= sz[big[u]]) big[u] = v;
}
}
int cnt[N * 2];
int centroid(int u) {
dfs(u, 0);
int num = sz[u] / 2;
while (sz[big[u]] > num) u = big[u];
return u;
}
void add(int u, int p, int s, int d) {
if (d >= 0) ++cnt[s + N];
for (auto v: g[u]) {
if (v == p || del[v]) continue;
add(v, u, s + c[v], min(d + c[v], c[v]));
}
}
long long ans;
void calc(int u, int p, int s, int d) {
if (d >= s) ans += cnt[N - s];
for (auto v: g[u]) {
if (v == p || del[v]) continue;
calc(v, u, s + c[v], min(d, s + c[v]));
}
}
void rev(int u, int p, int s, int d) {
if (d >= 0) --cnt[s + N];
for (auto v: g[u]) {
if (v == p || del[v]) continue;
rev(v, u, s + c[v], min(d + c[v], c[v]));
}
}
void build(int u) {
u = centroid(u);
if (c[u] >= 0) ++cnt[c[u] + N];
for (auto v: g[u]) {
if (del[v]) continue;
calc(v, u, c[v], min(0, c[v]));
add(v, u, c[u] + c[v], min({0, c[u] + c[v], c[v]}));
}
for (auto v: g[u]) {
if (del[v]) continue;
rev(v, u, c[u] + c[v], min({0, c[u] + c[v], c[v]}));
}
if (c[u] >= 0) --cnt[c[u] + N];
reverse(g[u].begin(), g[u].end());
for (auto v: g[u]) {
if (del[v]) continue;
calc(v, u, c[v], min(0, c[v]));
add(v, u, c[u] + c[v], min({0, c[u] + c[v], c[v]}));
}
ans += cnt[N];
for (auto v: g[u]) {
if (del[v]) continue;
rev(v, u, c[u] + c[v], min({0, c[u] + c[v], c[v]}));
}
del[u] = 1;
for (auto v: g[u])
if (!del[v]) build(v);
}
int main() {
ios :: sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int u = 1; u <= n; ++u) {
char ch;
cin >> ch;
c[u] = (ch == '(' ? 1 : -1);
}
for (int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
build(1);
cout << ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |