Problem:


Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:  

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))



Sample input:
3
())


Sample output:
(())

Submission status: Runtime Error

Solution code:
def power(a, n, mod):
  bi=str(format(n,"b")) #2進数
  res=1
  for i in range(len(bi)):
    res=(res*res) %mod
    if bi[i]=="1":
      res=(res*a) %mod
  return res

n, m, p = map(int, input().split())
print(power(n, p, m))

Submission status: Runtime Error

Solution code:
n=int(input())
s=input()
ans=s

c=s.count('()')
while c!=0:
  s=list(s)

  i=0
  n_s=''
  while i<=len(s)-1:
    if s[i]=='(' and s[i+1]==')':
      i+=2
    else:
      n_s+=s[i]
      i+=1

  s=''.join(n_s)
  c=s.count('()')

c_a=s.count('(')
c_b=s.count(')')

ans='('*c_b+ans+')'*c_a
print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
s=input()
ans=s

c=s.count('()')
while c!=0:
  s=list(s)
  i=0
  while i<=len(s)-1:
    if s[i]=='(' and s[i+1]==')':
      del s[i]
      del s[i+1]
    else:
      i+=1
  s=''.join(s)
  c=s.count('()')

c_a=s.count('(')
c_b=s.count(')')

ans='('*c_b+ans+')'*c_a
print(ans)

Submission status: Runtime Error

Solution code:
N, S = open('0').read().split()
N = int(N)
cnt = 0
l = 0
for i in range(N):
  if S[i]=='(':
    cnt += 1
  else:
    if cnt==0:
      l += 1
    else:
      cnt -= 1
cnt = 0
r = 0
for i in range(N-1,-1,-1):
  if S[i]==')':
    cnt += 1
  else:
    if cnt==0:
      r += 1
    else:
      cnt -= 1
print('('*l+S+')'*r)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
using namespace std;
typedef long long int ll;
typedef pair<int,int> P;
#define yn {puts("Yes");}else{puts("No");}
#define MAX_N 200005

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int a = 0, b = 0;
    drep(i,n){
        if(s[i]==')') a++;
        else a = max(0, a - 1);
    }
    rep(i,n){
        if(s[i]=='(') b++;
        else b = max(0, b - 1);
    }
    rep(i,a) cout << '(';
    rep(i,n) cout << s[i];
    rep(i,b) cout << ')';
    cout << endl;

    return 0;
}

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

x = n - s[::-1].find(")")
l = 0
r = 0
for i in range(x):
    if s[i] == "(":
        l += 1
    else:
        r += 1

if l < r:
    ans = "(" * (r - l) + s
print(ans + ")" * max(0, (ans.count("(") - ans.count(")"))))

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
#print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        #print(S)
        #print(i)
        if S[i]=="(" and S[i+1] ==")":
            # print(S, i)
            flag = 1
            del S[i] 
            del S[i]
            i -= 1
            # print(S, i)
        i += 1
        i = max(0,i)
        #print(i, len(S))
        if i+1>=len(S):
            flag2 = 0
a=0
b=0
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
#print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
#print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        #print(S)
        #print(i)
        if S[i]=="(" and S[i+1] ==")":
            # print(S, i)
            flag = 1
            del S[i] 
            del S[i]
            i -= 1
            # print(S, i)
        i += 1
        i = max(0,i)
        #print(i, len(S))
        if i+1>=len(S):
            flag2 = 0
a=0
b=0
print(S)
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
#print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
#print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        #print(S)
        #print(i)
        if S[i]=="(" and S[i+1] ==")":
            flag = 1
            del S[i] 
            del S[i+1]
            i -= 2
        i += 1
        i = max(0,i)
        #print(i, len(S))
        if i+1>=len(S):
            flag2 = 0
a=0
b=0
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
#print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
#print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        #print(i)
        if S[i]=="(" and S[i+1] ==")":
            flag = 1
            del S[i] 
            del S[i+1]
            i -= 2
        i += 1
        i = max(0,i)
        if i>=len(S):
            flag2 = 0
a=0
b=0
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
#print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
#print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        #print(i)
        if S[i]=="(" and S[i+1] ==")":
            flag = 1
            del S[i] 
            del S[i+1]
            i -= 2
        i += 1
        i = max(0,i)
        if i>len(S):
            flag2 = 0
