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: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys, re

N = input()
S = input()

i = 0
lit = S.split(')(')
l, r = 0, 0
for i, li in enumerate(lit):
    left, right = 0, 0
    if len(lit) > 1:
        kakko = li + ')' if i % 2 == 0 else '(' + li
    else:
        kakko = li
    left, right = 0, 0
    for k in kakko:
        if k == '(':
            left += 1
        else:
            right += 1
    if left > right:
        r += left - right
    else:
        l += right - left

s = '(' * l + S + ')' * r
print(s)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys

N = input()
S = input()

res = ''
left, stack = 0, 0
lit = S.split(')(')
for i, l in enumerate(lit):
    left = 0
    if len(lit) > 1:
        kakko = l + ')' if i % 2 == 0 else '(' + l
    else:
        kakko = l
    j = 0
    while True:
        if len(kakko)-1 < j:
            break
        if kakko[j] == '(':
            if len(kakko) - 1 > j:
                if kakko[j+1] == ')':
                    res += '()'
                    j += 2
                    continue
            left += 1
            j += 1
        else:
            if left != 0:
                left -= 1
            res = '(' + res + ')'
            j += 1
    if i == len(lit) - 1 and len(lit) > 1:
        res += '(' * left + ')' * left
        # print(res)
        # print('aa')
    else:
        stack += left
    # print(stack)
res = '(' * stack + res + ')' * stack

print(res)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys

N = input()
S = input()

res = ''
left, right = 0, 0
lit = S.split(')(')
for i, l in enumerate(lit):
    kakko = l + ')' if i % 2 == 0 else '(' + l
    j = 0
    while True:
        if len(kakko)-1 < j:
            break
        if kakko[j] == '(':
            if len(kakko) - 2 > j:
                if kakko[j+1] == ')':
                    res += '()'
                    j += 2
                else:
                    left += 1
                    j += 1
            else:
                left += 1
                j += 1
        else:
            if left != 0:
                left -= 1
            res = '(' + res + ')'
            j += 1
    part = '(' * left + ')' * left
    res  += part
print(res)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys

N = input()
S = input()

res = ''
lit = S.split(')(')
for i, l in enumerate(lit):
    kakko = l
    if len(lit) > 1:
        kakko = l + ')' if i % 2 == 0 else '(' + l
    right, left = 0, 0
    for k in kakko:
        if k == '(':
            left += 1
        else:
            right += 1
    part = '('*(right-left) + kakko if right > left else kakko + ')'*(left-right)
    res += part
print(res)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys

N = input()
S = input()

res = ''
lit = S.split(')(')
for i, l in enumerate(lit):
    kakko = l
    if len(lit) > 1:
        kakko = l + ')' if i % 2 == 0 else '(' + l
    print(kakko)
    right, left = 0, 0
    for k in kakko:
        if k == '(':
            left += 1
        else:
            right += 1
    part = '('*(right-left) + kakko if right > left else kakko + ')'*(left-right)
    res += part
print(res)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys

N = input()
S = input()

res = ''
lit = S.split(')(')
for i, l in enumerate(lit):
    kakko = l + ')' if i % 2 == 0 else '(' + l
    right, left = 0, 0
    for k in kakko:
        if k == '(':
            left += 1
        else:
            right += 1
    part = '('*(right-left) + kakko if right > left else kakko + ')'*(left-right)
    res += part
print(res)

Submission status: Wrong Answer

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

cnt = 0

ans = []

for s in S:
    if s =="(":
        if cnt >= 0:
            cnt += 1
            ans.append(s)
        else:
            ans.append(s)
            cnt = 0 - cnt
            for _ in range(cnt):
                ans.insert(0, s)
            cnt = 1
    else:
        if cnt <= 0:
            cnt -= 1
            ans.append(s)
        else:
            for _ in range(cnt):
                ans.append(s)
            cnt = 0

if cnt > 0:
    for _ in range(cnt):
        ans.append(")")
elif cnt < 0:
    cnt = 0 - cnt
    for _ in range(cnt):
        ans.insert(0, "(")

print(''.join(ans))

Submission status: Wrong Answer

Solution code:
import copy

