#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef pair PII; typedef vector VI; typedef vector VVI; #define MP make_pair #define PB push_back #define inf 1000000007 #define rep(i,n) for(int i=0;i<(int)(n);++i) template void Fill(A (&array)[N], const T &val){ std::fill( (T*)array, (T*)(array+N), val ); } bool comp(pairp,pairq){ if(p.first>=q.second&&q.first>=p.second){ return p.second<=q.second; } if(p.first=p.second){ return p.second<=p.first; } if(p.first>=q.second&&q.first> n >> s; vectora(n),b(n),c(n); if(s[0]=='('){ a[0]++; }else{ b[0]++; } rep(i,n-1){ if(s[i+1]=='('){ a[i+1]=a[i]+1; b[i+1]=b[i]; c[i+1]=c[i]; }else{ if(a[i]>0){ a[i+1] = a[i]-1; b[i+1] = b[i]; c[i+1] = c[i]+1; }else{ b[i+1] = b[i]+1; b[i+1] = b[i]; c[i+1] = c[i]; } } } vector > v(n); ll ans = 0; rep(i,n){ v[i].first = a[i]; v[i].second = b[i]; ans += c[i]; } sort(v.begin(),v.end(),comp); ll tmp = 0; rep(i,n){ ans +=min(tmp,v[i].second); tmp = max((ll)0,tmp-v[i].second); tmp += v[i].first; } cout << ans+ans << endl; return 0; }