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:
from collections import Counter

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

#N = 6
#S = ")))())"

S_list = list(S)

if "(" in S_list:    
    start_min = S_list.index("(")
else:
    start_min = N
    
if ")" in S_list:
    last_max = S_list[::-1].index(")")
else:
    last_max = N
    
for _ in range(start_min):
    S = "(" + S
for _ in range(last_max):
    S = S + ")"    

ct = Counter(S)
start_num = ct["("]
last_num = ct[")"]
diff = start_num - last_num
if diff>0:
    for i in range(diff):
        S = S + ")"
elif diff<0:
    for i in range(-diff):
        S = "(" + S

print(S)

Submission status: Wrong Answer

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

n1 = s.find("(")
n2 = s.rfind(")")

s1 = s[n1:]
s2 = s[:n2+1]
c1 = 0
c2 = 0
for ss in s1:
 if ss =="(":
  c1 += 1
 elif ss == ")":
  c1 -= 1
for ss in s2:
 if ss =="(":
  c2 -= 1
 elif ss == ")":
  c2 += 1
if c1:
 for i in range(c1):
  s = s + ")"
if c2:
 for i in range(c2):
  s = "(" + s
print(s)

Submission status: Wrong Answer

Solution code:
n = int(input())

s = list(raw_input())

hidari = 0
ans = ''
for k in s:
	if k == ')':
		if hidari == 0:
			ans = '(' + ans + ')'

		else :
			ans += '()'
			hidari -= 1

	else :
		hidari += 1

print ans + "("*hidari + ")" * hidari

Submission status: Wrong Answer

Solution code:
n=int(input())
line=input()
list=[]
list2=[]
for i in range (n):
	if line[i]=="(":
		list.append(1)
	elif line[i]==")":
		list.append(-1)
for j in range (n):
	list2.append(sum(list[:j+1]))
print("("*abs(min(list2))+line+")"*(list2[-1]-min(list2)))

Submission status: Wrong Answer

Solution code:
x=int(input())
y=input()
A=[]
for i in range(0,x):
  if y[i]=='(':
    A.append(1)
  elif y[1]==")":
    A.append(-1)

st=0

s=0
for i in A:

  if s>0:
    s+=i
  elif s<=0 and i==1:
    s=1
  elif s<=0 and i==-1:
    st+=1
    s+=i
out=''
for i in range(0,st):
  out+='('
for j in A:
  if j==1:
    out+='('
  elif j==-1:
    out+=')'
for i in range(0,s):
  out+=')'
print(out)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
ss=s
x=0
while x<len(ss)-1:
    if ss[x]=='(' and ss[x+1]==')':
        ss=ss[:x]+ss[x+2:]
        x=0
    x+=1
left=0
right=0
for i in ss:
    if i=='(':
        right+=1
    elif i==')':
        left+=1
q='('*left
w=')'*right
print(q+s+w)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
ss=s
x=0
while x<len(ss)-1:
    if ss[x]=='(' and ss[x+1]==')':
        ss=ss[:x]+ss[x+2:]
        x=0
    x+=1
left=0
right=0
for i in ss:
    if i=='(':
        right+=1
    elif i==')':
        left+=1
if left>0 and right>0:
    print('('*left+s+')'*right)
elif left==0 and right>0:
    print(s+')'*right)
elif right==0 and left>0:
    print('('*left+s)
else:
    print(s)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = input()
hist = [(0, 0)]
max_dist = 0
for v in s:
    x, y = hist[-1]
    if v == "(": x += 1
    elif v == ")": y += 1
    hist.append((x,y))
    print((x,y), max_dist)
    max_dist = max(y - x, max_dist)
lastx , lasty = hist[-1]
print ("(" * max_dist + s + ")" *(lastx - lasty + max_dist))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
ans = ""
cur = 0
for i in s:
  if i == "(":
    ans += "("
    cur += 1
    ans += i
  else:
    if cur:
      ans += i
      cur -= 1
    else:
      ans = "(" + ans
ans += ")" * cur
print(ans)

Submission status: Wrong Answer

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

mae = S.count("(")
ushiro = N - mae

p_sum = [0] * N

if S[0] == "(":
	p_sum[0] = 1
else:
	p_sum[0] = -1

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

def Good(x):
	if min(x) >= 0:
		return True
	else:
		return False

if not Good(p_sum):
	S = ["("] * (- min(p_sum)) + S + [")"] * (mae - ushiro - min(p_sum))

print("".join(S))

Submission status: Wrong Answer

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

mae = S.count("(")
ushiro = N - mae

if mae >= ushiro:
	i = 0
	while True:
		if S[i] == "(":
		 break
		i += 1

	S = ["("] * i + S + [")"] * ((mae - ushiro) + i)

elif mae < ushiro:
	i = 0
	while True:
		if S[-(i + 1)] == ")":
		 break
		i += 1

	S = ["("] * ((ushiro - mae) + i) + S + [")"] * i

p_sum = [0] * N

if S[0] == "(":
	p_sum[0] = 1
else:
	p_sum[0] = -1

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

def Good(x):
	if min(x) >= 0:
		return True
	else:
		return False

if mae == ushiro and not Good(p_sum):
	S = ["("] * (- min(p_sum)) + S + [")"] * (- min(p_sum))

print("".join(S))

Submission status: Wrong Answer

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

mae = S.count("(")
ushiro = N - mae

if mae >= ushiro:
	i = 0
	while True:
		if S[i] == "(":
		 break
		i += 1

	S = ["("] * i + S + [")"] * ((mae - ushiro) + i)

else:
	i = 0
	while True:
		if S[-(i + 1)] == ")":
		 break
		i += 1

	S = ["("] * ((ushiro - mae) + i) + S + [")"] * i

print("".join(S))

Submission status: Wrong Answer

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

left = 0
right = 0
ans = []
for s in S:
    if s == "(":
        left += 1
        ans.append("(")
    else:
        right += 1
        ans.append(")")
        if right > left:
            ans.insert(0, "(")
            left = 0
            right = 0

for i in range(left):
    ans.append(")")
print("".join(ans))

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
L,R,x = 0,0,0
for i in range(N):
    if x == 0:
        if S[i]==")":
            L += 1
        else:
            R += 1
            x += 1
    else:
        if S[i]==")":
            R -= 1
            x -= 1
        else:
            R += 1
print("("*L + S + ")"*R)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
A = deque()
B = []

left_cnt = 0
right_cnt = 0
for s in S:
    if s == "(":
        left_cnt += 1
        A.append("(")
    else:
        A.append(")")
        if right_cnt + 1 <= left_cnt:
            B.append("(")
        else:
            right_cnt += 1

C = [")"] * (left_cnt - right_cnt)
B.extend(A)
B.extend(C)
print("".join(B))

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
A = deque()
B = []
flg = False

if N == 1:
    print("()")
    exit()

left_cnt = 0
right_cnt = 0
for s in S:
    if s == "(":
        left_cnt += 1
    else:
        right_cnt += 1
        if right_cnt > left_cnt:
            break
else:
    if left_cnt == right_cnt:
        print("".join(S))
        exit()

for i in range(N-1):
    if flg:
        A.append(S[i])
        flg = False
        continue

    if S[i] == ")":
        A.appendleft("(")
        A.append(S[i])

    if (S[i] == "(") & (S[i+1] != ")"):
        A.append("(")
        B.append(")")

    if (S[i] == "(") & (S[i+1] == ")"):
        A.append(S[i])
        flg = True

if (S[N-1] == ")") & (S[N-2] != "("):
    A.append(S[N-1])
    A.appendleft("(")
elif (S[N-1] == ")") & (S[N-2] == "("):
    A.append(S[N-1])
elif S[N-1] == "(":
    A.append("(")
    B.append(")")

