#include using namespace std; using ll = long long; bool is_balanced(string s) { int open = 0; for (int i = 0; i < (int)s.size(); i++) { if (s[i] == '(') open++; else if (s[i] == ')') open--; if (open < 0) return false; } return open == 0; } int main() { int N; cin >> N; assert(1 <= N && N <= 100000); string S; cin >> S; assert(S.size() == 2 * N); assert(is_balanced(S)); vector A(N); for (int i = 0; i < N; i++) { cin >> A[i]; } stack s; vector v; vector parent(N + 1); vector d(N + 1); int next = 1; v.push_back(0); s.push(0); parent[0] = -1; for (int i = 0; i < (int)S.size(); i++) { if (S[i] == '(') { v.push_back(A[next - 1]); s.push(next); next++; } else { int me = s.top(); s.pop(); int p = s.top(); parent[me] = p; d[p]++; } } ll x = 0; ll ans = 0; priority_queue, vector>, greater>> pq; for (int i = 1; i <= N; i++) { if (d[i] == 0) { pq.emplace(v[i], i); } } while (!pq.empty()) { ll val = pq.top().first; int n = pq.top().second; pq.pop(); if (n == 0) break; x += val; ans += x; d[parent[n]]--; if (d[parent[n]] == 0) { pq.emplace(v[parent[n]], parent[n]); } } cout << ans << endl; }