Problem:
C:Parentheses Inversion
問題
(
と
)
からなる長さ $N$ の文字列 $S$ が与えられます。あなたは、以下の操作を好きな回数行うことができます。
コスト $A_i$ を払って $S_i$ を
(
と
)
のうち $S_i$ でない方の文字に変える
文字列 $S$ を正しいかっこ列に変えるために払う必要のあるコストの和の最小値を求めてください。
正しいかっこ列の定義
$T$ を
(
と
)
からなる長さ $M$ の文字列とします。$L= \{ i \mid 1\le i\le M , T_i = $
(
$ \},\ R=\{i \mid 1\le i\le M  , T_i = $
)
$ \} $ とおきます。以下の条件をみたす全単射 $f:L\to R$ が存在するとき、かつそのときに限り $T$ は正しいかっこ列であるといいます。
任意の $i\in L$ に対して $i< f(i)$
任意の $i,j\in L,\ i<j$ に対して $i<j<f(j)<f(i)$ または $i<f(i)<j<f(j)$
入力形式
入力は以下の形式で与えられます。
$N$
$S$
$A_1$ $\ldots$ $A_N$
制約
$2 \leq N \leq 200{,}000$
$1 \leq A_i \leq 10^{9}$
$N$ は偶整数
$A_i$は整数
$S$ は
(
,
)
のみからなる長さ $N$ の文字列
出力形式
文字列 $S$ を正しいかっこ列に変えるために払う必要のあるコストの和の最小値を一行に出力し、最後に改行を入れてください。
入力例 1
4
))((
1 1 1 1
出力例 1
2
入力例 2
4
))))
1 1 2 2
出力例 2
2
入力例 3
4
))))
1 2 1 2
出力例 3
2

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll=long long;
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
template<class T> bool chmax(T &a, T b){if (a < b){a = b;return true;} else return false;}
template<class T> bool chmin(T &a, T b){if (a > b){a = b;return true;} else return false;}

void Solve(){
    int N;
    cin>>N;
    string S;
    cin>>S;
    vector<ll>A(N);
    for(int i=0;i<N;i++)cin>>A[i];
    ll ans=0;
    {
        priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<pair<ll,int>>>pq;
        int sum=0;
        for(int i=0;i<N;i++){
            if(S[i]=='('){
                sum++;
            }else{
                pq.push({A[i],i});
                sum--;
                if(sum<0){
                    sum+=2;
                    ans+=pq.top().first;
                    S[pq.top().second]='(';
                    pq.pop();
                }
            }
        }
    }
    {
        priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<pair<ll,int>>>pq;
        int sum=0;
        for(int i=N-1;i>=0;i--){
            if(S[i]==')'){
                sum++;
            }else{
                pq.push({A[i],i});
                sum--;
                if(sum<0){
                    sum+=2;
                    ans+=pq.top().first;
                    S[pq.top().second]=')';
                    pq.pop();
                }
            }
        }
    }
    cout<<ans<<"\n";
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    Solve();
}
accuracy: 1
time_ms: 10
memory_kb: 9412
final_rank: 4

code_snippet: #include <bits/extc++.h>

#include <atcoder/all>

using ll = long long;

using mint = atcoder::modint998244353;

struct S {
  ll val;
  int left, right;

  S() = default;
  S(ll val, int i) : val(val), left(i), right(i) {}
  S(ll val, int left, int right) : val(val), left(left), right(right) {}
};

S op(S a, S b) {
  if (a.val > b.val) {
    return b;
  } else if (a.val < b.val) {
    return a;
  } else {
    return S(a.val, a.left, b.right);
  }
}

S e() {
  return {std::numeric_limits<ll>::max() / 2, -1};
}

struct SS {
  S first, second;
  SS(ll val, int i) : first(val, i), second(e()) {}

  SS(S first, S second) : first(first), second(second) {}
};

SS opp(SS a, SS b) {
  S first, second;

  if (a.first.val < b.first.val) {
    first = a.first;
    second = op(a.second, b.first);
  } else if (a.first.val > b.first.val) {
    first = b.first;
    second = op(a.first, b.second);
  } else {
    first = op(a.first, b.first);
    second = op(a.second, b.second);
  }

  return {first, second};
}

SS ee() {
  return {e(), e()};
}

using F = ll;

S mapping(F f, S x) {
  x.val += f;
  return x;
}
F composition(F f, F g) {
  return f + g;
}

F id() {
  return 0;
}

SS mapp(F f, SS x) {
  x.first.val += f;
  x.second.val += f;
  return x;
}

using lsegtree = atcoder::lazy_segtree<SS, opp, ee, F, mapp, composition, id>;

struct S2 {
  ll val;
  int idx;

  S2(ll val, int idx) : val(val), idx(idx) {}
};

S2 op2(S2 a, S2 b) {
  if (a.val > b.val) {
    return b;
  } else {
    return a;
  }
}

S2 e2() {
  return {std::numeric_limits<ll>::max() / 2, -1};
}

using segtree = atcoder::segtree<S2, op2, e2>;

int main() {
  int N;
  std::cin >> N;
  std::string s;
  std::cin >> s;
  std::vector<ll> A(N);
  for (auto& a : A) {
    std::cin >> a;
  }

  lsegtree lzy(N + 1);
  segtree open(N), close(N);

  lzy.set(0, SS(0, 0));

  for (int i = 0; i < N; i++) {
    if (s[i] == '(') {
      open.set(i, S2(A[i], i));
      lzy.set(i + 1, SS(lzy.get(i).first.val + 1, i + 1));
    } else {
      close.set(i, S2(A[i], i));
      lzy.set(i + 1, SS(lzy.get(i).first.val - 1, i + 1));
    }
  }

  ll ans = 0;

  while (lzy.all_prod().first.val < 0) {
    auto [x, l, r] = (lzy.all_prod().first.val % 2 == 0) ? lzy.all_prod().second
                                                         : lzy.all_prod().first;

    auto [p, i] = close.prod(0, l);

    ans += p;

    close.set(i, e2());

    lzy.apply(i + 1, N + 1, 2);
  }

  while (lzy.get(N).first.val > 0) {
    assert(lzy.all_prod().first.val == 0);

    auto [x, l, r] = lzy.all_prod().second;

    auto [p, i] = open.prod(r, N);

    ans += p;

    open.set(i, e2());

    lzy.apply(i + 1, N + 1, -2);
  }

  std::cout << ans << std::endl;
}
accuracy: 1
time_ms: 90
memory_kb: 43244
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
template<class T> bool chmin(T& a, T b) { return a > b ? a = b, true : false; }
template<class T> bool chmax(T& a, T b) { return a < b ? a = b, true : false; }
template<typename T>
concept Iterable = requires(T t) { std::begin(t); std::end(t); };
template<typename T>
	requires Iterable<T> && (!is_same_v<T, string>)
ostream& operator<<(ostream& os, const T& container) { for (auto& element : container) os << element << ' '; return os; }
template<typename R>
	requires ranges::range<R> && (!is_same_v<decay_t<R>, string>) && (!is_same_v<decay_t<R>, const char*>)
ostream& operator<<(ostream& os, R&& range) { for (auto& element : range)os << element << ' '; return os; }
template<typename T>
	requires Iterable<T> && (!is_same_v<T, string>)