A.extend(B)
print("".join(A))

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
A = deque()
B = []
flg = False

if N == 1:
    print("()")
    exit()

left_cnt = 0
right_cnt = 0
for s in S:
    if s == "(":
        left_cnt += 1
    else:
        right_cnt += 1
        if right_cnt > left_cnt:
            break
else:
    if left_cnt == right_cnt:
        print("".join(S))
        exit()

for i in range(N-1):
    if flg:
        A.append(S[i])
        flg = False
        continue

    if S[i] == ")":
        A.appendleft("(")
        A.append(S[i])

    if (S[i] == "(") & (S[i+1] != ")"):
        A.append("(")
        B.append(")")

    if (S[i] == "(") & (S[i+1] == ")"):
        A.append(S[i])
        flg = True

if (S[N-1] == ")") & (S[N-2] != "("):
    A.append(S[i])
    A.appendleft("(")
elif S[N-1] == "(":
    A.append("(")
    B.append(")")

A.extend(B)
print("".join(A))

Submission status: Wrong Answer

Solution code:
n = int(input())
lis = []
cou = 0
uncou = 0
s = str(input())

for i in range(n):
    if s[i] == ")":
        cou += 1
        uncou = 0
    else:
        for i in range(cou):
            lis.append("(")
        cou = -1
        uncou -= 1
    if i == n-1:
        for i in range(cou):
            lis.append("(")
        cou = 0
for m in range(n):
    lis.append(s[m])
while uncou < 0:
    lis.append(")")
    uncou += 1
print("".join(lis))

Submission status: Wrong Answer

Solution code:
n = int(input())
lis = []
li = []
cou = 0
s = str(input())

for i in range(n):
    if s[i] == ")":
        cou += 1
    else:
        cou -= 1
    while cou > 0:
        lis.append("(")
        cou -= 1
    lis.append(s[i])
while cou < 0:
    lis.append(")")
    cou += 1
print("".join(lis))

Submission status: Wrong Answer

Solution code:
n = int(input())
lis = []
li = []
cou = 0
s = str(input())
for i in range(n):
    if s[i] == "(":
        cou += 1
        lis.append(s[i])
    else:
        cou -= 1
        while cou < 0:
            lis.append("(")
            cou += 1
        lis.append(s[i])
while cou > 0:
    lis.append(")")
    cou -= 1
print("".join(lis))

Submission status: Wrong Answer

Solution code:
def d_Insertion(N, S):
    # 解説通り
    d = 0
    x = float('inf')
    for c in S:
        if c == '(':
            d += 1
        else:
            d -= 1
        x = min(x, d)
    ans = '(' * (-x) + S + ')' * (d - x)
    return ans

N = int(input())
S = input().strip()
print(d_Insertion(N, S))

Submission status: Wrong Answer

Solution code:
N = int(input())
s=list(input())
n=0
l=0
r=0
L=[]
while n < N:
    if s[n] == '(':
        l+=1
        if r != 0:
            L.append(-1*r)
        r=0
        n +=1
    else:
        r += 1
        if l != 0:
            L.append(l)
        l=0
        n += 1
if r!=0:
    L.append(-1*r)
elif l != 0:
    L.append(l)
i=0
p=0
while i<len(L):
    if L[i] < 0:
        ins=0
        while ins < abs(L[i]):
            s.insert(p,'(')
            ins+=1
        p += 2*abs(L[i])
        i += 1
    elif (i+1)<len(L):
        if abs(L[i+1])>abs(L[i]):
            ins=0
            while ins < (abs(L[i+1])-abs(L[i])):
                s.insert(p,'(')
                ins += 1
            p += 2*abs(L[i+1])
            i += 2
        elif abs(L[i])>abs(L[i+1]):
            p += abs(L[i])
            ins=0
            while ins < (abs(L[i])-abs(L[i+1])):
                s.insert(p,')')
                ins+=1
            p += abs(L[i])
            i += 2
        else:
            p += abs(L[i])
            i += 2
    else:
        ins=0
        while ins < L[i]:
            s.insert(-1,')')
            ins+=1
        i+=1
