No.684 Prefix Parenthesis
Problem Statement
A correct parenthesis sequence is defined as follows.
・The empty string is a correct parenthesis sequence.
・If a string $s$ is a correct parenthesis sequence, then '(' $+\ s\ +$ ')' is a correct parenthesis sequence.
・If strings $s,t$ are correct parenthesis sequences, then $s+t$ is a correct parenthesis sequence.
For example, "(())()", "(((())))", and so on are correct parenthesis sequences.
You are given a string $S$ of length $N$ consisting of '(' and ')'. For $1\le i\le N$, let $S_i$ denote the contiguous subsequence of $S$ from the $1$-st character to the $i$-th character. Let $T$ be a string obtained by concatenating $S_1,S_2,\cdots ,S_N$ in any order of your choice. Let $f(T)$ be the maximum length of a string that is a subsequence of $T$ and is a correct parenthesis sequence. Find the maximum value of $f(T)$.
※A subsequence of $S$ means a string obtained by deleting some characters from $S$ and joining the remaining characters without changing their order.
Input
$N$ $S$
$1\le N\le 10^5$
$S$ is a string of length $N$ consisting of '(' and ')'
Output
Find the maximum value of $f(T)$. Print a newline at the end.
Sample
Sample 1
Input
3 )((
Output
4
$S_1=$ ")" $,$ $S_2=$ ")(" $,$ $S_3=$ ")(("
Concatenating in the order $S_2+S_1+S_3$ gives $T=$")())((", and the longest string that is a subsequence of $T$ and a correct parenthesis sequence is "()". Thus $f(T)=2$.
Concatenating in the order $S_3+S_1+S_2$ gives $T=$")(())(", and the longest string that is a subsequence of $T$ and a correct parenthesis sequence is "(())". Thus $f(T)=4$.
No $T$ with $f(T)\gt 4$ exists, so the maximum value of $f(T)$ is $4$.
Sample 2
Input
5 )))))
Output
0
The only possible string for $T$ is ")))))))))))))))", and $f(T)=0$.
Sample 3
Input
10 (((()))()(
Output
34
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。
Pulmn
WA_TLE