#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; short int z[100001] = {}; short int y[100001] = {}; short int x[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; x[b] = f; y[b] = g; } else if (s[b - 1] == ')') { if (z[b - 1]>0) { e++; f--; } else if (z[b - 1] <= 0) { g++; } ans += e; z[b] += z[b - 1] - 1; if (z[b]<0) { z[b] = 0; } x[b] = f; y[b] = g; } } for (b = 1; b <= a; b++) { //cout << "xy" << x[b] << y[b] << endl; } for (b = 1; b <= a; b++) { for (c = a; c > b; c--) { if (y[c - 1] < y[c]) { /* 後ろの要素の方が大きかったら */ d = y[c]; /* 交換する */ y[c] = y[c - 1]; y[c - 1] = d; d = x[c]; /* 交換する */ x[c] = x[c - 1]; x[c - 1] = d; } } } for (b = 1; b <= a; b++) { for (c = a; c > b; c--) { if (x[c - 1] > x[c]) { /* 前の要素の方が大きかったら */ d = x[c]; /* 交換する */ x[c] = x[c - 1]; x[c - 1] = d; d = y[c]; /* 交換する */ y[c] = y[c - 1]; y[c - 1] = d; } } } for ( b = 1; b <= a; b++) { //cout << "xy" << x[b] << y[b] << endl; } /*c = f; d = g; e = 0;*/ g = 0; e = 0; //cout << ans * 2 << endl; //for ( b = 0; b < c+d; b++) for ( b = 1; b <= a; b++) { //cout << ans * 2 << "ge" << g << e << endl; if (b!=a) { g += y[b+1]; } e += x[b]; if (e - g >= 0 && e>0) { ans += g; e -= g; g = 0; } else if (e - g<0 && e>0) { ans += e; g -= e; e = 0; } /*if (f>0) { f--; } else if (g>0) { g--; } else { break; }*/ } /*while (1) { cout << ans * 2 << "gf" << g << f << endl; if (e - f >= 0 && e>0) { ans += f; e -= f; } else if (e - f<0 && e>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; }