istream& operator>>(std::istream& is, T& container) { for (auto& e : container)is >> e; return is; }
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
template<class T = ll> struct Edge {
	int to;
	T weight;
	bool operator==(Edge e) { return this->to == e.to and this->weight == e.weight; }
	bool operator<(Edge e) { return this->to == e.to ? this->weight < e.weight : this->to < e.to; }
};
#ifdef _DEBUG
#define SHOW(n) {const auto& _ret = n; cerr << #n << ": " << _ret << endl;}
#define MSG(x) cerr << x << endl;
#else
#define SHOW(n)
#define MSG(x)
#endif

////AtCoder Library
//#include <atcoder/all>
//using namespace atcoder;
////using mint = modint998244353;
////using mint = modint1000000007;
////using mint1 = dynamic_modint<0>;
//using mint = modint;
////mint::set_mod();
//istream& operator>>(istream& is, mint& x) { ll r; is >> r; x = r; return is; }
//ostream& operator<<(ostream& os, mint& x) { os << x.val(); return os; }

//boost
//#include <boost/multiprecision/cpp_int.hpp>
//using namespace boost::multiprecision;
//using l3 = int128_t;



#define REP(i, n) for(int i = 0; i < n; i++)
#define P pair<ll, ll>
ll powmod(ll a, ll b, ll mod = 998244353) {
	ll res = 1;
	a %= mod;
	while (b > 0) {
		if (b % 2 == 1) res = res * a % mod;
		a = a * a % mod;
		b /= 2;
	}
	return res;
}
vector<ll> f(210000);
ll ncr(ll n, ll r, ll mod = 998244353) {
	return f[n] * powmod(f[r], mod - 2) % mod * powmod(f[n - r], mod - 2) % mod;
}
ll mod = 998244353;
vector<ll> g[3100], v(3100), p(3100);

vector<P> dfs(int a) {
	vector<P> now;
	now.push_back(P(v[a], 1));
	for (auto& i : g[a])
	{
		vector<P> res = dfs(i);
		res.push_back(P(0, 1));
		vector<ll> t(2010);
		for (auto& p1 : now)
		{
			for (auto& p2 : res) {
				if (p1.first + p2.first > 2000)continue;
				t[p1.first + p2.first] += p1.second * p2.second % mod;
				t[p1.first + p2.first] %= mod;
			}
		}
		vector<P> ne;
		REP(i, 2010) {
			if (t[i] > 0)ne.push_back(P(i, t[i]));
		}
		now = ne;
		//cout << a << " " << now.size() << endl;
	}
	return now;
}

int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	ll n;
	string s;
	cin >> n >> s;
	vector<ll> v(n);
	REP(i, n)cin >> v[i];
	priority_queue<ll, vector<ll>, greater<ll>> q, q2;
	ll now = 0, ans = 0, li = 0;
	REP(i, n) {
		if (s[i] == '(')now++;
		else {
			now--;
			q.push(v[i]);
		}
		if (now == 0) {
			li = i + 1;
		}
		if (now < 0) {
			ans += q.top();
			q.pop();
			now = 1;
			li = i;
		}

	}
	now = 0;
	
	for (int i = n - 1; i >= li; i--) {
		if (s[i] == ')')now++;
		else {
			now--;
			q2.push(v[i]);
		}
		if (now < 0) {
			ans += q2.top();
			q2.pop();
			now = 1;
		}
	}
	cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 9264
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
#define rep(i, s, t) for (ll i = s; i < (ll)(t); i++)
#define rrep(i, s, t) for(ll i = (ll)(t) - 1; i >= (ll)(s); i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)

#define TT template<typename T>
TT using vec = vector<T>;
template<class T1, class T2> bool chmin(T1 &x, T2 y) { return x > y ? (x = y, true) : false; }
template<class T1, class T2> bool chmax(T1 &x, T2 y) { return x < y ? (x = y, true) : false; }

struct io_setup {
    io_setup() {
        ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        cout << fixed << setprecision(15);
    }
} io_setup;

using minheap =  priority_queue<ll, vector<ll>, greater<ll>>;
int main() {
    ll n;
    cin >> n;
    string S;
    cin >> S;
    vector<ll> A(n);
    rep(i, 0, n) cin >> A[i];

    auto rev = [&]() {
        reverse(all(A));
        reverse(all(S));
        for(auto & c : S) {
            if(c == '(') c = ')';
            else c = '(';
        }
        return;
    };

    auto cal = [&]() {
        minheap hp;
        ll ret = 0;
        ll sm = 0;
        rep(i, 0, n) {
            if(S[i] == '(') sm++;
            else {
                hp.push(A[i]);
                sm--;
            }
            while(sm < 0) {
                auto v = hp.top();
                hp.pop();
                ret += v;
                sm += 2;
            }
        }
      
        return ret;
    };


    ll ans = 0;
    ans += cal();
    rev();
    ans += cal();
    cout << ans << endl;

 
}
accuracy: 1
time_ms: 10
memory_kb: 6980
final_rank: 2

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); i++)
#define all(a) (a).begin(), (a).end()

int main(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    vector<int> a(n);
    rep(i, 0, n) cin >> a[i];
    ll ans = 0;
    rep(ttt,0,2){
        set<array<int,2>> ci; 
        int now = 0;
        rep(i, 0, n){
            if(s[i] == ')') {
                ci.insert({a[i], i});
                now--;
            }else{
                now++;
            }
            if(now < 0){
                auto itr = *ci.begin();
                ans += itr[0];
                s[itr[1]] = '(';
                ci.erase(ci.begin());
                now += 2;
            }
        }

        reverse(all(a));
        reverse(all(s));
        rep(i,0,n){
            if(s[i] == '(') s[i] = ')';
            else s[i] = '(';
        }
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 8960
final_rank: 19

code_snippet: /**
	author:  shobonvip
	created: 2025.05.08 17:32:17
**/

#include<bits/stdc++.h>
using namespace std;

/* BOOST MULTIPRECISION
#include<boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
//*/

typedef long long ll;

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)
#define all(v) v.begin(), v.end()

template <typename T> bool chmin(T &a, const T &b) {
	if (a <= b) return false;
	a = b;
	return true;
}

template <typename T> bool chmax(T &a, const T &b) {
	if (a >= b) return false;
	a = b;
	return true;
}

template <typename T> T max(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]);
	return ret;
}

template <typename T> T min(vector<T> &a){
	assert(!a.empty());
	T ret = a[0];
	for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]);
	return ret;
}

template <typename T> T sum(vector<T> &a){
	T ret = 0;
	for (int i=0; i<(int)a.size(); i++) ret += a[i];
	return ret;
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n; cin >> n;
	string s; cin >> s;
	vector<ll> a(n);
	rep(i,0,n) {
		cin >> a[i];
	}

	ll ans = 0;
	rep(i,0,n) {
		if (s[i] == ')') {
			ans += a[i];
			s[i] = '(';
			a[i] = - a[i];
		}
	}

	priority_queue<pair<ll,int>> pq;
	int piv = n-1;
	rep(i,0,n/2) {
		while (piv >= n-1-2*i) {
			pq.push(pair(-a[piv], piv));
			piv--;
		}
		assert(!pq.empty());
		auto [cost, ind] = pq.top();
		pq.pop();
		cost = -cost;
		ans += cost;
	}
	cout << ans << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 6960
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define rep(i,a,b) for (int i=(int)(a);i<(int)(b);i++)
#define all(p) p.begin(),p.end()


void solve();
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    // cin >> t;
    rep(i, 0, t) solve();
}