a=0
b=0
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
#print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N= int(input())
S=input()
SS= copy.copy(S)
S = list(S)
#N, A, B = map(int, input().split())

flag = 1
print(len(S))
while flag == 1:
    flag = 0
    flag2 = 1
    i = 0
    while flag2:
    # for i in range(len(S)-1):
        print(i)
        if S[i]=="(" and S[i+1] ==")":
            flag = 1
            del S[i] 
            del S[i+1]
            i -= 2
        i += 1
        i = max(0,i)
        if i>len(S):
            flag2 = 0
a=0
b=0
for i in range(len(S)):
    if S[i]=="(":
        b+=1
    elif S[i]==")":
        a+=1
print(S)
# initialization of string to ""
A = ""
B = ""

# traverse in the string
for x in range(a):
    
    A += "("   
for x in range(b):    
    B += ")"   

        
#print(str(A)+SS+str(B))
print(A+SS+B)

Submission status: Runtime Error

Solution code:
N=int(input())
s=input()
ans = s
flag_A = True
r = 0
l = 0
while flag_A:
    flag_B =False
    for n,i in enumerate(s[:-2]):
        if i =="(" and s[n+1] ==")":
            s = s[:n]+s[n+2:]
            flag_B = True
    if not flag_B:
        flag_A = False
for i in s:
    if i ==")":
        r += 1
    else:
        l += 1
print("("*r+ans+")"*l)

Submission status: Runtime Error

Solution code:
N=int(input())
s=input()
ans = s
flag_A = True
r = 0
l = 0
while flag_A:
    flag_B =False
    for n,i in enumerate(s):
        if n!=N-1 and  i =="(" and s[n+1] ==")":
            s = s[:n]+s[n+2:]
            flag_B = True
    if not flag_B:
        flag_A = False
for i in s:
    if i ==")":
        r += 1
    else:
        l += 1
print("("*r+ans+")"*l)

Submission status: Runtime Error

Solution code:
def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))
# import sys
# input = sys.stdin.readline

N=one_int()
S=one_str()

first_start_index=S.index("(")

count=0
for i in range(first_start_index, N):
    if S[i]=="(":
        count += 1
    else:
        count -= 1

#count　がプラス   => その分閉じカッコが後ろにつく
#count  がマイナス => その分開始カッコが銭湯に付く
ans=S
if count >0:
    ans+= ")"*count
else:
    ans = "("*int(abs(count)) +ans

ans = first_start_index*"(" + ans

print(ans)

Submission status: Runtime Error

Solution code:
N = int(input)
S = input()

d = S.replace('()','')

l = d.count('(')
r = d.count(')')

z = '('*l + d + ')'*r

print(z)

Submission status: Runtime Error

Solution code:
import queue
n=int(input())
s=input()
q=queue.Queue(s)
def br(a):
  for i in range(1,len(a)+1):
    if a[:i].count("(")<a[:i].count(")"):
      return ")"
  if a.count("(")==a.count(")"):
    return "0"
  else:
    return "("
for i in range(1,len(s)+1):
  if s[:i].count("(")<s[:i].count(")"):
    s.append("(")

Submission status: Runtime Error

Solution code:
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(long long i = 0; i < n; ++i)
typedef long long ll;
const ll MOD = 1e9+7;

int main(){
    int n; string s;
    cin >> n >> s;
    int lcnt = 0,rcnt = 0;
    int lnum = 0, rnum = 0;
    for(int i = 0; i < n; ){ // ( に対して) が少ない場合に付け足す
        lcnt = 0;
        rcnt = 0;
        while(i < n && s[i] == '('){
            lcnt++;
            i++;
            //cout << i << endl;
        }
        while(i < n && s[i] == ')'){
            rcnt++;
            i++;
        }
        //cout << lcnt << " " << rcnt << " " << lcnt - rcnt << endl;
        if(lcnt > rcnt) rnum += lcnt - rcnt;
    }

    for(int i = n-1; i >= 0; ){
        lcnt = 0;
        rcnt = 0;
        while(i >= 0 && s[i] == ')'){
            rcnt++;
            i--;
        }
        while(i >= 0 && s[i] == '('){
            lcnt++;
            i--;
        }
        //cout << rcnt - lcnt << endl;
        if(rcnt - lcnt) lnum += rcnt - lcnt;
    }
    rep(i,lnum) cout << '(';
    cout << s;
    rep(i,rnum) cout << ')';
}