n = int(input())
s = input()
deeps = copy.deepcopy(s)

while s.count("()") == 1:
    s = s.replace("()","")

ans = s.count(')')* '(' + deeps + s.count('(')*')'

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
bf = []
af = []
st = ['*']

for c in s:
    if (st[-1] == '(') and (c == ')'):
##        st.pop()
        st.append(c)
        af.pop()
        continue
    else:
        st.append(c)        
    if c ==  ')':
        bf.append('(')
    else:
        af.append(')')
ans = ''.join(bf) + ''.join(st[1:]) + ''.join(af)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
"""
8
())))()(
7
((())()

"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(len(s)):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return [str(i) for i in s1]+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+[str(i) for i in s1]
    else:
        return s1

def insert(s):
    for i in range(len(s)):
        if i<len(s)-1 and s[i]==")" and s[i+1]=="(":
            s=s[:i+1]+" "+s[i+1:]
    return s



slist=insert(s).split(" ")


posct,negct=detect(slist[len(slist)-1])

last=slist[len(slist)-1]

if posct<negct:
    s1=last[:posct*2]
    s2=last[posct*2:]
    slist.pop()
    slist.append(s1)
    slist.append(s2)
    

arrangelist=[]
for i in slist:
    arrangelist+=miniarrange(i)

print("".join(arrangelist))
    


"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def cut(s):
    start=s[0]
    if s[0]==")":
        return 0
    pt=0
    state=0
    while 1:
        if pt>=len(s):
            return -1
        if state==0 and s[pt]==")":
            state=1
        if state==1 and s[pt]=="(":
            break
        pt+=1
    return pt

def perfect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct




def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return s1+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+s1
    else:
        return s1





print(s[:cut(s)])
def arrange(s):
    pt=cut(s)
    s1=s[:cut(s)]
    s2=s[cut(s):]
    return miniarrange(s1) + arrange(s2)









    

posct,negct,ct = detect(s)
print(s[ct+1:])
print(s[:ct+1])


def arrange(s):
    posct,negct,ct=insert(s)
    if ct==len(s):
        return s
    if s[ct+1]=="(":
        s1=s[:ct+1]
        s2=s[ct+1:]
        return s1+arrange(s)
    else:

        
        
        
"""

Submission status: Wrong Answer

Solution code:
n = int(input())
x = input()
s =[]
s += x
l,r = 0,0 #r = ( ; l = )
for i in range(n):
 if s[i] == '(':
  r += 1
 else :
  l += 1
if r - l > 0:
 s += [')']*(r-l)
if r-l < 0:
 s = ['(']*(l-r) + s[:]
if r-l == 0:
 s = ['(']*r + s[:] + [')']*l
print(''.join(s))

Submission status: Wrong Answer

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

    s = S
    while not s.count('()'):
        s = s.replace('()', '')

    if len(s) == 0:
        print(S)
        return

    left = ''
    right = ''
    if s[0] == ')':
        left = '(' * s.count(')')
    if s[-1] == '(':
        right = ')' * s.count('(')

    print('{}{}{}'.format(left, S, right))

