제출 #480307

#제출 시각아이디문제언어결과실행 시간메모리
480307BERNARB01Zagrade (COI17_zagrade)C++17
40 / 100
153 ms24376 KiB
#include <bits/stdc++.h>

using namespace std;

const int N = (int) 3e5 + 9;

int n;
string a;
vector<int> g[N];

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> a;
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    --u; --v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  if (n <= 1000) {
    function<int(int, int, int)> DFS = [&](int v, int pr, int bal) {
      bal += (a[v] == '(') - (a[v] == ')');
      if (bal < 0) {
        return 0;
      }
      int ret = !bal;
      for (int u : g[v]) {
        if (u == pr) {
          continue;
        }
        ret += DFS(u, v, bal);
      }
      return ret;
    };
    int ans = 0;
    for (int i = 0; i < n; i++) {
      ans += DFS(i, -1, 0);
    }
    cout << ans << '\n';
  } else {
    long long ans = 0;
    for (int itr = 0; itr < 2; itr++) {
      reverse(a.begin(), a.end());
      vector<pair<char, int>> stk;
      for (int i = 0; i < n; i++) {
        if (a[i] == ')') {
          while (!stk.empty() && stk.back().first == ')') {
            stk.pop_back();
          }
          if (stk.empty()) {
            continue;
          }
          stk.back().first = ')';
          stk.back().second += 1;
          ans += stk.back().second;
        } else {
          if (stk.empty()) {
            stk.push_back({'(', 0});
            continue;
          }
          if (stk.back().first == '(') {
            stk.push_back({'(', 0});
            continue;
          }
          stk.push_back({'(', stk.back().second});
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...