問題一覧 > 通常問題

No.684 Prefix Parenthesis

レベル : / AI推定難易度 : 1675 / 実行時間制限 : 1ケース 2.000秒 / メモリ制限 : 512 MB / 標準ジャッジ問題
タグ : (AC するまで非表示) / 解いたユーザー数 29
作問者 : Pulmn / テスター : WA_TLE
お気に入りにしたユーザー ProblemId : 2258 / 自分の提出
問題文最終更新日: 2026-06-28 13:26:35
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 190 (順位表) の他の問題:

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もしくは右上の雲マークをクリックしてアカウントを作成してください。