main()

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
"""
8
())))()(
7
((())()

"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(len(s)):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return [str(i) for i in s1]+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+[str(i) for i in s1]
    else:
        return s1

def insert(s):
    for i in range(len(s)):
        if i<len(s)-1 and s[i]==")" and s[i+1]=="(":
            s=s[:i+1]+" "+s[i+1:]
    return s



slist=insert(s).split(" ")

posct,negct=detect(slist[len(slist)-1])
if posct<negct:
    slist[len(slist)-1] = ["("]*(negct-posct)+[str(i) for i in slist[len(slist)-1]]

arrangelist=[]
for i in slist:
    arrangelist+=miniarrange(i)

print("".join(arrangelist))
    


"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def cut(s):
    start=s[0]
    if s[0]==")":
        return 0
    pt=0
    state=0
    while 1:
        if pt>=len(s):
            return -1
        if state==0 and s[pt]==")":
            state=1
        if state==1 and s[pt]=="(":
            break
        pt+=1
    return pt

def perfect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct




def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return s1+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+s1
    else:
        return s1





print(s[:cut(s)])
def arrange(s):
    pt=cut(s)
    s1=s[:cut(s)]
    s2=s[cut(s):]
    return miniarrange(s1) + arrange(s2)









    

posct,negct,ct = detect(s)
print(s[ct+1:])
print(s[:ct+1])


def arrange(s):
    posct,negct,ct=insert(s)
    if ct==len(s):
        return s
    if s[ct+1]=="(":
        s1=s[:ct+1]
        s2=s[ct+1:]
        return s1+arrange(s)
    else:

        
        
        
"""

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
"""
8
())))()(
7
((())()

"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(len(s)):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return [str(i) for i in s1]+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+[str(i) for i in s1]
    else:
        return s1

def insert(s):
    for i in range(len(s)):
        if i<len(s)-1 and s[i]==")" and s[i+1]=="(":
            s=s[:i+1]+" "+s[i+1:]
    return s



slist=insert(s).split(" ")

posct,negct=detect(slist[len(slist)-1])
if posct<negct:
    slist[len(slist)-1] = ["("]*(negct-posct)+[str(i) for i in slist[len(slist)-1]]

print(slist)
arrangelist=[]
for i in slist:
    arrangelist+=miniarrange(i)

print("".join(arrangelist))
    


"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def cut(s):
    start=s[0]
    if s[0]==")":
        return 0
    pt=0
    state=0
    while 1:
        if pt>=len(s):
            return -1
        if state==0 and s[pt]==")":
            state=1
        if state==1 and s[pt]=="(":
            break
        pt+=1
    return pt

def perfect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct




def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return s1+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+s1
    else:
        return s1





print(s[:cut(s)])
def arrange(s):
    pt=cut(s)
    s1=s[:cut(s)]
    s2=s[cut(s):]
    return miniarrange(s1) + arrange(s2)









    

posct,negct,ct = detect(s)
print(s[ct+1:])
print(s[:ct+1])


def arrange(s):
    posct,negct,ct=insert(s)
    if ct==len(s):
        return s
    if s[ct+1]=="(":
        s1=s[:ct+1]
        s2=s[ct+1:]
        return s1+arrange(s)
    else:

        
        
        
"""

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
l = []
m = []
for f,s in groupby(S,key = lambda x:x == "("):
    l.append(len(list(s)))
    m.append(f)
if m[0] == False:
    l.insert(0,0)
if m[-1] == True:
    l.append(0)
r = [[l[i],l[i+1]] for i in range(0,len(l)-1,2)]
q = []
for i,j in r:
    if i < j:
        q.append(j)
    else :q.append(i)
resul = []
for i in q:
    resul.append("("*i)
    resul.append(")"*i)
print("".join(resul))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
stack_num = 0
ind = 0
ret = ""
nr = 0
for i in range(ind, n):
    if(s[i] == ")"):
        nr += 1
    else:
        break
if(nr > 0):
    s = "("*nr + s

n = len(s)
# print(ind, ret)
stack_num = 0
for i in range(n):
    if(s[i] == "("):
        stack_num += 1
    else:
        stack_num -= 1
# print(ret, stack_num)
if(stack_num >= 0):
    ret += s + ")"*stack_num
else:
    ret += "("*(-stack_num) + s

print(ret)

Submission status: Wrong Answer

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

    left = ''
    right = ''
    s = S.replace('()', '')
    l = s.count('(')
    r = s.count(')')
    if s[0] == ')':
        left = '(' * r
    if s[-1] == '(':
        right = ')' * l

    print('{}{}{}'.format(left, S, right))

main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
stack_num = 0
ind = 0
ret = ""
nr = 0
for i in range(ind, n):
    if(s[i] == ")"):
        nr += 1
    else:
        break
if(nr > 0):
    ret += "("*nr
    ret += ")"*nr
ind += nr
# print(ind, ret)
stack_num = 0
for i in range(ind, n):
    if(s[i] == "("):
        stack_num += 1
    else:
        stack_num -= 1
# print(ret, stack_num)
if(stack_num >= 0):
    ret += s[ind:n] + ")"*stack_num
else:
    ret += "("*(-stack_num) + s[ind:n]

print(ret)

Submission status: Wrong Answer

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

L = S.count('(')
R = S.count(')')