void solve(){
    int N;
    cin >> N;
    string S;
    cin >> S;
    ll ans = 0;
    vector<ll> A(N);
    rep(i, 0, N) cin >> A[i];
    priority_queue<ll> pq;
    rep(i, 0, N){
        if (S[i] == '('){
            ans += A[i];
            pq.push(A[i]);
        }
        else{
            pq.push(-A[i]);
        }
        if (i % 2 == 0){
            ans -= pq.top();
            pq.pop();
        }
    }
    cout << ans << "\n";
}
accuracy: 1
time_ms: 20
memory_kb: 5912
final_rank: 10

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define chmin(x,y) x = min(x,y)
#define chmax(x,y) x = max(x,y)
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 998244353
//#define MOD 1000000007
#define EPS 0.000000001



#define SIZE 200005

struct Info{
	Info(ll a_value){
		value= a_value;
	}
	bool operator<(const struct Info& arg) const{

		return value > arg.value; //昇順(PQ)
	}

	ll value;
};

ll A[SIZE];
char buf[SIZE];

int main(){

	int N;
	scanf("%d %s",&N,buf);

	for(int i = 0; i < N; i++){

		scanf("%lld",&A[i]);
	}

	ll ans = 0;
	ll rui = 0;
	priority_queue<Info> Q;

	for(int i = 0; i < N; i++){

		if(buf[i] == ')'){

			rui--;
			Q.push(Info(A[i]));

		}else{

			rui++;
		}
		if(rui < 0){
			ans += Q.top().value;
			Q.pop();
			rui += 2;
		}
	}

	while(!Q.empty()){
		Q.pop();
	}
	rui = 0;

	for(int i = N-1; i >= 0; i--){

		if(buf[i] == '('){

			rui--;
			Q.push(Info(A[i]));

		}else{

			rui++;
		}
		if(rui < 0){
			ans += Q.top().value;
			Q.pop();
			rui += 2;
		}
	}

	printf("%lld\n",ans);

	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 5628
final_rank: 8

code_snippet: #include <iostream>
#include <queue>

using namespace std;
typedef long long ll;
ll a[200010];
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int i,n; cin >> n;
    string s; cin >> s;
    for(i=0;i<n;i++) cin >> a[i];
    ll ans = 0;
    for(i=0;i<n;i++){
        if(s[i]=='('){
            ans += a[i];
            a[i] *= -1;
        }
    }
    priority_queue<ll,vector<ll>,greater<ll>> que;
    for(i=0;i<n;i++){
        que.push(a[i]);
        if(!(i&1)){
            ans += que.top();
            que.pop();
        }
    }
    cout << ans << "\n";
}
accuracy: 1
time_ms: 20
memory_kb: 5824
final_rank: 9

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    string s; cin >> s;
    vector<ll> a(n);
    ll res = 0;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        if (s[i] == '(') {
            res += a[i];
            a[i] = -a[i];
        }
    }
    int cnt = 0;
    priority_queue<ll,vector<ll>,greater<ll>> pq;
    for (int i = 0; i < n; ++i) {
        pq.push(a[i]);
        if (cnt == 0) {
            res += pq.top(); pq.pop();
            cnt++;
        }
        else {
            cnt--;
        }
    }
    cout << res << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 5936
final_rank: 11

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 3276.cc: Parentheses Inversion
 */

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<functional>
#include<utility>
 
using namespace std;

/* constant */

const int MAX_N = 200000;
const int INF = 1 << 30;
const long long LINF = 1LL << 60;

/* typedef */

typedef long long ll;
typedef vector<int> vi;
typedef queue<int> qi;
typedef pair<int,int> pii;

template <typename T>
struct SegTreeMin {
  int e2;
  vector<T> nodes;
  T defv;
  SegTreeMin() {}

  void init(int n, T _defv) {
    defv = _defv;
    for (e2 = 1; e2 < n; e2 <<= 1);
    nodes.assign(e2 * 2, defv);
  }

  T &geti(int i) { return nodes[e2 - 1 + i]; }
  void seti(int i, T v) { geti(i) = v; }

  void setall() {
    for (int j = e2 - 2; j >= 0; j--)
      nodes[j] = min(nodes[j * 2 + 1], nodes[j * 2 + 2]);
  }

  void set(int i, T v) {
    int j = e2 - 1 + i;
    nodes[j] = v;
    while (j > 0) {
      j = (j - 1) / 2;
      nodes[j] = min(nodes[j * 2 + 1], nodes[j * 2 + 2]);
    }
  }

  T min_range(int r0, int r1, int k, int i0, int i1) {
    if (r1 <= i0 || i1 <= r0) return defv;
    if (r0 <= i0 && i1 <= r1) return nodes[k];

    int im = (i0 + i1) / 2;
    T v0 = min_range(r0, r1, k * 2 + 1, i0, im);
    T v1 = min_range(r0, r1, k * 2 + 2, im, i1);
    return min(v0, v1);
  }
  T min_range(int r0, int r1) { return min_range(r0, r1, 0, 0, e2); }
};

template <typename T>
struct BIT {
  int n;
  vector<T> bits;
  
  BIT() {}
  BIT(int _n) { init(_n); }

  void init(int _n) {
    n = _n;
    bits.assign(n + 1, 0);
  }

  T sum(int x) {
    x = min(x, n);
    T s = 0;
    while (x > 0) {
      s += bits[x];
      x -= (x & -x);
    }
    return s;
  }

  void add(int x, T v) {
    if (x <= 0) return;
    while (x <= n) {
      bits[x] += v;
      x += (x & -x);
    }
  }

  int lower_bound(T v) {
    int	k = 1;
    while ((k << 1) <= n) k <<=	1;
    int	x = 0;
    for	(; k > 0; k >>= 1)
      if (x + k <= n && bits[x + k] < v) {
        x += k;
        v -= bits[x];
      }
    return x + 1;
  }
};

/* global variables */

char s[MAX_N + 4];
int as[MAX_N];
SegTreeMin<pii> st0, st1;
BIT<int> bit;

/* subroutines */

/* main */