Submission status: Runtime Error

Solution code:
def groupby(a):
    a2=[[a[0],1]]
    for i in range(1,len(a)):
        if a2[-1][0]==a[i]:
            a2[-1][1]+=1
        else:
            a2.append([a[i],1])
    return a2

n=int(input())
s=input()
t=groupby(s)
c=s.count("(")-s.count(")")
if c>0:
    s=s+c*")"
else:
    s=(-c)*"("+s
if t[0][0]==")":
    s=("("*t[0][1])+s+(")"*t[0][1])
if t[-1][0]=="(":
    s=+("("*t[-1][1])+s+(")"*t[-1][1])
print(s)

Submission status: Runtime Error

Solution code:
N=int(input())
S=input()
sl=list(S)
change=[0]
for i in range(1,N):
  if (sl[i-1]==')')and(sl[i]=='('):
    change.append(i)

change.append(N)
r_add=0
l_add=0
for i in range(len(change)-1):
  A=sl[change[i]:change[i+1]]
  r=0
  l=0
  for a in A:
    if a=='(':
      l+=1
    else:
      r+=1
      
  if r==l:
    continue
  elif r>l:
    l_add+=r-l
    r_add=max(0,r_add-(r-l))
  else:
    r_add+=l-r
      
print('('*l_add+S+')'*r_add)print('('*l_add+S+')'*r_add)

Submission status: Runtime Error

Solution code:
N=int(input())
S=input()
sl=list(S)
change=[0]
ans=''
for i in range(N+1):
  if (sl[i-1]==')')and(sl[i]=='('):
    change.append(i)

change.append(N)
for i in range(len(change)-1):
  A=sl[change[i]:change[i+1]]
  r=0
  l=0
  for a in A:
    if a=='(':
      l+=1
    else:
      r+=1
      
  if r==l:
    ans+=''.join(A)
  elif r>l:
    ans+='('*(r-l)+''.join(A)
  else:
    ans+=''.join(A)+')'*(l-r)
      
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
N = int(input())
edge = [[] for _ in range(N+1)]
for _ in range(N-1):
    a,b,c = map(int,input().split())
    edge[a].append((b,c))
    edge[b].append((a,c))
Q,K = map(int,input().split())
distance = [None] * (N+1)
def dfs(v1,d):
    distance[v1] = d
    for v2,dd in edge[v1]:
        if distance[v2] is not None:
            continue
        dfs(v2,d+dd)

dfs(K,0)

ans = [0] * Q
for i in range(Q):
    x,y = map(int,input().split())
    ans[i] = distance[x]+distance[y]
for a in ans:
    print(a)

Submission status: Runtime Error

Solution code:
from collections import deque

n = int(input())
s = input()
lCnt = 0
rCnt = 0
stack = deque()
stack.append(s[0])

for i in range(1, len(s)):
    prev = stack.pop()

    if prev == '(' and s[i] == ')':
        continue
    else:
        stack.append(prev)
        stack.append(s[i])

#print(stack)

for i in range(len(stack)):
    if stack[i] == '(':
        lCnt += 1
    else:
        rCnt += 1

s += ')' * lCnt
s = '(' * rCnt + s

print(s)

Submission status: Runtime Error

Solution code:
N = int(input())
S = input()

for i in reversed(range(N)):
    if S[i] == ")":
        tmp = i
        break
left = ""
for i in range(N-tmp-1):
    left += ")"

migi_kakko = 0
hidari_kakko = 0
for i in range(tmp+1):
    if S[i] == ")":
        migi_kakko += 1
    else:
        hidari_kakko += 1

right = ""
for i in range(migi_kakko-hidari_kakko):
    right += "("
for i in range(hidari_kakko-migi_kakko):
    left += ")"

ans = ""
ans += right
ans += S
ans += left
print(ans)

Submission status: Runtime Error

Solution code:
import sys


