Best parentheses

시간 제한2초메모리 제한1024 MB

요약
주어진 괄호열에서 올바른 괄호열이 되는 부분수열을 골라 선택한 위치의 가중치 합을 최대로 만든다.
난이도

어려움10점 중 8점

유형
동적 계획법, 그리디, 스택
정답자
아직 제출이 없습니다

문제

A string consisting only of parentheses ‘(‘ and ‘)’ is called balanced if it satisfies one of the following conditions.

  • It is an empty string.
  • It is a concatenation of two non-empty balanced strings.
  • It is a concatenation of ‘(‘, aa, and ‘)’, for some balanced string aa.

You are given nn characters s_1,…,s_ns\_1, \dots , s\_n of parentheses and nn integers c_1,…,c_nc\_1, \dots , c\_n. Then, you have to choose zero or more integers t_1,…,t_kt\_1, \dots ,t\_k so that they satisfy the following conditions.

  • 1≤t_1<t_2<t_3<⋯<t_k≤n1 \le t\_1 < t\_2 < t\_3 < \dots < t\_k \le n.
  • The concatenation of s_t_1,s_t_2,…,s_t_ks\_{t\_1}, s\_{t\_2}, \dots , s\_{t\_k} is a balanced string.

Note that the above conditions are always satisfied if you choose zero integers.

Your task is to maximize ∑_i=1kc_t_i\sum\_{i=1}^{k}{c\_{t\_i}}.

입력

The input consists of a single test case of the following format.

nn

s_1s_2⋯s_ns\_1 s\_2 \cdots s\_n

c_1c\_1 c_2c\_2 ⋯\cdots c_nc\_n

The first line consists of an integer nn (1≤n≤300,0001 \le n \le 300\\,000). The second line consists of nn characters s_1s_2⋯s_ns\_1 s\_2 \cdots s\_n, each of which is either ‘(‘ or ‘)’. The third line consists of nn integers c_1c\_1 c_2c\_2 ⋯\cdots c_nc\_n (∣c_i∣≤109|c\_i| \le 10^9).

출력

Output in a line the maximum possible value of ∑_i=1kc_t_i\sum\_{i=1}^{k}{c\_{t\_i}} by choosing zero or more integers t_1,…,t_kt\_1, \dots ,t\_k.

예제2

  1. 예제 1

    입력
    5
    ()(()
    3 -9 -2 1 0
    
    예상 출력
    3
    
  2. 예제 2

    입력
    6
    )()()(
    -3 1 -4 1 -5 9
    
    예상 출력
    0