print(''.join(s))

Submission status: Wrong Answer

Solution code:
N = int(input())
s=list(input())
n=0
l=0
r=0
L=[]
while n < N:
    if s[n] == '(':
        l+=1
        if r != 0:
            L.append(-1*r)
        r=0
        n +=1
    else:
        r += 1
        if l != 0:
            L.append(l)
        l=0
        n += 1
if r!=0:
    L.append(-1*r)
elif l != 0:
    L.append(l)
print(L)
i=0
p=0
while i<len(L):
    if L[i] < 0:
        ins=0
        while ins < abs(L[i]):
            s.insert(p,'(')
            ins+=1
        p += 2*abs(L[i])
        i += 1
    elif (i+1)<len(L):
        if abs(L[i+1])>abs(L[i]):
            ins=0
            while ins < (abs(L[i+1])-abs(L[i])):
                s.insert(p,'(')
                ins += 1
            p += 2*abs(L[i+1])
            i += 2
        elif abs(L[i])>abs(L[i+1]):
            p += abs(L[i])
            ins=0
            while ins < (abs(L[i])-abs(L[i+1])):
                s.insert(p,')')
                ins+=1
            p += abs(L[i])
            i += 2
        else:
            p += abs(L[i])
            i += 2
    else:
        ins=0
        while ins < L[i]:
            s.insert(-1,')')
            ins+=1
        i+=1
print(''.join(s))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
#-*- coding: utf-8 -*-

from collections import defaultdict
from math import factorial as f
from fractions import gcd as g

N = int (raw_input ())
s = raw_input ()
ret = ""
c = 0
st = []
cnt = 0
for i in range (N):
    if s [i] == "(":
        st.append (s [i])
    elif s [i] == ")":
        if len (st) == 0:
            if cnt:
                ret += "(" * cnt + ")" * cnt
                cnt = 0
            ret = "(" + ret + ")"
        elif st [-1] == "(":
            st.pop ()
            cnt += 1

cnt += len (st)
if cnt:
    ret += "(" * cnt + ")" * cnt

# if len (st):
#     ret += "(" * len (st) + ")" * len (st)

print ret

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout

def main():
    n = stdin.readline()
    S = stdin.readline()
    cnt = 0
    m = 0
    for s in S:
        if s == "(":
            cnt += 1
        else:
            cnt -= 1
        
        if cnt < 0:
            m += 1
            cnt += 1
    
    print("("*m+S+")"*cnt)
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout

def main():
    n = stdin.readline()
    S = stdin.readline()
    cnt = 0
    m = 0
    for s in S:
        if s == "(":
            cnt += 1
        else:
            cnt -= 1
            
        if cnt < 0:
            m += 1
            cnt += 1
        
    print("("*m+S+")"*cnt)
    
    
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout

def main():
    n = stdin.readline()
    S = stdin.readline()
    cnt = 0
    m = 0
    for s in S:
        if s == "(":
            cnt += 1
        else:
            cnt -= 1
            
        if cnt < 0:
            m += 1
            cnt += 1
        
    print("("*m+s+")"*cnt)
    
    
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
N = input()
L = 0
R = 0
num = 0
for c in N:
    if c == '(':
        num += 1
    else:
        if num:
            num -= 1
            print(num)
        else:
            L += 1
R = num

print('('*L+N+')'*R)

Submission status: Wrong Answer

Solution code:
n = int(input())
N = input()
num = 0
while N[num] == ')':
    N = '(' + N
    num += 2
    if num >= n*2:
        break
a = N.count('(')
b = len(N) - a
if (a - b) < 0:
    for i in range(b-a):
        N = '(' + N
elif (a -b) > 0:
    for i in range(a-b):
        N = N + ')'

print(N)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=input()
u=0
l=0
r=0
for c in S:
 if(c=="("):
  u+=1
 else:
   if(u):
    u-=1
   else:
    l-=1
r=u
print("("*l+S+")"*r)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

def removeKakkoRetsu(s):
	if s == '()':
		return ''

	if len(s) < 2:
		return s

	i = 0
	while(i < len(s) - 1):
		if s[i] == '(' and s[i + 1] == ')':
			s = s[:i] + s[i + 2:]
			#print("s:"+s)
		i += 1

	return s

n = int(sys.stdin.readline())
s = sys.stdin.readline()

s2 = str(s)
blen = len(s2)
s2 = removeKakkoRetsu(s)
while(len(s2) < blen):
	blen = len(s2)
	s2 = removeKakkoRetsu(s2)
	#print("s2:"+s2)

counter = Counter(s2)
start = counter['(']
end = counter[')']

s = s + ')' * start
s = '(' * end + s

print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

def removeKakkoRetsu(s):
	if s == '()':
		return ''

	if len(s) < 2:
		return s

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

	return s

n = int(sys.stdin.readline())
s = sys.stdin.readline()

s2 = str(s)
blen = len(s2)
s2 = removeKakkoRetsu(s)
while(len(s2) < blen):
	blen = len(s2)
	s2 = removeKakkoRetsu(s2)

counter = Counter(s2)
start = counter['(']
end = counter[')']

s = s + ')' * start
s = '(' * end + s

print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

def removeKakkoRetsu(s):
	if s == '()':
		return ''

	if len(s) < 2:
		return s

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

	return s

n = int(sys.stdin.readline())
s = sys.stdin.readline()

s2 = str(s)
blen = len(s2)
s2 = removeKakkoRetsu(s)
while(len(s2) < blen):
	blen = len(s2)
	s2 = removeKakkoRetsu(s)

counter = Counter(s2)
start = counter['(']
end = counter[')']

s = s + ')' * start
s = '(' * end + s

print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

n = int(sys.stdin.readline())
s = sys.stdin.readline()

sl = ""
while(s[0] == ')'):
	sl += s[0]
	s = s[1:]

sl = '(' * len(sl) + sl
s = sl + s

sr = ""
while(s[-1] == '('):
	sr += s[-1]
	s = s[:-1]

sr = sr + ')' * len(sr)
s = s + sr

counter = Counter(s)

start = counter['(']
end = counter[')']

diff = abs(start - end)

if start < end:
	s = '(' * diff + s
elif start > end:
	s = s + ')' * diff

if int(len(s)/2)%2 != 0:
	s = '(' + s + ')'

print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

n = int(sys.stdin.readline())
s = sys.stdin.readline()

sl = ""
while(s[0] == ')'):
	sl += s[0]
	s = s[1:]

sl = '(' * len(sl) + sl
s = sl + s

sr = ""
while(s[-1] == '('):
	sr += s[-1]
	s = s[:-1]

sr = sr + ')' * len(sr)
s = s + sr

counter = Counter(s)

start = counter['(']
end = counter[')']

diff = abs(start - end)

if start < end:
	s = '(' * diff + s
elif start > end:
	s = s + ')' * diff

print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import Counter

n = int(sys.stdin.readline())
s = sys.stdin.readline()
counter = Counter(s)

start = counter['(']
end = counter[')']

diff = abs(start - end)

if start < end:
	s = '(' * diff + s
elif start > end:
	s = s + ')' * diff

sl = ""
while(s[0] == ')'):
	sl += s[0]
	s = s[1:]

sl = '(' * len(sl) + sl
s = sl + s

sr = ""
while(s[-1] == '('):
	sr += s[-1]
	s = s[:-1]

sr = sr + ')' * len(sr)
s = s + sr

print(s)

Submission status: Wrong Answer