def main():
    n, s = sys.stdin.read().split()
    n = int(n)

    for i in range(n):
        if s[i] == ')':
            continue
        else:
            i_l = i
            break
    for i in range(n, 0, -1):
        if s[i-1] == '(':
            continue
        else:
            i_r = i
            break
    res_l = '(' * len(s[:i_l]) + s[:i_l]
    res_r = s[i_r:] + ')' * len(s[i_r:])

    c = s[i_l:i_r]
    count = c.count('(') - c.count(')')
    if count == 0:
        ans = res_l + c + res_r
    elif count < 0:
        ans = '(' * abs(count) + res_l + c + res_r
    else:
        ans = res_l + c + res_r + ')' * count
    print(ans)
    # s = '.' + s
    
    # # 左右から一度ずつチェック
    # # 左から
    # count = 0
    # flag = False
    # for i in range(1, len(s)):
    #     if s[i] == ')':
    #         if not flag:
    #             count += 1
    #         else:
    #             flag = False
    #     elif s[i] == '(':
    #         if s[i-1] == '.':
    #             count -= 1
    #         elif s[i-1] == ')':
    #             flag = True
    #         elif s[i-1] == '(':
    #             if not flag:
    #                 count -= 1
    #             else:
    #                 break
    
    # s = s.replace('.', '') + '.'
    # if count >= 1:
    #     s = '(' * count + s


    # count = 0
    # flag = False
    # for i in range(len(s)-2, -1, -1):
    #     if s[i] == '(':
    #         if not flag:
    #             count += 1
    #         else:
    #             flag = False
    #     elif s[i] == ')':
    #         if s[i+1] == '.':
    #             count -= 1
    #         elif s[i+1] == '(':
    #             flag = True
    #         elif s[i+1] == ')':
    #             if not flag:
    #                 count -= 1
    #             else:
    #                 break
    #     print(count)
    
    # s = s.replace('.', '')
    # if count >= 1:
    #     s = s + ')' * count

    # print(s)

            

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n=int(input())
S=list(input())

i,cnt1=0,0
ins=[0]*(n+1)
while i<len(S):
  if S[i]=='(':
    cnt1+=1
    i+=1
  else:
    j,cnt2=0,0
    while i<len(S):
      if S[i]=='(':
        break
      else:
        cnt2+=1
      i+=1
      
    tmp=''
    if cnt2>cnt1:
      for _ in range(cnt2-cnt1):
        tmp+='('
      ins[i-(cnt1+cnt2)]=tmp
    elif cnt1>cnt2:
      for _ in range(cnt1-cnt2):
        tmp+=')'
      ins[i]=tmp
    cnt1,cnt2=0,0

if cnt1>0 and cnt2==0:
  tmp=''
  for _ in range(cnt1):
    tmp+=')'
  ins[-1]=tmp
for i,s in enumerate(ins):
  if s!=0:
    if i==0:
      S.insert(i,s)
    else:
      S.insert(i+1,s)
print(*S,sep='')

Submission status: Runtime Error

Solution code:
n = int(input())
s = str(input())
r = [i for i in range(n) if s[i] == "("]
l = [i for i in range(n) if s[i] == ")"]
if r == []: print(n*"(" + s)
elif l == []: print(s + n*")")
elif min(r) > max(l):
    print(len(l)*"(" + s + len(r)*")")
else:
    cnt = 0
    for i in reversed(range(len(r))):
        if r[i] < max(l):
            cnt += 1
            l.pop(-1)
    print((len(l)) * "(" + s + (len(r) - cnt) * ")")

Submission status: Runtime Error

Solution code:
n = int(input())
s = str(input())
r = [i for i in range(n) if s[i] == "("]
l = [i for i in range(n) if s[i] == ")"]
if min(r) > max(l):
    print(len(l)*"(" + s + len(r)*")")
else:
    cnt = 0
    for i in range(len(r)):
        if r[i] < max(l):
            cnt += 1
            l.pop(-1)
    print((len(l)) * "(" + s + (len(r) - cnt) * ")")

Submission status: Runtime Error

Solution code:
#insertion
n=int(input())
s=input()
count=1
countlist=[]
s=s+"X"
for i  in range(n):
    if s[i]==s[i+1]:
        count+=1
    else:
        if s[i]=="(":
            countlist.append((count,"L"))
        else:
            countlist.append((count,"R"))
        count=1

if len(countlist)%2==0 and countlist[0][1]=="L":
    pass
elif len(countlist)%2!=0 and countlist[0][1]=="L":
    countlist.append((countlist[-1][0],"R"))
elif len(countlist)%2==0 and countlist[0][1]=="R":
    countlist.append(countlist[-1][0],"R")
    countlist=[(countlist[0][0],"L")]+countlist
elif len(countlist)%2!=0 and countlist[0][1]=="R":
    countlist=[(countlist[0][0],"L")]+countlist

