cswork / OAOpen practice workspace

AmazonOA #157

Find Max To Balance

Estimated MediumJudge-ready

Topics (AI-labelled)Stacks & HeapsGreedy

The original bracket string scores 0. Each bracket in kit has its own rating and can be used at most once, and you may choose none; insert the chosen brackets anywhere in the original string, keeping the original order, to get a balanced bracket string, and maximize the total rating of the chosen brackets. Completion is guaranteed to be possible.

Input

The first line contains the original string s, the second line contains kit, and the third line contains the rating of each character of kit. This site sets 1≤|s|,|kit|≤100000 and ratings in −10^9..10^9.

Output

Output a single integer answer.

Example 1

Input:

()
(())
4 2 -3 -3

Output:

1

Example 2

Input:

)
(
-5

Output:

-5

Example 3

Input:

()
()
-1 -2

Output:

0

Example notes

Example 1: choose the left bracket rated 4 and the right bracket rated −3 for a gain of 1; choosing one more pair would lower the total. Example 2: the only left bracket must be added, so the answer is −5. Example 3: the original string is already balanced, so choosing no brackets gives 0.

Editorial

Loading solution…