Solution code:
#Insertion
import numpy as np
n = int(input())
s = input()
ans = ""
while ( s != "" ):
    if ( s[0]==")" ):
        ans = "(" + ans + ")"
        s = s[1:]
    else:
        num = s.find(")")
        if ( num !=-1 ):
            ans = ans + s[:num+1] + ")" * (num-1)
            s = s[num+1:]
        else:
            ans = ans + s + ")"*len(s)
            s = ""

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ns = lambda: stdin.readline()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))

N = ni()
S = ns()

X = [0]*(len(S)-1)
for i in range(len(S)-1):
    if(S[i] == '('):
        X[i] = 1
    else:
        X[i] = -1

x = 0
d = [0]*(len(S))

for i in range(1, len(S)):
    d[i] = sum(X[0:i])

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

Submission status: Wrong Answer

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

pair_cnt = S.count("()")
head_cnt = S.count("(") - pair_cnt
tail_cnt = S.count(")") - pair_cnt

res = S
res = tail_cnt * "(" + res
res = res + head_cnt * ")"

print(res)

Submission status: Wrong Answer

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

pair_cnt = S.count("()")
head_cnt = S.count("(") - pair_cnt
tail_cnt = S.count(")") - pair_cnt

res = S
for i in range(tail_cnt):
    res = "(" + res
for i in range(head_cnt):
    res = res + ")"

print(res)

Submission status: Wrong Answer

Solution code:
import copy


def get_completed(s):
    ans = copy.deepcopy(s)
    for i, c in enumerate(s):
        if c == '(':
            if i+1 < len(s):
                if s[i+1] == ')':
                    continue
            ans = ans + ')'

        if c == ')':
            if i-1 >= 0:
                if s[i-1] == '(':
                    continue
            ans = '(' + ans

    return ans


if __name__ == '__main__':
    N = input()
    S = input()

    print(get_completed(S))

Submission status: Wrong Answer

Solution code:
n = input()
s = input()
count = 0
countl = 0
for c in s:
    if c=='(':
        count += 1
    else:
        count -= 1
    if count < 0:
        countl += 1
        count = 0
count = 0
countr = 0
for c in s[::-1]:
    if c=='(':
        count -= 1
    else:
        count += 1
    if count < 0:
        countr += 1  
        count = 0
print(countl)
print(countr)
print("("*countl + s + ")"*countr)

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[36]:

number = int(input())
strings = input()


# In[37]:

while True:
    counter = 0

    for s in strings:
        if s == "(":
            counter += 1
        else:
            if counter > 0:
                counter -= 1
            else:
                strings = "(" + strings
                counter = -1
                break
        
    if counter > 0:
        strings = strings + ")" * counter
        
    if counter == 0:
        break
            
    print(strings)


# In[ ]:

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[31]:

number = int(input())
strings = input()


# In[32]:

while True:
    counter = 0

    for s in strings:
        if s == "(":
            counter += 1
        else:
            if counter > 0:
                counter -= 1
            else:
                strings = "(" + strings
        
    if counter > 0:
        strings = strings + ")" * counter
        
    if counter == 0:
        break
            
    print(strings)


# In[ ]:

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[17]:

number = int(input())
strings = input()


# In[18]:

while True:
    counter = 0

    for s in strings:
        if s == "(":
            counter -= 1
        else:
            counter += 1
        
    if counter > 0:
        strings = "(" * counter + strings
        
    if counter < 0:
        strings = strings + ")" * (-counter)
        
    if counter == 0:
        break
            
    print(strings)

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[7]:

number = int(input())
strings = input()


# In[8]:

while True:
    counter = 0

    for s in strings:
        if s == "(":
            if counter > 0:
                strings = "(" * counter + strings
                break
            else:
                counter -= 1
        else:
            counter += 1
        
    if counter < 0:
        strings = strings + ")" * (-counter)
        
    if counter == 0:
        break
            
    print(strings)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
x = int(input())
y = input()

z = y

