#include <bits/stdc++.h>
using namespace std;
const int N = 3e5;
string s;
list<int> adj[N];
int n;
long long ans = 0;
map<int, int> m1, m2;
int dfs(int v, int p = -1, int d = INT32_MIN) {
bool check = true;
if (d != INT32_MIN) {
d += s[v] == ')' ? -1 : 1;
check = false;
if (s[v] == ')')
ans += m1[d + 1], m2[d]++;
else
ans += m2[d - 1], m1[d]++;
}
for (int i : adj[v]) {
if (i != p) {
if (d == INT32_MIN)
d = dfs(i, v) + (s[v] == ')' ? -1 : 1);
else
dfs(i, v, d);
if (check) {
check = false;
if (s[v] == ')')
ans += m1[d + 1], m2[d]++;
else
ans += m2[d - 1], m1[d]++;
}
}
}
if (d == INT32_MIN)
d = s[v] == ')' ? -1 : 1;
if (check) {
if (s[v] == ')')
ans += m1[d + 1], m2[d]++;
else
ans += m2[d - 1], m1[d]++;
}
return d;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> s;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--, v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0);
cout << ans;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
9 ms |
7420 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
171 ms |
55048 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
9 ms |
7420 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |