#include using namespace std; class UnionFind{ private: vector par,siz; public: UnionFind(int N){par.resize(N,-1);} int root(int x){ //連結成分の代表頂点を返す. if(par.at(x) == -1) return x; else return par.at(x) = root(par.at(x)); } bool unite(int u, int v){ //u,vを連結する 連結してた->false,した->trueを返す. u = root(u),v = root(v); if(u == v) return false; par.at(u) = v; return true; } bool issame(int u, int v){ //同じ連結成分ならtrue. if(root(u) == root(v)) return true; else return false; } }; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; string s; cin >> s; vector par(N+1,-1); int idx = 0; stack St; St.push(idx); for(auto c : s){ if(c == '('){ idx++; par.at(idx) = St.top(); St.push(idx); } else St.pop(); } vector A(N+1),B(N+1,1); for(int i=1; i<=N; i++) cin >> A.at(i); using T = tuple; auto comp = [&](const T &a,const T &b) -> bool { auto [x,y,p] = a; auto [x2,y2,q] = b; return x*y2 < x2*y; }; priority_queue,decltype(comp)> Q(comp); for(int i=1; i<=N; i++) Q.push({A.at(i),B.at(i),i}); UnionFind Z(N+1); long long answer = 0; while(Q.size()){ auto [a,b,pos] = Q.top(); Q.pop(); if(A.at(pos) != a || B.at(pos) != b) continue; Z.unite(pos,par.at(pos)); int leader = Z.root(pos); long long &a2 = A.at(leader),&b2 = B.at(leader); answer += b2*a; a2 += a; b2 += b; if(leader != 0) Q.push({a2,b2,leader}); } cout << answer << endl; }