#include #include #include using namespace std; int main() { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0,ans=0; string s; cin >> a; cin >> s; int z[100001] = {}; z[0] = 0; for (b = 1; b <= a; b++) { if (s[b - 1] == '(') { z[b] += z[b - 1] + 1; /*if (z[b - 1]<0) { e++; } else*/ if(z[b - 1]>=0) { f++; } ans += e; } else if (s[b - 1] == ')') { if (z[b - 1]>0) { e++; } else if (z[b - 1] <= 0) { g++; } ans += e; z[b] += z[b - 1] - 1; } } c = f; d = g; e = 0; for ( b = 0; b < f+g; b++) { if (e-f>=0) { ans += f; e -= f; } else if (e-f<0) { ans += e; e = 0; } e += g; if (g>0) { g--; } else if (f>0) { f--; } else { break; } } //for ( b = 1; b <= a; b++) //{ // if (s[b-1]=='(') // { // z[b] += z[b - 1] + 1; // if (z[b - 1]<0) // { // e++; // } // ans += e; // h = 1; // } // else if (s[b - 1] == ')') // { // if (z[b-1]>0) // { // e++; // } // ans += e; // z[b] += z[b - 1] - 1; // if (h==0) // { // ans--; // } // } //} // //for (b = 0; b <= a; b++) //{ // //cout << z[b] << endl; //} ////sort(z, z + 100001); //sort(z,z+a); //for (b = a; b>=0 ; b--) //{ // if (z[b]>0) // { // c+=z[b]; // } // else if (z[b]<0) // { // if (c>0) // { // if (c-z[b]<0) // { // ans += c; // c += z[b]; // } // else // { // ans += -z[b]; // c += z[b]; // } // } // } //} //for ( b = 0; b < a; b++) //{ // //cout << z[b] << endl; //} //if (ans<0) //{ // ans = 0; //} cout << ans*2 << endl; return 0; }