#include #include #include #include #include #include #include #include #include using range_add_range_min = atcoder::lazy_segtree< int, [](int x, int y) { return std::min(x, y); }, []{ return 1 << 30; }, int, [](int f, int x) { return f + x; }, [](int f, int g) { return f + g; }, []{ return 0; } >; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::string s; std::cin >> n >> s; std::vector a(2 * n); for (auto &e : a) std::cin >> e; std::vector cost(2 * n); long long ans = 0; for (int i = 0; i < 2 * n; ++i) { if (s[i] == '(') { ans += a[i]; cost[i] = -a[i]; } else { cost[i] = a[i]; } } std::vector p(2 * n); std::iota(p.begin(), p.end(), 0); std::ranges::sort(p, {}, [&cost](int i) { return cost[i]; }); std::vector used(2 * n, false); std::vector init(2 * n + 1); for (int i = 0; i < n; ++i) init[i + 1] = init[i] + 1; for (int i = n; i < 2 * n; ++i) init[i + 1] = init[i] - 1; range_add_range_min seg(init); int r = n - 1; for (int i : p) { used[i] = true; if (i <= r) { ans += cost[i]; continue; } while (r >= 0 and used[r]) --r; if (r < 0) break; if (seg.prod(r + 1, i + 1) >= 2) { ans += cost[i]; seg.apply(r + 1, i + 1, -2); --r; } } std::cout << ans << std::endl; }