結果

問題 No.2591 安上がりな括弧列
ユーザー anonymously
提出日時 2023-12-19 17:03:41
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
TLE  
実行時間 -
コード長 1,135 bytes
コンパイル時間 253 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 224,072 KB
最終ジャッジ日時 2024-09-27 08:55:12
合計ジャッジ時間 4,196 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 9 TLE * 1 -- * 13
権限があれば一括ダウンロードができます

ソースコード

diff #

# coding: utf-8
import heapq

def isValid(S):
    a=0
    for c in S:
        if c=='(':
            a+=1
        elif c==')':
            a-=1
        else:
            raise Exception
        if a<0:
            return False
    return a==0    

def change(S,i):
    L=list(S)
    if S[i]=='(':
        L[i]=')'
    elif S[i]==')':
        L[i]='('
    else:
        raise Exception
    return "".join(L)

def dijkstra(n,S,A):
    closed=set()
    temp={}
    heap=[]
    heapq.heappush(heap,(0,S))
    while heap:
        tupl=heapq.heappop(heap)
        T=tupl[1]
        cost=tupl[0]
        if T not in closed:
            closed.add(T)
            if(isValid(T)):
                return cost
            for i in range(len(T)):
                U=change(T,i)
                if U not in closed:
                    if U not in temp:
                        temp[U]=cost+A[i]
                    else:
                        temp[U]=min(temp[U],cost+A[i])
                    heapq.heappush(heap,(temp[U],U))
    raise Exception

if __name__ == "__main__":
    print(dijkstra(int(input()),input(),list(map(int,input().split()))))
0