int main() {
  int n;
  scanf("%d%s", &n, s);
  for (int i = 0; i < n; i++) scanf("%d", as + i);

  int c = 0;
  st0.init(n, pii(INF, -1)), st1.init(n, pii(INF, -1));
  for (int i = 0; i < n; i++) {
    if (s[i] == '(') st0.seti(i, pii(as[i], i)), c++;
    else st1.seti(i, pii(as[i], i)), c--;
  }
  st0.setall(), st1.setall();
  //printf("c=%d\n", c);

  ll sum = 0;
  while (c > 0) {
    pii e = st0.min_range(0, n);
    int ai = e.first, i = e.second;
    s[i] = ')';
    sum += ai; c -= 2;
    st0.set(i, pii(INF, i));
    st1.set(i, pii(-ai, i));
  }
  while (c < 0) {
    pii e = st1.min_range(0, n);
    int ai = e.first, i = e.second;
    s[i] = '(';
    sum += ai; c += 2;
    st1.set(i, pii(INF, i));
    st0.set(i, pii(-ai, i));
  }
  //printf("sum=%lld, %s\n", sum, s);

  bit.init(n);
  for (int i = 0; i < n; i++)
    bit.add(i + 1, (s[i] == '(') ? 1 : -1);

  for (int i = 0, j = n - 1; i <= j;) {
    while (i <= j && bit.sum(i + 1) >= 0) i++;
    while (i <= j && bit.sum(j + 1) >= 0) j--;
    if (i > j) break;

    pii e1 = st1.min_range(0, i + 1);
    int a1 = e1.first, i1 = e1.second;
    s[i1] = '(';
    sum += a1;
    st1.set(i1, pii(INF, i1));
    st0.set(i1, pii(-a1, i1));
    bit.add(i1 + 1, 2);

    pii e0 = st0.min_range(j + 1, n);
    int a0 = e0.first, j0 = e0.second;
    s[j0] = ')';
    sum += a0;
    st0.set(j0, pii(INF, j0));
    st1.set(j0, pii(-a0, j0));
    bit.add(j0 + 1, -2);

    //printf("i=%d, j=%d, %s\n", i, j, s);
  }

  printf("%lld\n", sum);

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 13040
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    int N;
    cin >> N;
    string S;
    cin >> S;
    vector<int> A(N);
    for (auto& x : A) cin >> x;
    ll ans = 0;
    priority_queue<int, vector<int>> pq;
    rep(i,0,N) {
        if (S[i] == ')') {
            ans += A[i];
            A[i] *= -1;
        }
        pq.push(A[i]);
        if (i % 2 == 0) {
            pq.pop();
        }
    }
    while (!pq.empty()) {
        ans += pq.top();
        pq.pop();
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 4736
final_rank: 5

code_snippet: //#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#if __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;
using mint = modint1000000007;
// using mint = modint998244353;
// using mint = modint;
#endif
using ll = long long;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
// const int MOD = (int)1e9 + 7;
// const int MOD = (int)998244353;
const int INF = (int)1e9 + 1001010;
const ll llINF = (ll)4e18 + 11000010;
const double PI = 3.14159265358979;
const double EPS = 1e-10;
#define ALL(x) x.begin(),x.end()
#define RALL(x) x.rbegin(),x.rend()
#define endn "\n"
#define SUM(v) accumulate(ALL(v), 0LL)
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define popcount __builtin_popcount
#define popcountll __builtin_popcountll

template<class T, class U> istream & operator >> (istream &i, pair<T,U> &A) {i >> A.first >> A.second; return i;}
template<class T, class U, class V> istream & operator >> (istream &i, tuple<T,U,V>&A) {i >> get<0>(A) >> get<1>(A) >> get<2>(A); return i;}
template<class T> istream & operator >> (istream &i, vector<T> &A) {for(auto &I : A) {i >> I;} return i;}
template<class T, class U> ostream & operator << (ostream &o, const pair<T,U> &A) {o << A.first << " " << A.second; return o;}
template<class T, class U, class V>ostream & operator << (ostream &o, const tuple<T,U,V> &A) {o << get<0>(A) << " " << get<1>(A) << " " << get<2>(A); return o;}
template<class T> ostream & operator << (ostream &o, const vector<T> &A) {int i=A.size(); for(auto &I : A){o << I << (--i ? endn : "");} return o;}

template <class T, class S> pair<T,S> operator + (const pair<T,S> &x, const pair<T,S> &y) {return pair<T,S>(x.first + y.first, x.second + y.second);}
template <class T, class S> pair<T,S> operator - (const pair<T,S> &x, const pair<T,S> &y) {return pair<T,S>(x.first - y.first, x.second - y.second);}
template <class T, class S> pair<T,S> operator += (pair<T,S> &l, const pair<T,S> &r) {return l = l + r;}
template <class T, class S> pair<T,S> operator -= (pair<T,S> &l, const pair<T,S> &r) {return l = l - r;}

template<class T,class U>bool chmax(T &a,const U &b){return ((a<b) ? (a=b, true) : false);}
template<class T,class U>bool chmin(T &a,const U &b){return ((a>b) ? (a=b, true) : false);}

ll ceil(ll a, ll b){return (a+b-1) / b;};


int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n; string s; cin >> n >> s;
    vector<ll> a(n); cin >> a;
    ll ans = 0;
    for(int i = 0; i < n; i++){
        if(s[i] == ')'){
            ans += a[i];
            a[i] *= -1;
        }
    }

    reverse(ALL(a));
    pqg<int> pq;
    for(int i = 0; i < n/2; i++){
        pq.emplace(a[2*i]);
        if(i != 0) pq.emplace(a[2*i -1]);

        ans += pq.top(); pq.pop();
    }
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 5516
final_rank: 7

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T, typename V>
void ndarray(vector<T>& vec, const V& val, int len) { vec.assign(len, val); }
template <typename T, typename V, typename... Args> void ndarray(vector<T>& vec, const V& val, int len, Args... args) { vec.resize(len), for_each(begin(vec), end(vec), [&](T& v) { ndarray(v, val, args...); }); }
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template <typename T> vector<T> sort_unique(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <typename T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <typename T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T, size_t sz> ostream &operator<<(ostream &os, const array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
#if __cplusplus >= 201703L
template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
#endif
template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T, typename TH> ostream &operator<<(ostream &os, const unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <typename TK, typename TV, typename TH> ostream &operator<<(ostream &os, const unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl
#define dbgif(cond, x) ((cond) ? cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl : cerr)
#else
#define dbg(x) (x)
#define dbgif(cond, x) 0
#endif

int main() {
    int N;
    string S;
    cin >> N >> S;
    vector<int> A(N);
    cin >> A;

    vector<lint> left(N + 1), right(N + 1);
    vector<int> ld(N + 1), rd(N + 1);

    priority_queue<int, vector<int>, greater<int>> pq;
    int depth = 0;

    lint sum = 0;
    REP(i, N) {
        if (S[i] == '(') {
            ++depth;
        } else {
            --depth;
            pq.push(A[i]);
        }

        if (depth < 0) {
            depth += 2;
            sum += pq.top();
            pq.pop();
        }
        left[i + 1] = sum;
        ld[i + 1] = depth;
    }

    while (pq.size()) pq.pop();
    depth = 0;
    sum = 0;
    IREP(i, N) {
        if (S[i] == ')') {
            ++depth;
        } else {
            --depth;
            pq.push(A[i]);
        }
        if (depth < 0) {
            depth += 2;
            sum += pq.top();
            pq.pop();
        }
        right[N - i] = sum;
        rd[N - i] = depth;
    }

    lint ret = 1LL << 60;
    REP(l, N + 1) {
        if (ld[l] == rd[N - l]) chmin(ret, left[l] + right[N - l]);
    }
    cout << ret << '\n';
}
accuracy: 1
time_ms: 20
memory_kb: 9428
final_rank: 15

code_snippet: #include <bits/stdc++.h>
    using namespace std;
    #include <math.h>
    #include <iomanip>
    #include <cstdint>
    #include <string>
    #include <sstream>
    
    template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
    template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
    #define rep(i,n) for (int i = 0; i < (n); ++i)

    typedef long long ll;
    typedef unsigned long long ull;
    using P=pair<ll,ll>;
    using tp=tuple<ll,ll,ll>;
    const int INF=1001001001;
    const ll INFL=1e18;
    const int mod=998244353;
    
    void solve(){
        int n;
        string s;
        cin>>n>>s;
        vector<ll>a(n);
        rep(i,n)cin>>a[i];

        ll ans=0;
        rep(i,n){
            if(s[i]=='('){
                ans+=a[i];
                a[i]*=-1;
            }
        }
        priority_queue<int,vector<int>,greater<int>>q;
        rep(i,n){
            q.push(a[i]);
            if(i%2==0){
                ans+=q.top();
                q.pop();
            }
        }
        cout<<ans<<endl;
    }  

    int main(){
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        
        solve();
        
        return 0;
    }
accuracy: 1
time_ms: 20
memory_kb: 5512
final_rank: 6

code_snippet: //#define _GLIBCXX_DEBUG

#include<bits/stdc++.h>
using namespace std;

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define UNIQUE(a) (a).erase(unique((a).begin(),(a).end()),(a).end())
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]<v[j];});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]>v[j];});
  return ord;
}
template<typename T> vector<T> inv_perm(const vector<T>&ord){
  vector<T>inv(ord.size());
  for(int i=0;i<ord.size();i++)inv[ord[i]] = i;
  return inv;
}
ll FLOOR(ll n,ll div){assert(div>0);return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){assert(div>0);return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
ll modulo(ll n,ll d){return (n%d+d)%d;};
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
ll MULT(ll x,ll y){if(LLONG_MAX/x<=y)return LLONG_MAX;return x*y;}
ll POW2(ll x, ll k){ll ret=1,mul=x;while(k){if(mul==LLONG_MAX)return LLONG_MAX;if(k&1)ret=MULT(ret,mul);mul=MULT(mul,mul);k>>=1;}return ret;}
ll POW(ll x, ll k){ll ret=1;for(int i=0;i<k;i++){if(LLONG_MAX/x<=ret)return LLONG_MAX;ret*=x;}return ret;}
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}

int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
  ll n;cin>>n;
  string s;cin>>s;
  vector<ll>a(n);
  rep(i,0,n)cin>>a[i];
  auto f=[&](){
    QP<ll>que;
    ll cnt=0;
    rep(i,0,n){
      if(s[i]=='('){
        cnt++;
      }
      else{
        cnt--;
        que.push(a[i]);
        if(cnt<0){
          res+=poll(que);
          cnt+=2;
        }
      }
    }
  };
  f();
  for(auto &c:s)c=(c=='('?')':'(');
  reverse(ALL(s));
  reverse(ALL(a));
  f();
  cout<<res<<endl;
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 6712
final_rank: 12

code_snippet: #pragma region Macros
//#pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma comment(linker, "/stack:200000000")
#ifdef ONLINE_JUDGE
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("popcnt")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2,tune=native")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2")
// #pragma GCC target("avx2")
#endif
#pragma GCC optimize("Ofast")
#ifdef noimi
#define oj_local(a, b) b
#else
#define oj_local(a, b) a
#endif

#define LOCAL if(oj_local(0, 1))
#define OJ if(oj_local(1, 0))

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfenv>
#include <cfloat>
#include <chrono>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <immintrin.h>
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

using namespace std;
using ll = long long;
using ull = unsigned long long int;
using i128 = __int128_t;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using ld = long double;
template <typename T> using vc = vector<T>;
template <typename T> using vvc = vector<vc<T>>;
template <typename T> using vvvc = vector<vvc<T>>;
using vi = vc<int>;
using vl = vc<ll>;
using vpi = vc<pii>;
using vpl = vc<pll>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
template <typename T> int si(const T &x) { return x.size(); }
template <class T, class S> inline bool chmax(T &a, const S &b) { return (a < b ? a = b, 1 : 0); }
template <class T, class S> inline bool chmin(T &a, const S &b) { return (a > b ? a = b, 1 : 0); }
vi iota(int n) {
    vi a(n);
    return iota(a.begin(), a.end(), 0), a;
}
template <typename T> vi iota(const vector<T> &a, bool greater = false) {
    vi res(a.size());
    iota(res.begin(), res.end(), 0);
    sort(res.begin(), res.end(), [&](int i, int j) {
        if(greater) return a[i] > a[j];
        return a[i] < a[j];
    });
    return res;
}

