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>
#define fi first
#define se second
#define mp make_pair
#define TASK ""
#define ALL(x) (x).begin(), (x).end()
using namespace std;
template <typename T1, typename T2> bool mini(T1 &a, T2 b) {
if (a > b) {a = b; return true;} return false;
}
template <typename T1, typename T2> bool maxi(T1 &a, T2 b) {
if (a < b) {a = b; return true;} return false;
}
const int N = 3e5 + 5;
const int oo = 1e9;
const long long ooo = 1e18;
const int mod = 1e9 + 7; // 998244353;
const long double pi = acos(-1);
vector <int> adj[N];
long long ans;
int cnt[N];
int sz[N];
int a[N];
int n;
bool bk[N];
int dfs(int u, int p = -1) {
int &res = sz[u];
res = 1;
for (int v : adj[u])
if (v != p && !bk[v])
res += dfs(v, u);
return res;
}
int getcen(int u, int S, int p = -1) {
for (int v : adj[u])
if (v != p && !bk[v] && sz[v] * 2 >= S)
return getcen(v, S, u);
return u;
}
void dfs(int u, int cur, int minval, int p = -1) {
cur += a[u];
mini(minval, cur);
if (cur == minval && cur <= 0)
ans += cnt[-cur];
for (int v : adj[u])
if (v != p && !bk[v])
dfs(v, cur, minval, u);
}
void solve(int u, int cur, int minval, int p = -1) {
cur += a[u];
minval += a[u];
mini(minval, 0);
if (minval == 0)
cnt[cur]++;
for (int v : adj[u])
if (v != p && !bk[v])
solve(v, cur, minval, u);
}
void dfs1(int u, int cur = 0, int p = -1) {
cur += a[u];
if (cur < 0)
return;
if (cur == 0)
ans++;
for (int v : adj[u])
if (v != p && !bk[v])
dfs1(v, cur, u);
}
void centroid(int u) {
int s = dfs(u);
int cen = getcen(u, s);
bk[cen] = true;
// cerr << "centroid: " << cen << "\n";
for (int v : adj[cen]) if (!bk[v]) {
dfs(v, 0, 0, cen);
solve(v, a[cen], min(a[cen], 0), cen);
}
ans += cnt[0];
for (int i = 0; i <= s; i++)
cnt[i] = 0;
reverse(ALL(adj[cen]));
for (int v : adj[cen]) if (!bk[v]) {
dfs(v, 0, 0, cen);
solve(v, a[cen], min(a[cen], 0), cen);
}
for (int i = 0; i <= s; i++)
cnt[i] = 0;
dfs1(cen);
// cerr << ans << "\n";
for (int v : adj[cen]) {
if (!bk[v]) {
// cerr << cen << " " << v << "\n";
centroid(v);
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
#ifdef ONLINE_JUDGE
// freopen(TASK".inp","r",stdin);
// freopen(TASK".out","w",stdout);
#endif
cin >> n;
for (int i = 1; i <= n; i++) {
char c; cin >> c;
a[i] = (c == '(') ? 1 : -1;
}
for (int i = 1; i < n; i++){
int u,v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
centroid(1);
cout << ans;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |