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:
import sys
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

N = ii()
S = input()

pos = 0
r_cnt = 0

while pos < N and S[pos]==')':
    r_cnt += 1
    pos += 1

l_cnt = 0

for i in range(pos, N):
    if S[i]=='(':
        l_cnt += 1
    else:
        l_cnt -= 1

if l_cnt > 0:
    print('('*r_cnt + S + ')'*l_cnt)
elif l_cnt == r_cnt == 0:
    print('(' + S + ')')
else:
    print('('*(r_cnt-l_cnt) + S)

Submission status: Wrong Answer

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

d = [0] * n
nl = 0
nr = 0
for i in range(n):
    if S[i] == '(': nl += 1
    if S[i] == ')': nr += 1
    d[i] = nl - nr

x = min(d)
# print(d)
# print(x)

print('('*(-x) + S + ')'*(d[-1]-x))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=input()
cntl=0
cntr=0
flag=0
for s in S:
    if cntr == 0 and cntl == 0: flag = 0
    if s==")" and cntr==0: cntl += 1
    elif s==")" and cntr>0 and flag:
        cntr -= 1
        if cntl > 0: cntl-= 1
    elif s=="(": 
        cntr += 1
        if flag == 0: flag = 1
    elif s=="(" and cntl>0 and flag: 
        cntl -= 1
        if cntr > 0: cntr -= 1
print(cntl, cntr)
print("("*cntl + S + ")"*cntr)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
a=0 #"("
b=0 #")"
cnt=0
for i in range(n):
    if s[i]=="(":
        if a<b:
            cnt+=b-a
            a,b=1,0
        else:
            a+=1
    else:
        b+=1
if a<b:
    cnt+=b-a
s=(cnt*"("+s)
print(s+")"*(len(s)-s.count("(")))

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
flag=False
for i in range(n-1,-1,-1):
    if s[i]==")":
        a=i
        flag=True
        break

if flag:
    t=s[:a+1]
    x=t.count("(")
    y=len(t)-x
    if x<y:
        print("("*(y-x)+t+"("*(n-a-1)+")"*(n-a-1))
    else:
        print(t+")"*(x-y)+"("*(n-a-1)+")"*(n-a-1))
else:
    print("("*n+")"*n)

Submission status: Wrong Answer

Solution code:
def main():
    from collections import deque
    n = int(input())
    s = input()
    s_ = deque(s)
    left = []
    right = []
    for i in s:
        if i == ")":
            right.append(i)
        else:
            left.append(i)
    if len(right) > len(left):
        times = len(right)-len(left)
        for j in range(times):
            s_.appendleft("(")
    elif len(right) < len(left):
        times = len(left)-len(right)
        for k in range(times):
            s_.append(")")
    else:
        times = len(left)
        if ")(" in s:
            for l in range(times):
                s_.append(")")
                s_.appendleft("(")

    print("".join(s_))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    from collections import deque
    n = int(input())
    s = input()
    s_ = deque(s)
    left = []
    right = []
    for j in s:
        if j == ")":
            right.append(j)
        else:
            left.append(j)
    if len(right) > len(left):
        times = len(right)-len(left)
        for i in range(times):
            s_.appendleft("(")
    elif len(right) < len(left):
        times = len(left)-len(right)
        for i in range(times):
            s_.appendleft(")")
    else:
        times = len(left)
        if ")(" in s:
            for i in range(times):
                s_.append(")")
                s_.appendleft("(")

    print("".join(s_))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
a=0
b=n
if s[0]==')':
    for i in range(n-1):
        if s[i]==')' and s[i+1]=='(':
            a=i
            break
    a+=1
if s[n-1]=='(':
    for i in reversed(range(1,n)):
        if s[i]=='(' and s[i-1]==')':
            b=i
            break

x=s[a:b].count('(')
y=s[a:b].count(')')

if x<y:
    a+=(y-x)
else:
    b-=(x-y)
print(a*'('+s+(n-b)*')')

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    S = input()
    add = ""
    left = 0
    right = 0
    for i in range(N):
        if S[i] == '(':
            left += 1

        else:
            right += 1
            if left < right:
                left += 1
                add += '('

    add2 = ""

    for i in range(N-1,-1,-1):
        if S[i] == '(':
            left += 1
            if left > right:
                right += 1
                add2 += ')'

        else:
            right += 1
    print(add+S+add2)

    
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def test1(s):
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) == 1 and stack[-1] == '(':
            out += '(' + tmp + ')'
            tmp = ''
            stack.pop()
        elif s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''

    for i in range(len(tmp)//2):
        out = '(' + out + ')'

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    return out


def test2(s):
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''
        # print('out', out)
        # print(tmp)

    out += tmp

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    return out


def main():
    N = I()
    s = S()
    c = 0
    stack = deque()

    for i in range(len(s)):
        if s[i] == '(':
            stack.append('(')
            c += 1
        elif len(stack) > 0:
            stack.pop()
            c -= 1
        else:
            c += 1

    # print(c, stack)
    print('(' * c + s + ')' * len(stack))

    # print('out1', out1)
    # print('out2', out2)

    # print(sorted([out1, out2])[0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def test1(s):
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) == 1 and stack[-1] == '(':
            out += '(' + tmp + ')'
            tmp = ''
            stack.pop()
        elif s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''

    for i in range(len(tmp)//2):
        out = '(' + out + ')'

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    return out


def test2(s):
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''
        # print('out', out)
        # print(tmp)

    out += tmp

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    return out


def main():
    N = I()
    s = S()
    out1 = test1(s)
    out2 = test2(s)

    # print('out1', out1)
    # print('out2', out2)

    print(sorted([out1, out2])[0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def main():
    N = I()
    s = S()
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) == 1 and stack[-1] == '(':
            out += '(' + tmp + ')'
            tmp = ''
            stack.pop()
        elif s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''
        # print('out', out)
        # print(tmp)

    # if len(tmp) > 0:
    #     out += tmp
    # print(out, tmp, stack)

    for i in range(len(tmp)//2):
        out = '(' + out + ')'

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    print(out)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def main():
    N = I()
    s = S()
    stack = deque()
    out = ''
    tmp = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) > 0 and stack[-1] == '(':
            tmp = '(' + tmp + ')'
            stack.pop()
        elif s[i] == ')' and len(stack) == 0:
            tmp = '(' + tmp + ')'
        else:
            stack.append('(')
            out += tmp
            tmp = ''
        # print(tmp)

    if len(tmp) > 0:
        out += tmp

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    print(out)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def main():
    N = I()
    s = S()
    stack = deque()
    out = ''

    for i in range(len(s)):
        if s[i] == ')' and len(stack) > 0 and stack.pop() == '(':
            out += '()'
        elif s[i] == ')' and len(stack) == 0:
            out = '(' + out + ')'
        else:
            stack.append('(')

    tmp = ''
    while len(stack) > 0:
        tmp = '(' + tmp + ')'
        stack.pop()

    out += tmp

    print(out)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    S = input()
    ans = ''
    left, right = 0, 0
    for s in S:
        if s == '(':
            left += 1
            if right:
                m = max(left, right)
                ans += '(' *m + ')'*m 
                left, right = 1, 0
        else:
            right += 1
    if right or left:
        m = max(left, right)
        ans += '(' *m + ')'*m
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
cnt = 0
for i in range(n - 1):
    if s[i] == "(" and s[i + 1] == ")":
        cnt += 1
cntl,cntr=0,0
for i in range(n):
    if s[i] == "(":
        cntl += 1
    else:
        cntr += 1
cntl = cntl - cnt
cntr = cntr - cnt
print("("*cntr+s+")"*cntl)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = input()
L = len([i for i in X if i == ")"])
R = len(X) - L
X = (L - R) * "(" + X + (len(X) - (L - R)) * ")"
print(X)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = input()
mL = 0
for i in X:
  if i == ")":
    mL += 1
  else:
    break
mR = 0
for i in X[::-1]:
  if i == "(":
    mR += 1
  else:
    break
X = mL * "(" + X + mR * ")"
L = len([i for i in X if i == ")"])
R = len(X) - L
if L > R:
  X = (L - R) * "(" + X
else:
  X += (R - L) * ")"
print(X)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = input()
mL = 0
for i in X:
  if i == ")":
    mL += 1
  else:
    break
mR = 0
for i in X[::-1]:
  if i == "(":
    mR += 1
  else:
    break
result = mL * "(" + X + mR * ")"
L = len([i for i in result if i != "("])
R = len(result) - L
print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = input()
mL = 0
for i in X:
  if i == ")":
    mL += 1
  else:
    break
mR = 0
for i in X[::-1]:
  if i == "(":
    mR += 1
  else:
    break
result = mL * "(" + X + mR * ")"
L = len([i for i in result if i != "("])
R = len(result) - L
if L > R:
  result = (L - R) * "(" + result
else:
  result += (R - L) * ")"
print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = input()
L = len([i for i in X if i != "("])
R = len(X) - L
mL = 0
for i in X:
  if i == ")":
    mL += 1
  else:
    break
mR = 0
for i in X[::-1]:
  if i == "(":
    mR += 1
  else:
    break
#print(L, R, mL, mR)
result = ""
if L >= R:
  result += "(" * max([L-R, mL])
result += X
if R >= L:
  result += ")" * max([R-L, mR])
print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
lcnt = 0
rcnt = 0
res = ""
for char in input():
  if char == ")":
    rcnt += 1
  else:
    lcnt+=1
    for i in range(rcnt):
      res += "("
    for i in range(rcnt):
      res += ")"
      rcnt = 0
else:
  for i in range(lcnt - rcnt) :
    res = "(" + res
  for i in range(rcnt) :
    res += "("
  for i in range(max(lcnt,rcnt) ):
    res += ")"
  print(res)

Submission status: Wrong Answer

Solution code:
N = int(input())
lcnt = 0
rcnt = 0
for char in input():
  if char == ")":
    rcnt += 1
  else:
    lcnt+=1
    for i in range(rcnt):
      print("(",end="")
    for i in range(rcnt):
      print(")",end="")
      rcnt = 0
else:
  for i in range(max(lcnt,rcnt) ) :
    print("(",end="")
  for i in range(max(lcnt,rcnt) ):
    print(")",end="")
  cnt = 0

Submission status: Wrong Answer

Solution code:

import math
import itertools
import statistics
#import collections
n = int(input())
s = input()

amari = 0
plus = 0

for i in range(n):
    if s[i]==")":
        plus += 1
    else:
        if plus <= 0:
            amari +=1
        else:
            plus -= 1

for i in range(amari):
    print("(", end="")

print(s, end="")

for i in range(plus):
    print(")", end="")

Submission status: Wrong Answer

Solution code:

import math
import itertools
import statistics
#import collections
n = int(input())
s = input()

amari = 0
plus = 0

for i in range(n):
    if s[i]==")":
        plus += 1
    else:
        if plus <= 0:
            amari +=1
        else:
            plus -= 1

for i in range(plus):
    print("(", end="")

print(s, end="")

for i in range(amari):
    print(")", end="")

Submission status: Wrong Answer

Solution code:

import math
import itertools
import statistics
#import collections
n = int(input())
s = input()

mark = [0]*n
count = 1

left = False
rigth = False
kakko = []

for i in range(len(s)-1):
    if s[0]=="(":
        left=True #左から始まるとき
    else:
        rigth=True #右から始まるとき

    if s[i]!=s[i+1]:
        kakko.append(count)
        count = 1
    else:
        count +=1

kakko.append(count)
l_k=0
r_k = 0

for i in range(len(kakko)):
    if i%2==0:
        if left:
            l_k+=kakko[i]
        else:
            r_k+=kakko[i]
    else:
        if left:
            r_k +=kakko[i]
        else:
            l_k += kakko[i]


if l_k!=r_k:
    for i in range(abs(r_k-l_k)):
        print("(", end="")

    print(s, end="")

    for i in range(abs(l_k-r_k)):
        print(")", end="")
else:
    for i in range(r_k):
        print("(", end="")

    print(s, end="")

    for i in range(l_k):
        print(")", end="")

Submission status: Wrong Answer

Solution code:

import math
import itertools
import statistics
#import collections
n = int(input())
s = input()

mark = [0]*n
count = 1

left = False
rigth = False
kakko = []

for i in range(len(s)-1):
    if s[0]=="(":
        left=True #左から始まるとき
    else:
        rigth=True #右から始まるとき

    if s[i]!=s[i+1]:
        kakko.append(count)
        count = 1
    else:
        count +=1

kakko.append(count)
l_k=0
r_k = 0

for i in range(len(kakko)):
    if i%2==0:
        if left:
            l_k+=kakko[i]
        else:
            r_k+=kakko[i]
    else:
        if left:
            r_k +=kakko[i]
        else:
            l_k += kakko[i]


if l_k!=r_k:
    for i in range(r_k-l_k):
        print("(", end="")

    print(s, end="")

    for i in range(l_k-r_k):
        print(")", end="")
else:
    for i in range(r_k):
        print("(", end="")

    print(s, end="")

    for i in range(l_k):
        print(")", end="")

Submission status: Wrong Answer

Solution code:
import sys

n = int(input())
a = input()
s = list(a)

right = 0
left = 0

for i in s:
    if i == "(":
        right+=1
    else:
        left+=1

for _ in range(max(0,left - right)):
    sys.stdout.write("(")
sys.stdout.write(a)
for _ in range(max(0,right - left)):
    sys.stdout.write(")")

Submission status: Wrong Answer

Solution code:
import sys

n = int(input())
a = input()
s = list(a)

right = 0
left = 0

for i in s:
    if s == "(":
        right+=1
    else:
        left+=1

for _ in range(max(0,left - right)):
    sys.stdout.write("(")
sys.stdout.write(a)
for _ in range(max(0,right - left)):
    sys.stdout.write(")")

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
ans = s
if s.count(")") == 0:
	ans += ")"*(s.count("("))
	print (ans)
	exit()
if s.count("(") == 0:
	ans = "("*(s.count(")")) + ans
	print (ans)
	exit()
lef2 = s.rindex(")")
rit2 = s.index("(")

ans = s
ans += ")"*(n-(lef2+1))
ans = "("*rit2 + ans
lef = ans.count("(")
rit = ans.count(")")
if lef > rit:
	ans += ")"*(lef-rit)
	print (ans)
elif lef == rit:
	print (ans)
else:
	ans = "("*(rit-lef) + ans
	print (ans)

Submission status: Wrong Answer

Solution code:
from collections import deque,defaultdict

n=int(input())
s=list(input())

parts=[]
start=0
for i in range(n-1):
    if s[i]==")" and s[i+1]=="(":
        parts.append(s[start:i+1])
        start=i+1
parts.append(s[start:])

l=0
r=0
for i in range(len(parts)):
    c=defaultdict(int)
    for g in parts[i]:
        if g=='(':
            c['(']+=1
        else:
            c[')']+=1
    if c['(']>c[')']:
        r+=c['(']-c[')']
    else:
        l+=c[')']-c['(']

s=deque(s)
for i in range(l):
    s.appendleft('(')
for g in range(r):
    s.append(')')
print(''.join(s))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

d = deque()
stack = []
for i in range(N):
    if S[i] == '(':
        stack.append(S[i])
    else:
        if len(stack) > 0:
            if stack[-1] == '(':
                stack.pop()
                d.append('(')
                d.append(')')
            else:
                stack.append(')')
        else:
            d.appendleft('(')
            d.append(')')
  
print(''.join(d) + ''.join(stack) + ''.join([')']*len(stack)))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
m = 0
c1, c2 = 0, 0
for i in range(n):
    if s[i] == ")":
        m += 1
        c2 = c1
    else:
        c1 += 1
j = 0
while True:
    if j == n:
        break
    if s[j] == "(":
        break
    j += 1
l = max((m - c2), j)
s1 = ["("] * l
for i in s:
    if i == "(":
        l += 1
    else:
        l -= 1
s2 = [")"] * l
s = s1 + s + s2
print("".join(s))

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
kf=0
kn=kp=0
ans=""
headkcnt=lastkcnt=0
for i in range(n):
  if s[i]=="(":
    if kf==0:
      kn+=1
    else:
      headkcnt+=max(0,kp-kn)
      lastkcnt+=max(0,kn-kp)
      ans=ans+"("*kn+")"*kp
      kn=1
      kp=0
      kf=0
  else:
    if kf==1:
      kp+=1
    else:
      kp=1
      kf=1
headkcnt+=max(0,kp-kn)
lastkcnt+=max(0,kn-kp)
mm=min(headkcnt,lastkcnt)
ans="("*(headkcnt-mm)+ans+"("*kn+")"*(kp+lastkcnt-mm)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
kf=0
kn=kp=0
ans=""
headkcnt=lastkcnt=0
for i in range(n):
  if s[i]=="(":
    if kf==0:
      kn+=1
    else:
      headkcnt+=max(0,kp-kn)
      lastkcnt+=max(0,kn-kp)
      ans=ans+"("*kn+")"*kp
      kn=1
      kp=0
      kf=0
  else:
    if kf==1:
      kp+=1
    else:
      kp=1
      kf=1
headkcnt+=max(0,kp-kn)
lastkcnt+=max(0,kn-kp)
ans="("*headkcnt+ans+"("*kn+")"*(kp+lastkcnt)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
kf=0
kn=kp=0
ans=""
headkcnt=lastkcnt=0
for i in range(n):
  if s[i]=="(":
    if kf==0:
      kn+=1
    else:
      headkcnt+=max(0,kn-kp)
      lastkcnt+=max(0,kp-kn)
      ans=ans+"("*min(kn,kp)+")"*min(kn,kp)
      kn=1
      kp=0
      kf=0
  else:
    if kf==1:
      kp+=1
    else:
      kp=1
      kf=1
headkcnt+=max(0,kn-kp)
lastkcnt+=max(0,kp-kn)
ans="("*headkcnt+ans+"("*min(kn,kp)+")"*min(kn,kp)+")"*+lastkcnt
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
kf=0
kn=kp=0
ans=""
lastkcnt=0
for i in range(n):
  if s[i]=="(":
    if kf==0:
      kn+=1
    else:
      head=max(0,kp-kn)
      lastkcnt+=max(0,(kn-kp))
      ans="("*head+ans+"("*(max(kn,kp)-head)+")"*(max(kn,kp)-max(0,(kn-kp)))
      kn=1
      kp=0
      kf=0
  else:
    if kf==1:
      kp+=1
    else:
      kp=1
      kf=1
head=max(0,kp-kn)
ans="("*head+ans+"("*(max(kn,kp)-head)+")"*(max(kn,kp)+lastkcnt)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
ans = []
#S1 = groupby(S)
a=0
a1=0
b=0
b1=0
S1 = groupby(list(S))
for key,group in S1:
  group = list(group)
  if list(key)==['(']:
    a=len(group)
    a1+=a
  else:
    b=len(group)
    if a1==0:
      b1+=b
    else:
      a1-=b
S = "("*b1+S
S = S+")"*a1
print("".join(S))

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
ans = []
#S1 = groupby(S)
a=0
a1=0
b=0
b1=0
S1 = groupby(list(S))
for key,group in S1:
  group = list(group)
  if list(key)==['(']:
    a=len(group)
    a1+=a
  else:
    b=len(group)
    b1+=b-a
    a1-=b
S = "("*b1+S
S = S+")"*a1
print("".join(S))

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
ans = []
#S1 = groupby(S)
a=0
a1=0
b=0
b1=0
cnt = 0
c=0
S1 = groupby(list(S))
for key,group in S1:
  group = list(group)
  if list(key)==['(']:
    a=len(group)
    a1+=a
  else:
    b=len(group)
    b1+=b
    a1-=b
S = "("*b1+S
S = S+")"*a1
print("".join(S))

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
ans = []
#S1 = groupby(S)
a=0
a1=0
b=0
b1=0
cnt = 0
c=0
if S[0]==")":
  for i in range(N-1):
    if S[i]==")":
      c+=1
    else:
      break
S = "("*c+S
S=list(S)
S1 = groupby(S)
for key,group in S1:
  group = list(group)
  if list(key)==[')']:
    a=len(group)
    a1+=a
    ans.append(a)
  else:
    b=len(group)*-1
    b1+=b
    ans.append(b)
if 0<sum(ans):
  S = ["("]*sum(ans)+S
elif sum(ans)<0:
  S = S+[")"]*(sum(ans)*-1)
print("".join(S))

Submission status: Wrong Answer

Solution code:
from itertools import groupby
N = int(input())
S = input()
ans = []
#S1 = groupby(S)
a=0
a1=0
b=0
b1=0
cnt = 0
c=0
if S[0]==")":
  for i in range(N-1):
    if S[i]==")":
      c+=1
    else:
      break
S = "("*c+S
S=list(S)
S1 = groupby(S)

for key,group in S1:
  group = list(group)
  if list(key)==[')']:
    a=len(group)
    a1+=a
    ans.append(a)
  else:
    b=len(group)*-1
    b1+=b
    ans.append(b)
if 0<sum(ans):
  S = ["("]*sum(ans)+S
elif sum(ans)<0:
  S = S+[")"]*(sum(ans)*-1)
print("".join(S))

Submission status: Wrong Answer

Solution code:
from collections import Counter
N = int(input())
S = input().split(')(')

if len(S) >= 2:
    S[0] += ')'
    S[-1] = '(' + S[-1]
for i in range(1, len(S) - 1):
    S[i] = '(' + S[i] + ')'
# print(S)

cnt = 0
for i in range(len(S)):
    # print('s', S[i])
    c = Counter(S[i])
    l = c['(']
    r = c[')']
    if l > r:
        S[i] = S[i] + (l - r) * ')'
    elif l < r:
        # S[i] = (r - l) * '(' + S[i]
        cnt += r - l
# print(S)
S[0] = cnt * '(' + S[0]
ans = ''.join(S)
print(ans)
#  ())
# (())

#     )))())
# (((()))())
#   ((()))(())
#     ))))((((
# (((())))(((())))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
n = len(s)
l = 0
r = 0
flag = True
for i in range(n):
  if(s[n-1-i] == '(' and flag == True):
    continue
  elif(s[n-1-i] == ')'):
    flag = False
    r += 1
  else:
    l += 1
d1 = max(0,r-l)

l = d1
r = 0

for i in range(n):
  if(s[i] == ')'):
    r += 1
  else:
    l += 1

d2 = max(0,l-r)

for i in range(d1):
  print('(',end = '')
print(s,end='')
for i in range(d2):
  print(')',end = '')
print('')

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
l = 0
r = 0
flag = True
for i in range(n):
  if(s[n-1-i] == '(' and flag == True):
    continue
  elif(s[n-1-i] == ')'):
    flag = False
    r += 1
  else:
    l += 1
d1 = max(0,r-l)

l = d1
r = 0

for i in range(n):
  if(s[i] == ')'):
    r += 1
  else:
    l += 1

d2 = max(0,l-r)

for i in range(d1):
  print('(',end = '')
print(s,end='')
for i in range(d2):
  print(')',end = '')
print('')