if L == 0:
    ans = '(' * R + S
elif R == 0:
    ans = S + ')' * L
else:
    rindex = S.rindex(')')
    lindex = S.index('(')
    r_tmp = max(0, N - rindex - 1)
    l_tmp = max(0, lindex)
    l_ = l_tmp * '(' + l_tmp * ')'
    r_ = r_tmp * '(' + r_tmp * ')'
    S_ = S[lindex: rindex+1]
    l = S_.count('(')
    r = S_.count(')')

    if r > l:
        ans = (r - l) * '(' + l_ + S_ + r_
    elif r < l:
        ans = l_ + S_ + r_ + (l - r) * ')'
    else:
        ans = l_ + S_ + r_

print(ans)

Submission status: Wrong Answer

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

L = S.count('(')
R = S.count(')')

if L == 0:
    ans = '(' * R + S
elif R == 0:
    ans = S + ')' * L
else:
    rindex = S.rindex(')')
    lindex = S.index('(')
    r_tmp = max(0, N - rindex - 1)
    l_tmp = max(0, lindex)
    l_ = l_tmp * '(' + l_tmp * ')'
    r_ = r_tmp * '(' + r_tmp * ')'
    S_ = S[lindex: rindex+1]
    l = S_.count('(')
    r = S_.count(')')

    if r > l:
        ans = (r - l) * '(' + l_ + S_ + r_
    elif r < l:
        ans = l_ + S_ + r_ + (l - r) * ')'
    else:
        ans = l_ + S_ + r_
        
    print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
"""
8
())))()(
7
((())()

"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(len(s)):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return [str(i) for i in s1]+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+[str(i) for i in s1]
    else:
        return s1

def insert(s):
    for i in range(len(s)):
        if i<len(s)-1 and s[i]==")" and s[i+1]=="(":
            s=s[:i+1]+" "+s[i+1:]
    return s



slist=insert(s).split(" ")
arrangelist=[]
for i in slist:
    arrangelist+=miniarrange(i)

print("".join(arrangelist))
    


"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def cut(s):
    start=s[0]
    if s[0]==")":
        return 0
    pt=0
    state=0
    while 1:
        if pt>=len(s):
            return -1
        if state==0 and s[pt]==")":
            state=1
        if state==1 and s[pt]=="(":
            break
        pt+=1
    return pt

def perfect(s):
    posct=0
    negct=0
    ct=0
    for i in range(s):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct




def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return s1+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+s1
    else:
        return s1





print(s[:cut(s)])
def arrange(s):
    pt=cut(s)
    s1=s[:cut(s)]
    s2=s[cut(s):]
    return miniarrange(s1) + arrange(s2)









    

posct,negct,ct = detect(s)
print(s[ct+1:])
print(s[:ct+1])


def arrange(s):
    posct,negct,ct=insert(s)
    if ct==len(s):
        return s
    if s[ct+1]=="(":
        s1=s[:ct+1]
        s2=s[ct+1:]
        return s1+arrange(s)
    else:

        
        
        
"""

Submission status: Wrong Answer

Solution code:
import numpy as np
 
n = int(input())
a = input()
s = [0] * n
m = n
count = 0

for i in range(n) :
    if a[i] == '(' :
         s[i] = -1
    else :
         s[i] = 1

for i in range(m) :
    count = s[i]
    if count == 0 :
        continue
    elif count > 0 :
        s.insert(0, -1)
        m = m + 1
        count = count - 1
        i = i + 1
    elif i == m - 1 :
        if count < 0 :
            s.insert(m, 1)
            m = m + 1

for i in range(m) :
    if s[i] == -1 :
        print ('(', end = '')
    else :
        print (')', end = '')
print ()

print (s)

Submission status: Wrong Answer

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

L = S.count('(')
R = S.count(')')

if L == 0:
    ans = '(' * R + S
elif R == 0:
    ans = S + ')' * L
else:
    rindex = S.rindex(')')
    lindex = S.index('(')
    r_tmp = max(0, N - rindex - 1)
    l_tmp = max(0, lindex)
    S_ = S[lindex: rindex+1]
    l = S_.count('(')
    r = S_.count(')')

    ans = l_tmp * '(' + l_tmp * ')'
    if r > l:
        ans = (r - l) * '(' + ans + S_
    elif r < l:
        ans += S_ + (l - r) * ')'

    ans += r_tmp * '(' + r_tmp * ')'

    print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
"""
8
())))()(
7
((())()

"""
def detect(s):
    posct=0
    negct=0
    ct=0
    for i in range(len(s)):
        if s[i]=="(":
            posct+=1
        else:
            negct+=1
    return posct,negct

def miniarrange(s1):
    posct,negct=detect(s1)
    if posct>negct:
        return [str(i) for i in s1]+[")"]*(posct-negct)
    elif posct<negct:
        return ["("]*(negct-posct)+[str(i) for i in s1]
    else:
        return s1

def insert(s):
    for i in range(len(s)):
        if i<len(s)-1 and s[i]==")" and s[i+1]=="(":
            s=s[:i+1]+" "+s[i+1:]
    return s



slist=insert(s).split(" ")
arrangelist=[]
for i in slist:
    arrangelist+=miniarrange(i)

print("".join(arrangelist))

Submission status: Wrong Answer

Solution code:
#! coding:utf-8 -*-
n = int(input())
s = input()
s = list(s)

count = 0
k = 0
ans = []
ls = 's'
for i in range(len(s)):
    if (ls == 's' and s[i] == '(') or (ls == '(' and s[i] == '('):
        count += 1
        ls = '('
    elif s[i] == ')':
        k += 1
        ls = ')'
    elif ls == ')' and s[i] == '(':
        if k - count > 0: 
            for i in range(k - count):
                ans.insert(0,'(')
            for i in range(count):
                ans.append('(')
            for i in range(k):
                ans.append(')')
        else :
            for i in range(count):
                ans.append('(')
            for i in range(k):
                ans.append(')')
            for i in range(k - count):
                ans.append(')')

        k = 0
        count = 1



if k - count > 0: 
    for i in range(k - count):
        ans.insert(0,'(')
    for i in range(count):
        ans.append('(')
    for i in range(k):
        ans.append(')')
else :
    for i in range(count):
        ans.append('(')
    for i in range(k):
        ans.append(')')
    for i in range(k - count):
        ans.append(')')


tmp = 0
for i in range(len(ans)):
    if ans[-1 - i] == '(':
        tmp += 1
    else:
        break

for i in range(tmp):
    ans.append(')')

for i in range(len(ans)):
    print(ans[i],sep = '', end = '')
print()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
l,r = 0,0
for c in s:
	if c == '(':
		l += 1
	else:
		r += 1

if '()' in s:


	if l < r:
		if s.startswith(')'):
			print('('+'('*(r - l) + s + ')')
		else:
			print('('*(r - l) + s)
	elif l > r:
		if s.startswith(')'):
			print('('+s + ')'*(l - r) + ')')
		else:
			print(s + ')'*(l - r))
	else:
		if s.startswith(')'):
			print('(' + s + ')')
		else:
			print(s)

else:
	print('('*r + s + ')'*l)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
bf = []
af = []
st = ['*']

for c in s:
    if (st[-1] == '(') and (c == ')'):
##        st.pop()
        st.append(')')
        af.pop()
        continue
    else:
        st.append(c)        
    if c ==  ')':
        bf.append('(')
    else:
        af.append(')')
ans = ''.join(bf) + ''.join(st[1:]) + ''.join(af)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

bla_input = input()

count_left = 0
count_right = 0

for i in bla_input:
	if i == '(':
		count_left += 1
	else:
		count_right += 1

if count_left > count_right:
	bla_add = ')' * (count_left - count_right)
	bla_result = bla_input + bla_add
elif count_right > count_left:
	bla_add = '(' * (count_right - count_left)
	bla_result = bla_add + bla_input
else:
	bla_result = bla_input

print(bla_result)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
l,r = 0,0
for c in s:
	if c == '(':
		l += 1
	else:
		r += 1

if '()' in s:
	if l < r:
		print('('*(r - l) + s)
	elif l > r:
		print(s + ')'*(l - r))
	else:
		print(s)

else:
	print('('*r + s + ')'*l)

Submission status: Wrong Answer

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

L = S.count('(')
R = S.count(')')

if L == 0:
    ans = '(' * R + S
elif R == 0:
    ans = S + ')' * L
else:
    l = 0
    for i in range(S.rindex(')') + 1):
        if S[i] == '(':
            l += 1

    if R <= l:
        ans = S + ')' * (L - R)
    else:
        ans = '(' * (R - l) + S + ')' * (L - l)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
rs = [c for c in s]
rs.reverse()
stack = [0]*n
for i in range(n):
    if(i > 0):
        stack[-i - 1] = stack[-i]
    if(s[-i - 1] == ')'):
        stack[-i - 1] += 1
    else:
        if(stack[-i - 1] > 0):
            stack[-i - 1] -= 1
# print(stack)
# print(s)
nr = 0
ind = 0
ret = ""
for i in range(n):
    if(stack[i] > nr):
        if(s[ind] != "("):
            ret += "(" * (stack[i] - nr)
            nr += (stack[i] - nr)
        else:
            nr += 1
    elif(stack[i] < nr):
        nr -= 1
    ret += s[ind]
    ind += 1
stack2 = 0
for c in ret:
    if(c == "("):
        stack2 += 1
    else:
        stack2 -= 1
if(stack2 != 0):
    ret += ")"*stack2

print(ret)

# taiou = [None]*n
# for i in range(n):
#     if(s[i] == "("):
#         for j in range(i+1, n):
#             if(s[j] == ")"):
#                 taiou[i] = j
#                 taiou[j] = i
#                 break
#         if(taiou[i] is None):

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
rs = [c for c in s]
rs.reverse()
stack = [0]*n
for i in range(n):
    if(i > 0):
        stack[-i - 1] = stack[-i]
    if(s[-i - 1] == ')'):
        stack[-i - 1] += 1
    else:
        if(stack[-i - 1] > 0):
            stack[-i - 1] -= 1
print(stack)
print(s)
nr = 0
ind = 0
ret = ""
for i in range(n):
    if(stack[i] > nr):
        if(s[ind] != "("):
            ret += "(" * (stack[i] - nr)
            nr += (stack[i] - nr)
        else:
            nr += 1
    elif(stack[i] < nr):
        nr -= 1
    ret += s[ind]
    ind += 1
stack2 = 0
for c in ret:
    if(c == "("):
        stack2 += 1
    else:
        stack2 -= 1
if(stack2 != 0):
    ret += ")"*stack2

print(ret)

Submission status: Wrong Answer

Solution code:
N = int(raw_input())
S = raw_input()
S_sub = S
while ("()" in S):
    S = S.replace("()","")
a = 0
b = 0
for x in S:
    if x == ')':
        a += 1
    else:
        break
for x in S:
    if x == '(':
        b += 1
print a
print b
print "(" * a + S_sub + ")" * b

Submission status: Wrong Answer

Solution code:
N = int(raw_input())
S = raw_input()
S_sub = S
while ("()" in S):
    S = S.replace("()","")
a = 0
b = 0
for x in S:
    if x == ')':
        a += 1
    else:
        break
for x in S:
    if x == '(':
        b += 1
print S
print a
print b
print "(" * a + S_sub + ")" * b

Submission status: Wrong Answer

Solution code:
q = input()

b = input()
br = b

left = ''
right  = ''
for i in range(int(q)):
    if  i == int(q)-1 and br[i] == '(':
        right += ')'
    else:
        
        if br[i] == ')' and br[i-1] != '(':
            left += '('
        elif br[i] == '(' and br[i+1] != ')' :
            right += ')'
print(left + b+ right)

Submission status: Wrong Answer

Solution code:
q = input()

b = input()
br = b
print(br)
left = ''
right  = ''
for i in range(int(q)):
    if  i == int(q)-1 and br[i] == '(':
        right += ')'
    else:
        
        if br[i] == ')' and br[i-1] != '(':
            left += '('
        elif br[i] == '(' and br[i+1] != ')' :
            right += ')'
print(left + b+ right)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = input()
l = a.count("(")
r = a.count(")")

for i in range(r):
    a = "("+a
for j in range(l):
    a = a+")"
    
print(a)

Submission status: Wrong Answer

Solution code:
import numpy as np
def d():
    n = int(input())
    s = input()
    l = [ 1 if x=='(' else -1 for x in s[:] ]
    mt = np.cumsum(l) # mountain
    mi = np.amin(mt)
    left = ''; right = ''
    if mi < 0:
        left = '('*(mi*-1)
    if mt[-1]-mi > 0:
        right = ')'*(mt[-1]-mi)
    # print(mt, mi)
    print(left + s + right)

d()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import array, bisect, collections, copy, heapq, itertools, math, random, re, string, sys, time

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7


def II(): return int(input())
def ILI(): return list(map(int, input().split()))
def IAI(LINE): return [ILI() for __ in range(LINE)]
def IDI(): return {key: value for key, value in ILI()}


def read():
    N = II()
    S = str(input())
    return (N, S)


def solve(N, S):
    ans = collections.deque([])
    count_curl = []
    count = 0
    now = S[0]
    for s in S:
        if s == now:
            count += 1
        else:
            count_curl.append((now, count))
            now = s
            count = 1
    else:
        count_curl.append((now, count))

    for i, now in enumerate(count_curl):
        if i == 0 and now[0] == ")":
            for __ in range(now[1]):
                ans.append("(")
            for __ in range(now[1]):
                ans.append(")")
            continue

        if now[0] == "(":
            for __ in range(now[1]):
                ans.append("(")
            for __ in range(now[1]):
                ans.append(")")
        elif now[0] == ")":
            pre = count_curl[i - 1]
            if now[1] > pre[1]:
                dif = now[1] - pre[1]
                for __ in range(dif):
                    ans.appendleft("(")
                for __ in range(dif):
                    ans.append(")")

    ans = "".join(ans)
    return ans


def main():
    params = read()
    print(solve(*params))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
S1 = "".join(S.split(")("))
S2 = "".join(S1.split(")("))
d = (S2[0] == "(") + (S2[-1] == ")") + (S1 == S or S1 == S2) 
a = S2.count("(") + 2 - d
b = S2.count(")") + 2 - d
print("(" * b + S + ")" * a)

Submission status: Wrong Answer

Solution code:
import numpy as np

N = int(input())
S = list(input())
S_v = np.array(S)
def pop(S):
    index=[]
    for i in range(len(S)-1):
        if S[i]=='('and S[i+1]==')':
            index.append(i)
            index.append(i+1)
    index = np.array(index)
    answer = np.delete(S,index)
    return answer
p = np.array([])
while len(S_v)!=len(p):
    p = S_v
    S_v = pop(S_v)
print (S_v)
n_left = len(np.where(S_v==')')[0])
n_right = len(np.where(S_v=='(')[0])
print ('('*n_left+''.join(S)+')'*n_right)

Submission status: Wrong Answer

Solution code:
N = int(raw_input())
S = raw_input()
S_sub = S
S = S.replace("()","")
a = 0
b = 0
for i in range(len(S)):
    if S[i] == ')':
        a += 1
    if S[i] == '(':
        b += 1
print "(" * a + S_sub + ")" * b

Submission status: Wrong Answer

Solution code:
n=int(input())
data=list(map(lambda x:[str(x),-1],input()))
while 1:
    i=0
    while i<len(data):
        if data[i][0]==')' and data[i][1] == -1:
            break
        i+=1
    if i==len(data):
        break
    j=i-1
    while j>=0:
        if data[j][0]=='(' and data[j][1]==-1:
            data[i][1]=1
            data[j][1]=1
            break
        j-=1
    if j==-1:
        data[i][1]=1
        data.insert(0,['(',1])
while 1:
    i=len(data)-1
    while i>=0:
        if data[i][0]=='(' and data[i][1] == -1:
            break
        i-=1
    if i==-1:
        break
    j=i+1
    x=0
    while j<len(data):
        if data[j][0]=='(':
            x+=1
        else:
            x-=1
        if x==0:
            data[i][1]=1
            data.insert(j+1,[')',1])
            break
        j+=1
    if j==len(data):
        data[i][1]=1
        data.append([')',1])
print(''.join(list(map(lambda x:x[0],data))))