// macros
#define overload5(a, b, c, d, e, name, ...) name
#define overload4(a, b, c, d, name, ...) name
#define endl '\n'
#define REP0(n) for(ll jidlsjf = 0; jidlsjf < n; ++jidlsjf)
#define REP1(i, n) for(ll i = 0; i < (n); ++i)
#define REP2(i, a, b) for(ll i = (a); i < (b); ++i)
#define REP3(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define rep(...) overload4(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define per0(n) for(int jidlsjf = 0; jidlsjf < (n); ++jidlsjf)
#define per1(i, n) for(ll i = (n)-1; i >= 0; --i)
#define per2(i, a, b) for(ll i = (a)-1; i >= b; --i)
#define per3(i, a, b, c) for(ll i = (a)-1; i >= (b); i -= (c))
#define per(...) overload4(__VA_ARGS__, per3, per2, per1, per0)(__VA_ARGS__)
#define fore0(a) rep(a.size())
#define fore1(i, a) for(auto &&i : a)
#define fore2(a, b, v) for(auto &&[a, b] : v)
#define fore3(a, b, c, v) for(auto &&[a, b, c] : v)
#define fore4(a, b, c, d, v) for(auto &&[a, b, c, d] : v)
#define fore(...) overload5(__VA_ARGS__, fore4, fore3, fore2, fore1, fore0)(__VA_ARGS__)
#define fi first
#define se second
#define pb push_back
#define ppb pop_back
#define ppf pop_front
#define eb emplace_back
#define drop(s) cout << #s << endl, exit(0)
#define si(c) (int)(c).size()
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define rng(v, l, r) v.begin() + l, v.begin() + r
#define all(c) begin(c), end(c)
#define rall(c) rbegin(c), rend(c)
#define SORT(v) sort(all(v))
#define REV(v) reverse(all(v))
#define UNIQUE(x) SORT(x), x.erase(unique(all(x)), x.end())
template <typename T = ll, typename S> T SUM(const S &v) { return accumulate(all(v), T(0)); }
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define overload2(_1, _2, name, ...) name
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) vector<vector<vector<type>>> name(h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)                                                                                                                         \
    vector<vector<vector<vector<type>>>> name(a, vector<vector<vector<type>>>(b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define vvvvv(type, name, a, b, c, d, ...) vector name(a, vector(b, vector(c, vector(d, vector<type>(__VA_ARGS__)))))
#define vvvvvv(type, name, a, b, c, d, e, ...) vector name(a, vector(b, vector(c, vector(d, vector(e, vector<type>(__VA_ARGS__))))))
constexpr pii dx4[4] = {pii{1, 0}, pii{0, 1}, pii{-1, 0}, pii{0, -1}};
constexpr pii dx8[8] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};

namespace yesno_impl {
const string YESNO[2] = {"NO", "YES"};
const string YesNo[2] = {"No", "Yes"};
const string yesno[2] = {"no", "yes"};
const string firstsecond[2] = {"second", "first"};
const string FirstSecond[2] = {"Second", "First"};
const string possiblestr[2] = {"impossible", "possible"};
void YES(bool t = 1) { cout << YESNO[t] << endl; }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { cout << YesNo[t] << endl; }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { cout << yesno[t] << endl; }
void no(bool t = 1) { yes(!t); }
void first(bool t = 1) { cout << firstsecond[t] << endl; }
void First(bool t = 1) { cout << FirstSecond[t] << endl; }
void possible(bool t = 1) { cout << possiblestr[t] << endl; }
}; // namespace yesno_impl
using namespace yesno_impl;

#define INT(...)                                                                                                                                               \
    int __VA_ARGS__;                                                                                                                                           \
    IN(__VA_ARGS__)
#define LL(...)                                                                                                                                                \
    ll __VA_ARGS__;                                                                                                                                            \
    IN(__VA_ARGS__)
#define STR(...)                                                                                                                                               \
    string __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
#define CHR(...)                                                                                                                                               \
    char __VA_ARGS__;                                                                                                                                          \
    IN(__VA_ARGS__)
#define DBL(...)                                                                                                                                               \
    double __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
#define VEC(type, name, size)                                                                                                                                  \
    vector<type> name(size);                                                                                                                                   \
    IN(name)
#define VEC2(type, name1, name2, size)                                                                                                                         \
    vector<type> name1(size), name2(size);                                                                                                                     \
    for(int i = 0; i < size; i++) IN(name1[i], name2[i])
#define VEC3(type, name1, name2, name3, size)                                                                                                                  \
    vector<type> name1(size), name2(size), name3(size);                                                                                                        \
    for(int i = 0; i < size; i++) IN(name1[i], name2[i], name3[i])
#define VV(type, name, h, w)                                                                                                                                   \
    vector<vector<type>> name(h, vector<type>(w));                                                                                                             \
    IN(name)
int scan() { return getchar(); }
void scan(int &a) { cin >> a; }
void scan(long long &a) { cin >> a; }
void scan(char &a) { cin >> a; }
void scan(double &a) { cin >> a; }
void scan(string &a) { cin >> a; }
template <class T, class S> void scan(pair<T, S> &p) { scan(p.first), scan(p.second); }
template <class T> void scan(vector<T> &);
template <class T> void scan(vector<T> &a) {
    for(auto &i : a) scan(i);
}
template <class T> void scan(T &a) { cin >> a; }
void IN() {}
template <class Head, class... Tail> void IN(Head &head, Tail &...tail) {
    scan(head);
    IN(tail...);
}

template <typename T, typename S> T ceil(T x, S y) {
    assert(y);
    return (y < 0 ? ceil(-x, -y) : (x > 0 ? (x + y - 1) / y : x / y));
}

template <typename T, typename S> T floor(T x, S y) {
    assert(y);
    return (y < 0 ? floor(-x, -y) : (x > 0 ? x / y : x / y - (x % y == 0 ? 0 : 1)));
}
template <class T> T POW(T x, int n) {
    T res = 1;
    for(; n; n >>= 1, x *= x)
        if(n & 1) res *= x;
    return res;
}
template <class T, class S> T POW(T x, S n, const ll &mod) {
    T res = 1;
    x %= mod;
    for(; n; n >>= 1, x = x * x % mod)
        if(n & 1) res = res * x % mod;
    return res;
}
vector<pll> factor(ll x) {
    vector<pll> ans;
    for(ll i = 2; i * i <= x; i++)
        if(x % i == 0) {
            ans.push_back({i, 1});
            while((x /= i) % i == 0) ans.back().second++;
        }
    if(x != 1) ans.push_back({x, 1});
    return ans;
}
template <class T> vector<T> divisor(T x) {
    vector<T> ans;
    for(T i = 1; i * i <= x; i++)
        if(x % i == 0) {
            ans.pb(i);
            if(i * i != x) ans.pb(x / i);
        }
    return ans;
}
template <typename T> void zip(vector<T> &x) {
    vector<T> y = x;
    UNIQUE(y);
    for(int i = 0; i < x.size(); ++i) { x[i] = lb(y, x[i]); }
}
template <class S> void fold_in(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void fold_in(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto e : a) v.emplace_back(e);
    fold_in(v, tail...);
}
template <class S> void renumber(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void renumber(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto &&e : a) e = lb(v, e);
    renumber(v, tail...);
}
template <class S, class... Args> vector<S> zip(vector<S> &head, Args &&...args) {
    vector<S> v;
    fold_in(v, head, args...);
    sort(all(v)), v.erase(unique(all(v)), v.end());
    renumber(v, head, args...);
    return v;
}
template <typename T> vector<T> RUI(const vector<T> &v) {
    vector<T> res(v.size() + 1);
    for(int i = 0; i < v.size(); i++) res[i + 1] = res[i] + v[i];
    return res;
}
// 反時計周りに 90 度回転
template <typename T> void rot(vector<vector<T>> &v) {
    if(empty(v)) return;
    int n = v.size(), m = v[0].size();
    vector res(m, vector<T>(n));
    rep(i, n) rep(j, m) res[m - 1 - j][i] = v[i][j];
    v.swap(res);
}
// x in [l, r)
template <class T, class S> bool inc(const T &x, const S &l, const S &r) { return l <= x and x < r; }

constexpr ll ten(int n) { return n == 0 ? 1 : ten(n - 1) * 10; }
// bit 演算系
ll pow2(int i) { return 1LL << i; }
int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
int topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
int lowbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); }
int lowbit(ll a) { return a == 0 ? 64 : __builtin_ctzll(a); }
// int allbit(int n) { return (1 << n) - 1; }
constexpr ll mask(int n) { return (1LL << n) - 1; }
// int popcount(signed t) { return __builtin_popcount(t); }
// int popcount(ll t) { return __builtin_popcountll(t); }
int popcount(uint64_t t) { return __builtin_popcountll(t); }
static inline uint64_t popcount64(uint64_t x) {
    uint64_t m1 = 0x5555555555555555ll;
    uint64_t m2 = 0x3333333333333333ll;
    uint64_t m4 = 0x0F0F0F0F0F0F0F0Fll;
    uint64_t h01 = 0x0101010101010101ll;

    x -= (x >> 1) & m1;
    x = (x & m2) + ((x >> 2) & m2);
    x = (x + (x >> 4)) & m4;

    return (x * h01) >> 56;
}
bool ispow2(int i) { return i && (i & -i) == i; }

ll rnd(ll l, ll r) { //[l, r)
#ifdef noimi
    static mt19937_64 gen;
#else
    static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
#endif
    return uniform_int_distribution<ll>(l, r - 1)(gen);
}
ll rnd(ll n) { return rnd(0, n); }

template <class t> void random_shuffle(vc<t> &a) { rep(i, si(a)) swap(a[i], a[rnd(0, i + 1)]); }

int in() {
    int x;
    cin >> x;
    return x;
}
ll lin() {
    unsigned long long x;
    cin >> x;
    return x;
}

template <class T, class S> pair<T, S> operator-(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi - y.fi, x.se - y.se); }
template <class T, class S> pair<T, S> operator+(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi + y.fi, x.se + y.se); }
template <class T> pair<T, T> operator&(const pair<T, T> &l, const pair<T, T> &r) { return pair<T, T>(max(l.fi, r.fi), min(l.se, r.se)); }
template <class T, class S> pair<T, S> operator+=(pair<T, S> &l, const pair<T, S> &r) { return l = l + r; }
template <class T, class S> pair<T, S> operator-=(pair<T, S> &l, const pair<T, S> &r) { return l = l - r; }
template <class T> bool intersect(const pair<T, T> &l, const pair<T, T> &r) { return (l.se < r.se ? r.fi < l.se : l.fi < r.se); }

