結果

問題 No.3147 Parentheses Modification and Rotation (RM Ver.)
ユーザー naniwazu
提出日時 2025-05-14 04:44:02
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 82 ms / 2,000 ms
コード長 949 bytes
コンパイル時間 508 ms
コンパイル使用メモリ 82,600 KB
実行使用メモリ 80,384 KB
最終ジャッジ日時 2025-05-14 04:44:07
合計ジャッジ時間 4,186 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict

N = int(input())
if N % 2 != 0:
    print(-1)
    exit()

S = input()
R, M = map(int, input().split())

accum = [0] + [1 if s == "(" else -1 for s in S] * 2
for i in range(2 * N):
    accum[i + 1] += accum[i]

count = defaultdict(int)
range_min = 0
for i in range(N + 1):
    count[accum[i]] += 1
    range_min = min(range_min, accum[i])

ans = float("inf")

for i in range(N):
    rotation_cost = (N - i) % N * R
    accum_left = accum[i]
    accum_right = accum[i + N]
    close_to_open_required = (accum_left - range_min + 1) // 2
    open_to_close_required = (accum_right - range_min + 1) // 2
    modification_cost = (close_to_open_required + open_to_close_required) * M
    ans = min(ans, rotation_cost + modification_cost)

    count[accum[i]] -= 1
    count[accum[i + N + 1]] += 1
    if count[range_min - 1] > 0:
        range_min -= 1
    elif count[range_min] == 0:
        range_min += 1

print(ans)
0