ans=""
for i in range(0,len(countlist),2):
    x=max(countlist[i][0],countlist[i+1][0])
    ans=ans+"("*x+")"*x
print(ans)

Submission status: Runtime Error

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    s = str(input().rstrip('\n'))
    t = s
    while True:
        l_len = len(s)
        while True
            s = s.replace("()", "")
            if len(s) == l_len:
                break
            else:
                l_len = len(s)
        if len(s) == 0:
            print(t)
            exit()
        else:
            if s[0] == ")":
                s = "".join((list("(") + list(s)))
                t = "".join((list("(") + list(t)))
            else:
                s = "".join((list(s)) + list(")"))
                t = "".join((list(t)) + list(")"))


if __name__ == '__main__':
    slove()

Submission status: Runtime Error

Solution code:
N=int(input())
S=input()

temp=list(S)
f=True

while f:
    f=False
    L=len(temp)
    for i in range(L-2,-1,-1):
        if  "".join(temp[i:i+2])=="()":
            temp.pop(i+1)
            temp.pop(i)
            f=True

Ltemp=len(temp)
if temp[0]=="(":
    add=")"*len(temp)
    ans=S+add
else:
    cnt1=0
    cnt2=0
    for i in range(Ltemp):
        if temp[i]==")":
            cnt1+=1
        else:
            cnt2+=1
        add1="("*cnt1
        add2=")"*cnt2
    ans=add1+S+add2


print(ans)

Submission status: Runtime Error

Solution code:
#%%
N = int(input())
S = list(input())

T = S.copy()

flag = False

#print(S)


for i in range(N):
    flag = False
    i = 0
    while True:
        if i > len(S) - 1:
            break
        if S[i] == '(':
            tmp = i
            flag = True
        if flag and S[i] == ')':
            S.pop(tmp)
            S.pop(i)
            flag = False
        i += 1

#print(S)
#print(T)

a = S.count('(')
b = S.count(')')

ans = '('*b + ''.join(T) + ')'*a
print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

lcount = 0
rcount = 0

while s[lcount] == ")":
    lcount += 1

while s[n-1-rcount] == "(":
    rcount += 1

res = "(" * lcount + s + ")" * rcount

l = s.count("(")
r = s.count(")")

if l > r:
    res = res + ")" * (l-r)

elif r > l:
    res = "(" * (r-l) + res

print(res)

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

left = 0
leftplus = 0
for i in range(len(s)):
    if s[i] == '(':
        left += 1
    else:
        if left == 0:
            leftplus += 1
        else:
            left -= 1

right = 0
rightplus = 0
r = s[::-1]
for i in range(len(reverse)):
    if r[i] == ')':
        right += 1
    else:
        if right == 0:
            rightplus += 1
        else:
            right -= 1
print('('*leftplus + s + ')'*rightplus)

Submission status: Runtime Error

Solution code:
from collections import deque

N = int(input())
S = input()
ans = deque(S)
S += " "

ind = 0
for _ in range(N):
    if S[ind] == "(" and S[ind+1] == ")":
        ind += 2
        continue
    elif S[ind] == ")":
        ans.appendleft("(")
    elif S[ind] == "(":
        ans.append(")")
    ind += 1

print("".join(ans))

Submission status: Runtime Error

Solution code:
from collections import deque

N = int(input())
S = input()

ans = deque(S)

ind = 0
for _ in range(N-1):
    if S[ind] == "(" and S[ind+1] == ")":
        ind += 2
        continue
    elif S[ind] == ")":
        ans.appendleft("(")
    elif S[ind] == "(":
        ans.append(")")
    ind += 1

print("".join(ans))

Submission status: Runtime Error

Solution code:
N = int(input())
S = list(input())

a = 0
b = 0
c = 0
d = 0

a = [i for i, x in enumerate(S) if x == '('][0]
b = [i for i, x in enumerate(S) if x == ')'][-1]

light_a = S[:b+1].count('(')
light_b = S[:b+1].count(')')
left_a = S[a:].count('(')
legt_b = S[a:].count(')')

#print(light_a, light_b, left_a, legt_b)
c = max(0, light_b - light_a)
d = max(0, left_a - legt_b)
#print(c, d)

#print(a, b)
S = '('*c + ''.join(S) + ')'*d
print(S)

Submission status: Runtime Error