template <typename T> struct edge {
    int from, to;
    T cost;
    int id;
    edge(int to, T cost) : from(-1), to(to), cost(cost) {}
    edge(int from, int to, T cost) : from(from), to(to), cost(cost) {}
    edge(int from, int to, T cost, int id) : from(from), to(to), cost(cost), id(id) {}
    constexpr bool operator<(const edge<T> &rhs) const noexcept { return cost < rhs.cost; }
    edge &operator=(const int &x) {
        to = x;
        return *this;
    }
    operator int() const { return to; }
    friend ostream operator<<(ostream &os, edge &e) { return os << e.to; }
};
template <typename T> using Edges = vector<edge<T>>;

using Tree = vector<vector<int>>;
using Graph = vector<vector<int>>;
template <class T> using Wgraph = vector<vector<edge<T>>>;
Graph getG(int n, int m = -1, bool directed = false, int margin = 1) {
    Tree res(n);
    if(m == -1) m = n - 1;
    while(m--) {
        int a, b;
        cin >> a >> b;
        a -= margin, b -= margin;
        res[a].emplace_back(b);
        if(!directed) res[b].emplace_back(a);
    }
    return res;
}
Graph getTreeFromPar(int n, int margin = 1) {
    Graph res(n);
    for(int i = 1; i < n; i++) {
        int a;
        cin >> a;
        res[a - margin].emplace_back(i);
    }
    return res;
}
template <class T> Wgraph<T> getWg(int n, int m = -1, bool directed = false, int margin = 1) {
    Wgraph<T> res(n);
    if(m == -1) m = n - 1;
    while(m--) {
        int a, b;
        T c;
        scan(a), scan(b), scan(c);
        a -= margin, b -= margin;
        res[a].emplace_back(b, c);
        if(!directed) res[b].emplace_back(a, c);
    }
    return res;
}
void add(Graph &G, int x, int y) { G[x].eb(y), G[y].eb(x); }
template <class S, class T> void add(Wgraph<S> &G, int x, int y, T c) { G[x].eb(y, c), G[y].eb(x, c); }

#define TEST                                                                                                                                                   \
    INT(testcases);                                                                                                                                            \
    while(testcases--)

istream &operator>>(istream &is, i128 &v) {
    string s;
    is >> s;
    v = 0;
    for(int i = 0; i < (int)s.size(); i++) {
        if(isdigit(s[i])) { v = v * 10 + s[i] - '0'; }
    }
    if(s[0] == '-') { v *= -1; }
    return is;
}

ostream &operator<<(ostream &os, const i128 &v) {
    if(v == 0) { return (os << "0"); }
    i128 num = v;
    if(v < 0) {
        os << '-';
        num = -num;
    }
    string s;
    for(; num > 0; num /= 10) { s.push_back((char)(num % 10) + '0'); }
    reverse(s.begin(), s.end());
    return (os << s);
}
namespace aux {
template <typename T, unsigned N, unsigned L> struct tp {
    static void output(std::ostream &os, const T &v) {
        os << std::get<N>(v) << (&os == &cerr ? ", " : " ");
        tp<T, N + 1, L>::output(os, v);
    }
};
template <typename T, unsigned N> struct tp<T, N, N> {
    static void output(std::ostream &os, const T &v) { os << std::get<N>(v); }
};
} // namespace aux
template <typename... Ts> std::ostream &operator<<(std::ostream &os, const std::tuple<Ts...> &t) {
    if(&os == &cerr) { os << '('; }
    aux::tp<std::tuple<Ts...>, 0, sizeof...(Ts) - 1>::output(os, t);
    if(&os == &cerr) { os << ')'; }
    return os;
}
template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {
    if(&os == &cerr) { return os << "(" << p.first << ", " << p.second << ")"; }
    return os << p.first << " " << p.second;
}
template <class Ch, class Tr, class Container> std::basic_ostream<Ch, Tr> &operator<<(std::basic_ostream<Ch, Tr> &os, const Container &x) {
    bool f = true;
    if(&os == &cerr) os << "[";
    for(auto &y : x) {
        if(&os == &cerr)
            os << (f ? "" : ", ") << y;
        else
            os << (f ? "" : " ") << y;
        f = false;
    }
    if(&os == &cerr) os << "]";
    return os;
}

#ifdef noimi
#undef endl
void debug() { cerr << endl; }
void debug(bool) { cerr << endl; }
template <class Head, class... Tail> void debug(bool is_front, Head head, Tail... tail) {
    if(!is_front) cerr << ", ";
    cerr << head;
    debug(false, tail...);
}

