#include using namespace std; #define DEBUG(x) cout<<#x<<": "< #define vl vector #define vii vector< vector > #define vll vector< vector > #define vs vector #define pii pair #define pis pair #define psi pair #define pll pair #define fi first #define se second #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define all(c) c.begin(),c.end() #define in(x, a, b) a <= x && x < b const int inf = 1000000001; const ll INF = 2e18; const ll MOD = 1000000007; //const ll mod = 1000000009; const double pi = 3.14159265358979323846; #define Sp(p) cout< min(b.second, a.first); } int main() { int n; cin >> n; string s; cin >> s; ll ans = 0; vector num(n); string t; pll numnow = pll(0, 0); int delnow = 0; rep (i, n) { t.push_back(s[i]); if (s[i] == '(') { numnow.first++; } else { numnow.second++; } if (t.size() >= 2 && t.substr(t.size() - 2, 2) == "()") { delnow++; t.pop_back(); t.pop_back(); numnow.first--; numnow.second--; } ans += delnow; num[i] = numnow; } sort(all(num), cmp); ll now = 0; rep (i, n) { ll used = min(now, num[i].first); ans += used; now -= used; now += num[i].second; } cout << ans * 2 << endl; }