while z.find("()") != -1:
    z = z.replace("()","")

a = z.count("(")
b = z.count(")")

ans = z

for i in range(a):
    ans = ans + ")"

for i in range(b):
    ans = "(" + ans

print(ans)

Submission status: Wrong Answer

Solution code:
#Python

N = input()
S = raw_input()

#print N
#print S

sub_str1=S[0:S.find('(')]
sub_str2=S[S.find('('):]
#print sub_str1
#print sub_str2



#sub_str1='('*len(sub_str1)+ sub_str1
#print sub_str1

if sub_str2.count('(') > sub_str2.count(')'):
	sub_str2 =sub_str2+')'* ( sub_str2.count('(') - sub_str2.count(')') )
#print sub_str2


S=sub_str1+sub_str2
S='('*(S.count(')')-S.count('('))+S

print S

Submission status: Wrong Answer

Solution code:
#Python

N = input()
S = raw_input()

#print N
print S

sub_str1=S[0:S.find('(')]
sub_str2=S[S.find('('):]
#print sub_str1
#print sub_str2



#sub_str1='('*len(sub_str1)+ sub_str1
#print sub_str1

if sub_str2.count('(') > sub_str2.count(')'):
	sub_str2 =sub_str2+')'* ( sub_str2.count('(') - sub_str2.count(')') )
#print sub_str2


S=sub_str1+sub_str2
S='('*(S.count(')')-S.count('('))+S

print S

Submission status: Wrong Answer

Solution code:
import re
def kezuru(str):
    if str.find('()') == -1:
        return str
    else:
        return kezuru(str.replace('()',''))

str = input()
kezutta = kezuru(str)
#print('(' * len(re.search('\)+',kezutta).group(0)) + str + ')' * len(re.search('\(+',kezutta).group(0)))
n1 = 0
m1 = re.search('\)+',kezutta)
if m1:
    n1 = len(m1.group(0))
n2 = 0
m2 = re.search('\(+',kezutta)
if m2:
    n2 = len(m2.group(0))
print(n1 * '(' + str + n2 * ')')

Submission status: Wrong Answer

Solution code:
import re
input()
strorig = input()
closeFirst = re.search('^\)*',strorig).group(0)
openLast = re.search('\(*$',strorig).group(0)
strModified = '(' * len(list(closeFirst)) + strorig + ')' * len(list(openLast))
nums = [-1 if i == '(' else 1 for i in list(strModified)]
sumnums = sum(nums)
if sumnums < 0:
    result = strModified + ')' * (-1 * sumnums)
else:
    result = '(' * sumnums + strModified
print(result)

Submission status: Wrong Answer

Solution code:
import re
strorig = input()
closeFirst = re.search('^\)*',strorig).group(0)
openLast = re.search('\(*$',strorig).group(0)
strModified = '(' * len(list(closeFirst)) + strorig + ')' * len(list(openLast))
nums = [-1 if i == '(' else 1 for i in list(strModified)]
sumnums = sum(nums)
if sumnums < 0:
    result = strModified + ')' * (-1 * sumnums)
else:
    result = '(' * sumnums + strModified
print(result)

Submission status: Wrong Answer

Solution code:
#Python

N = input()
S = raw_input()

#print N
#print S

sub_str1=S[0:S.find('(')]
sub_str2=S[S.find('('):]
#print sub_str1
#print sub_str2


#print sub_str2.find(')')
if sub_str2.find(')') == -1:
	S=S+')'*S.count('(')
	#print S

S='('*(S.count(')')-S.count('('))+S

print S

Submission status: Wrong Answer

Solution code:
N = input()
ss = raw_input()
s=ss.split("()")

while len(s)>1:
    s="".join(s)
    print(s)
    s=s.split("()")

a=""
b=""

s=s[0]
N=len(s)



for i in range(N):
    if s[i]=="(":
        a+=")"
    if s[i]==")":
        b+="("