#define dump(args...)                                                                                                                                          \
    {                                                                                                                                                          \
        vector<string> _debug = _split(#args, ',');                                                                                                            \
        err(true, begin(_debug), args);                                                                                                                        \
    }

vector<string> _split(const string &s, char c) {
    vector<string> v;
    stringstream ss(s);
    string x;
    while(getline(ss, x, c)) {
        if(empty(v))
            v.eb(x);
        else {
            bool flag = false;
            for(auto [c, d] : {pair('(', ')'), pair('[', ']'), pair('{', '}')}) {
                if(count(all(v.back()), c) != count(all(v.back()), d)) flag = true;
            }
            if(flag)
                v.back() += "," + x;
            else
                v.eb(x);
        }
    }
    return move(v);
}

void err(bool, vector<string>::iterator) { cerr << endl; }
template <typename T, typename... Args> void err(bool is_front, vector<string>::iterator it, T a, Args... args) {
    if(!is_front) cerr << ", ";
    cerr << it->substr((*it)[0] == ' ', (*it).size()) << " = " << a, err(false, ++it, args...);
}

// #define dump(...) cerr << #__VA_ARGS__ << " : ", debug(true, __VA_ARGS__)
#else
#define dump(...) static_cast<void>(0)
#define dbg(...) static_cast<void>(0)
#endif
void OUT() { cout << endl; }
template <class Head, class... Tail> void OUT(const Head &head, const Tail &...tail) {
    cout << head;
    if(sizeof...(tail)) cout << ' ';
    OUT(tail...);
}

template <typename T> static constexpr T inf = numeric_limits<T>::max() / 2;

template <class F> struct REC {
    F f;
    REC(F &&f_) : f(std::forward<F>(f_)) {}
    template <class... Args> auto operator()(Args &&...args) const { return f(*this, std::forward<Args>(args)...); }
};

template <class S> vector<pair<S, int>> runLength(const vector<S> &v) {
    vector<pair<S, int>> res;
    for(auto &e : v) {
        if(res.empty() or res.back().fi != e)
            res.eb(e, 1);
        else
            res.back().se++;
    }
    return res;
}
vector<pair<char, int>> runLength(const string &v) {
    vector<pair<char, int>> res;
    for(auto &e : v) {
        if(res.empty() or res.back().fi != e)
            res.eb(e, 1);
        else
            res.back().se++;
    }
    return res;
}

int toint(const char &c, const char start = 'a') { return c - start; }
int toint(const char &c, const string &chars) { return find(all(chars), c) - begin(chars); }
int alphabets_to_int(const char &c) { return (islower(c) ? c - 'a' : c - 'A' + 26); }
template <typename T> auto toint(const T &v, const char &start = 'a') {
    vector<decltype(toint(v[0]))> ret;
    ret.reserve(v.size());
    for(auto &&e : v) ret.emplace_back(toint(e, start));
    return ret;
}
template <typename T> auto toint(const T &v, const string &start) {
    vector<decltype(toint(v[0]))> ret;
    ret.reserve(v.size());
    for(auto &&e : v) ret.emplace_back(toint(e, start));
    return ret;
}
// a -> 0, A -> 26
template <typename T> auto alphabets_to_int(const T &s) {
    vector<decltype(alphabets_to_int(s[0]))> res;
    res.reserve(s.size());
    for(auto &&e : s) { res.emplace_back(alphabets_to_int(e)); }
    return res;
}

template <class T, class F> T bin_search(T ok, T ng, const F &f) {
    while(abs(ok - ng) > 1) {
        T mid = ok + ng >> 1;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
template <class T, class F> T bin_search_double(T ok, T ng, const F &f, int iter = 80) {
    while(iter--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

struct Setup_io {
    Setup_io() {
        ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
        cout << fixed << setprecision(11);
    }
} setup_io;

#pragma endregion

int main() {
    INT(n);
    STR(s);
    VEC(int, a, n);
    ll sum = 0;
    rep(2) {
        pqg<ll> pq;
        int c = 0;
        rep(i, n) {
            c += (s[i] == '(' ? 1 : -1);
            if(s[i] == ')') pq.emplace(a[i]);
            if(c < 0) {
                c += 2;
                sum += pq.top();
                pq.pop();
            }
        }
        REV(a);
        REV(s);
        fore(e, s) e ^= (')' ^ '(');
    }
    OUT(sum);
}
accuracy: 1
time_ms: 10
memory_kb: 5940
final_rank: 1

code_snippet: #include <bits/stdc++.h>
    using namespace std;
    #include <math.h>
    #include <iomanip>
    #include <cstdint>
    #include <string>
    #include <sstream>
    template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
    template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
    #define rep(i,n) for (int i = 0; i < (n); ++i)

    typedef long long ll;
    typedef unsigned long long ull;
    using P=pair<ll,ll>;
    const int INF=1001001001;
    const int mod=998244353;
    
    void solve(){
	    int n;
        string s;
        cin>>n>>s;
        vector<int>a(n);
        rep(i,n)cin>>a[i];
        
        ll ans=0;
        rep(z,2){
            vector<int>b(n);
            rep(i,n)b[i]=s[i]=='('?1:-1;
            priority_queue<P,vector<P>,greater<P>>q;
            int sum=0;
            rep(i,n){
                sum+=b[i];
                if(b[i]==-1){q.push({a[i],i});}
                if(sum<0){
                    auto p=q.top();q.pop();
                    int val=p.first,j=p.second;
                    ans+=val;
                    s[j]*=-1;
                    sum+=2;
                }
            }
            reverse(s.begin(),s.end());
            reverse(a.begin(),a.end());
            rep(i,n)s[i]=(s[i]=='('?')':'(');
            //cout<<s<<endl;
        }

        cout<<ans<<endl;
    }  

    int main(){
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        
        solve();  

        return 0;
    }
accuracy: 1
time_ms: 20
memory_kb: 9024
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(ll i=0;i<n;i++)
#define repl(i,l,r) for(ll i=(l);i<(r);i++)
#define per(i,n) for(ll i=(n)-1;i>=0;i--)
#define perl(i,r,l) for(ll i=r-1;i>=l;i--)
#define fi first
#define se second
#define pb push_back
#define ins insert
#define pqueue(x) priority_queue<x,vector<x>,greater<x>>
#define all(x) (x).begin(),(x).end()
#define CST(x) cout<<fixed<<setprecision(x)
#define rev(x) reverse(x);
using ll=long long;
using vl=vector<ll>;
using vvl=vector<vector<ll>>;
using pl=pair<ll,ll>;
using vpl=vector<pl>;
using vvpl=vector<vpl>;
const ll MOD=1000000007;
const ll MOD9=998244353;
const int inf=1e9+10;
const ll INF=4e18;
const ll dy[8]={1,0,-1,0,1,1,-1,-1};
const ll dx[8]={0,1,0,-1,1,-1,1,-1};
template <typename T> inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, true) : (false));
}
template <typename T> inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, true) : (false));
}
int main(){
  ll n;cin >> n;
  string s;cin >> s;
  vl v(n);rep(i,n)v[i]=(s[i]=='('? 1:-1);
  vl a(n);rep(i,n)cin >> a[i];
  ll ans=0;
  priority_queue<pl,vpl,greater<pl>> rt;
  ll cum=0;
  rep(i,n){
    cum+=v[i];
    if(v[i]==-1){
      rt.push({a[i],i});
    }
    if(cum<0){
      auto [val,idx]=rt.top();rt.pop();
      ans+=val;v[idx]*=-1;
      cum+=2;
    }
  }
  rev(all(a));rev(all(v));
  rep(i,n)v[i]*=-1;
  cum=0;
  while(rt.size())rt.pop();
  rep(i,n){
    cum+=v[i];
    if(v[i]==-1){
      rt.push({a[i],i});
    }
    if(cum<0){
      auto [val,idx]=rt.top();rt.pop();
      ans+=val;v[idx]*=-1;
      cum+=2;
    }
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 60
memory_kb: 9400
final_rank: 18

code_snippet: #include <bits/stdc++.h>
#include <iostream>
#include <limits>
#include <numeric>
#include <type_traits>
#include <bitset>
#include <map>
#include <unordered_map>
#include <set>

using namespace std;

#define rep(i,n,m) for(ll (i)=(n);(i)<(m);(i)++)
#define rrep(i,n,m) for(ll (i)=(n);(i)>(m);(i)--)
using ll = long long;
const ll mod = 998244353;
const ll inf = 1e9;
const ll INF = 1e18;


void pline(vector<ll> lis){
    rep(i,0,lis.size()){
        printf ("%lld",lis[i]);
        if (i != lis.size()-1) printf(" ");
        else printf("\n");
    }
}

int main(){

    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    //ModFac mf(200000);

    ll N;
    cin >> N;

    string s;
    cin >> s;

    vector<ll> S(N);
    rep(i,0,N){
        if (s[i] == '(') S[i] = 1;
        else S[i] = -1;
    }

    vector<ll> A(N);
    rep(i,0,N) cin >> A[i];

    //前から見て行って、累積和が負になったら )を1個反転する
    ll ans = 0;

    {
        ll sum = 0;
        priority_queue<pair<ll,ll>> q;

        rep(i,0,N){
            if (S[i] == -1){
                q.push(make_pair(-A[i],i));
            }
            sum += S[i];

            if (sum < 0){
                ll ind = q.top().second;
                ans -= q.top().first;
                S[ind] *= -1;
                sum += 2; 
                q.pop();
            }
        }
    }


    {
        ll sum = 0;
        priority_queue<pair<ll,ll>> q;

        rrep(i,N-1,-1){
            if (S[i] == 1){
                q.push(make_pair(-A[i],i));
            }
            sum += S[i];

            if (sum > 0){
                ll ind = q.top().second;
                ans -= q.top().first;
                S[ind] *= -1;
                sum -= 2; 
                q.pop();
            }
        }
    }

    cout << ans << endl;



}

/*

https://drive.google.com/drive/u/2/folders/1gZBJHglPKtJR9h8ZRL2vd6MSQTxiqamZ

*/
accuracy: 1
time_ms: 20
memory_kb: 10476
final_rank: 16