Solution code:
# ABC064D - Insertion
def main():
    # count shortages on both sides -> restore
    N = int(input())
    S = input().rstrip()
    l, r = i.count("("), i.count(")")
    ans = "(" * max(0, r - l) + i + ")" * max(0, l - r)
    print(ans)
    


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
s - input()
cnt = 0
m = 0
for i in s:
    if i == ')':
        cnt += 1
    else:
        cnt -= 1
    m = max(m, cnt)
print('()'*m+s+')'*(m-cnt))

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()
t = s
r = 0
l = 0
id=n-1
while t[id]=='(':
    r+=1
    id-=1
t = t[:id+1]
id = 0
while id<len(t) and t[id]==')':
    l+=1
    id+=1
t = t[id:]
if t.count('(')>t.count(')'):
    r+=t.count('(')-t.count(')')
else:
    l+=t.count(')')-t.count('(')
print('('*l+s+')'*r)

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

num = 0
lmax = 0
rmax = 0
for i in range(n):
    if s[i] == ")":
        num += 1
    else:
        num -= 1
    if num == -1:
        
    lmax = max(lmax, num)

num = 0
for i in range(n-1, -1, -1):
    if s[i] == "(":
        num += 1
    else:
        num -= 1
    rmax = max(rmax, num)

print("("*lmax + s + ")"*rmax)

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

num = 0
l = 0
r = 0
for i in range(n):
    if s[i] == ")":
        num += 1
    else:
        num -= 1
    if num == -1:
        l += 1
        num = 0

num = 0
for i in range(n-1, 0, -1):
    if s[i] == "(":
        num += 1
    else:
        num -= 1
    if num == 01:
        r += 1
        num = 0

print("("*l + s + ")"*r)

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()
x = 0
xm = float('inf')
for i in range(n):
    if s[i] == '(':
        x += 1
    elif s[i] == ')':
        x -= 1
        xm = min(xm, x)
print('(' * -xm + s + ')' * (x - xm))

Submission status: Runtime Error

Solution code:
N = int(input())
S = input()

pares = S[:]

counter = 0
pares_num = []
for s in pares:
    if s == '(':
        counter += 1
        pares_num.append(counter)
    else:
        counter -= 1
        pares_num.append(counter)
        
min_num = min(pares_num)
if min_num < 0:
    pares = '(' * (-1*min_num) + pares
    

counter = 0
pares_num = []
for s in pares:
    if s == '(':
        counter += 1
        pares_num.append(counter)
    else:
        counter -= 1
        pares_num.append(counter)
#print(pares)
#print(pares_num)

zeros = [i for i, x in enumerate(pares_num) if x == 0]
max_num = max(pares_num[zeros[-1]:])
pares += ')' * max_num

print(pares)

Submission status: Runtime Error

Solution code:
n=int(input())
s=input()
t=s[0]
chk=0
d=[]
for i in s:
    if i==")"==t:
        chk-=1
    elif i=="("==t:
        chk+=1
    else:
        d.append(chk)
        t=["(",")"][i==")"]
        chk=[1,-1][i==")"]
d.append(chk)
if d[0]<0: d=[0]+d
if d[-1]>0: d.append(d[-1]*-1)
p=sum(d)
if p<0: ans[0]+=abs(p)
if p>0: ans[-1]+=p
ans=""
for i in d:
    ans+=["(",")"][i<0]*abs(i)
print(ans)

Submission status: Runtime Error

Solution code:
def trim(S, N):
    a = 0
    while S[a] == ")":
        a += 1
    b = N-1
    while S[b] == "(":
        b -= 1
    return a, b


def count(S, a, b):
    i = a
    c = 0
    while i <= b:
        if S[i] == "(":
            c += 1
        else:
            c -= 1
        i += 1
    return c


N = int(input())
S = input()

a, b = trim(S, N)
if a > b:
    print("(" * a + S + ")" * (N-b-1))
else:
    c = count(S, a, b)

    if c > 0:
        print("(" * a + S + ")" * (N-b-1-c))
    else:
        print("(" * (a-c) + S + ")" * (N-b-1))

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007

#A

#B

