#include #define show(x) cerr << #x << " = " << (x) << endl; using namespace std; template inline ostream& operator<<(ostream& os, const vector& v) { os << "["; for (const auto& p : v) { os << p << ","; } return (os << "]" << endl); } template inline ostream& operator<<(ostream& os, const pair& p) { return (os << "<" << p.first << "," << p.second << ">"); } int main() { int N; cin >> N; string S; cin >> S; using P = pair; vector

data(N); int L = 0, R = 0; int depth = 0; int ans = 0; for (int i = 0; i < N; i++) { if (S[i] == ')') { if (R == 0) { L++; } else { depth++; R--; } } else { R++; } ans += depth; data[i] = {L, R}; } sort(data.begin(), data.end(), [](const P& p1, const P& p2) { return (p1.first != p2.first) ? p1.first < p2.first : p1.second > p2.second; }); R = 0; for (int i = 0; i < N; i++) { const int L = data[i].first; const int use = min(R, L); R -= use; ans += use; R += data[i].second; } cout << 2 * ans << endl; return 0; }