print(b+ss+a)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=input()
open=0
output=S
for c in S:
    if c=="(":
        open=open+1

    else:
        if open>0:
            open=open-1
        else:
            output="("+output

if open>0:
    output=output+")"

print(output)

Submission status: Wrong Answer

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

left = 0
right = 0
for i in range(N):
    if(S[i] is ")"):
        left += 1
    else:
        score = 0
        for j in range(i, N):
            score += 1 if S[j] is ")" else -1
        if score > 0:
            left += score
        else:
            right -= score
        break

for i in range(left):
    S = "(" + S
for i in range(right):
    S = S + ")"
print(S)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
left = 0
right = 0
count = 0
for i in range(len(S)):
    count += 1 if S[i] is ")" else -1
    if(i == N-1 or (S[i] is ")" and S[i+1] is "(")):
        if(count > 0):
            left += count
        else:
            right -= count
        count = 0
while(left > 0 and right > 0):
    left -= 1
    right -= 1
for i in range(left):
    S = "(" + S
for i in range(right):
    S = S + ")"
print(S)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
left = 0
right = 0
count = 0
for i in range(len(S)):
    count += 1 if S[i] is ")" else -1
    if(i == N-1 or (S[i] is ")" and S[i+1] is "(")):
        if(count > 0):
            left += count
        else:
            right += abs(count)
        count = 0

for i in range(left):
    S = "(" + S
for i in range(right):
    S = S + ")"
print(S)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
left = 0
right = 0
count = 0
for i in range(len(S)):
    if(S[i] == ")"):
        count += 1
        if(i != N-1 and S[i+1] == "("):
            if(count > 0):
                left += count
            else:
                right += abs(count-1)
            count = 0
    else:
        count -= 1

if(count > 0):
    left += count
else:
    right += abs(count-1)

for i in range(left):
    S = "(" + S
for i in range(right):
    S = S + ")"
print(S)

Submission status: Wrong Answer

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

output = ''

start = 0
end = 0
for i in S:
    if i == '(':
        if end > 0:
            output += '(' * end
            output += ')' * end
            end = 0
        start += 1
        output += i
    else:
        if start > 0:
            start -= 1
            output += i
        else:
            end += 1

for i in range(start):
    output += ')'

for i in range(end):
    output += ')'

output = '(' * end + output

print(output)

Submission status: Wrong Answer

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

N = input()
S = input()
pattern = re.compile(r'\)\(')
sentence = S
lit = []
while True:
    m = re.search(pattern, sentence)
    if m:
        lit.append(sentence[:m.start()+1])
        sentence = sentence[m.end()-1:]
    else:
        lit.append(sentence)
        break
left, right = 0, 0
for li in lit:
    l, r = 0, 0
    for char in li:
        if char == '(':
            l += 1
        else:
            r += 1
    if l > r:
        right += l - r
    else:
        left += r - l
s = '(' * left + S + ')' * right
print(s)

Submission status: Wrong Answer

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

N = input()
S = input()
pattern = re.compile(r'\)\(')
sentence = S
lit = []
while True:
    m = re.search(pattern, sentence)
    if m:
        lit.append(sentence[:m.start()+1])
        sentence = sentence[m.end()-1:]
    else:
        lit.append(sentence)
        break
l, r = 0, 0
for li in lit:
    left, right = 0, 0
    for char in li:
        if char == '(':
            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, re

N = input()
S = input()
pattern = re.compile(r'\)\(')
sentence = S
lit = []
while True:
    m = re.search(pattern, sentence)
    if m:
        lit.append(sentence[:m.start()+1])
        sentence = sentence[m.end()-1:]
    else:
        lit.append(sentence)
        break
print(lit)
l, r = 0, 0
for li in lit:
    left, right = 0, 0
    for char in li:
        if char == '(':
            left += 1
        else:
            right += 1
    if left > right:
        r += left - right
    else:
        l += right - left
s = '(' * l + S + ')' * r
print(s)