#C
"""
f = [0]
for i in range(1,400):
    f.append(0)
for i in range(400,800):
    f.append(1)
for i in range(800,1200):
    f.append(2)
for i in range(1200,1600):
    f.append(3)
for i in range(1600,2000):
    f.append(4)
for i in range(2000,2400):
    f.append(5)
for i in range(2400,2800):
    f.append(6)
for i in range(2800,3200):
    f.append(7)
for i in range(3200,4801):
    f.append(-1)
n = I()
a = LI()
k = [1 for i in range(8)]
s = 0
t = 0
for i in a:
    if f[i] >= 0:
        if k[f[i]]:
            k[f[i]] = 0
            s += 1
    else:
        t += 1
print(max(s,1),min(s+t,n))
"""

#D
n = I()
s = S()
ans = []
k = 0
for i in range(n):
    if s[i] == ")":
        k += 1
    else:
        if k > 0:
            ans += ["("]*k
            k = 0
        k -= 1
if k < 0:
    ans += [")"]*(-k)
else:
    ans = ["("]*k+ans
i = 0
while ans[i] == "(":
    i += 1
    if i == len(ans):break
for j in range(n):
    ans.insert(i+j,s[j])
for i in ans:
    print(i,end = "")
print()
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Runtime Error

Solution code:
N = int(input())
S = list(input())

l_point = 0

left_first = S.index("(")
for i in range(left_first, N):
    if S[i] == "(":
        l_point += 1
    else:
        l_point -= 1

r_point = 0
T = S[::-1]

right_first = T.index(")")
for j in range(right_first, N):
    if T[j] == ")":
        r_point += 1
    else:
        r_point -= 1

migi = ")" * max(0, l_point)
hidari = "(" * max(0, r_point)
center = "".join(S)

print(hidari + center + migi)

Submission status: Runtime Error

Solution code:
N = input()

S = raw_input()
sample = [i for i in S]

i = 0
while i < len(sample)-1:
    if sample[i] == '(' and sample[i+1] == ')':
        del sample[i],sample[i+1]
        i = 0
    i += 1

S = '('*sample.count(')')+S+')'*sample.count('(')
print S

Submission status: Runtime Error

Solution code:
N = int(input())
S = input()

count = 0
for _ in range(N):
    if S[_] == ")":
      count += 1
    else:
      index = _
      break
      
left = "(" * count

count = 0
for _ in range(index, N):
  if S[_] == "(":
    count += 1
  else:
    count -= 1
    
if count < 0:
  left += "(" * abs(count)
  right = ""
else:
  right = ")" * count
  
print(left + S + right)

Submission status: Runtime Error

Solution code:
a = int(input())
ar = list(input())
b = 0
c = 0
t = 0
z = 0
while ar[t] == ")":
    if ar[t] == ")":
        z += 1
    t += 1
for i in range(z):
    ar.insert(0,"(")
for r in ar:
    if r == "(":
        b += 1
    else:
        c += 1
if b > c:
    d = b - c
    for i in range(d):
        ar.append(")")
else:
    d = c - b
    for i in range(d):
        ar.insert(0,"(")
print("".join(ar))

Submission status: Runtime Error

Solution code:
n = int(input())
s = input()

n_left = 0
ans = s
for i in range(n):
  if s[i] == '(':
    n_left += 1
  elif s[i] == ')':
	if n_left == 0:
      ans = '(' + ans
    else:
      n_left -= 1
for i in range(n_left):
  ans += ')'
print(ans)

Submission status: Runtime Error

Solution code:
def insertion(S):
    Sc = S
    Scc = Sc.replace("()", "")
    while Scc != Sc:
        Sc = Scc
        Scc = Scc.replace("()", "")

    # Sc は ((((... or ))))... or ...))))((((...
    # print(Sc)
    if Sc[0] != Sc[-1]:
        pos = Sc.find(")(")
        S = insertion(S[:pos+1]) + insertion(S[pos+1:])
    elif Sc[0] == '(':
        S += ')' * len(Sc)
    else:
        S = '(' * len(Sc) + S

    return S

N = int(input())
print(insertion(input()))

Submission status: Runtime Error

Solution code:
N = int(input())
S = input()

cnt = 0
max_neg = 0
left_add = 0
right_add = 0
for i in range(N):
    if S[i] == '(': cnt += 1
    else:
       cnt -= 1
       if cnt < 0:
           left_add = max(left_add, -cnt)
    for i in range(left_add):
        S.insert(0, '(')
N += left_add

cnt = 0
for i in range(N):
    if S[i] == '(': cnt += 1
    else: cnt -= 1
for i in range(cnt):
    S = S + ')'

print(S)