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 deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue
#import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): #startline-------------------------------------------
    N = int(input())
    S = input()
    Sr = S.replace("()","p")
    nr = Sr.count(")")
    nl = Sr.count("(")
    print("("*nr+S+")"*nl)

if __name__ == "__main__":
    main() #endline===============================================

Submission status: Wrong Answer

Solution code:
def resolve():
    s = input()
    tmp = s
    while "()" in tmp:
        tmp = tmp.replace("()", "")
    l = tmp.count(")")
    r = tmp.count("(")
    ans = "(" * l + s + ")" * r
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    s = input()
    tmp = s
    while "()" in tmp:
        tmp.replace("()", "")
    l = tmp.count(")")
    r = tmp.count("(")
    ans = "(" * l + s + ")" * r
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    s = input()
    tmp = s
    while "()" in tmp:
        tmp.replace("()", "")
    l = tmp.count("(")
    r = tmp.count(")")
    ans = "(" * r + s + ")" * l
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
stack = []
for i in range(N):
  if S[i] == "(":
    stack.append("(")
  elif S[i] == ")" and len(stack) == 0:
    stack.append("(")
    stack.append(")")
  elif S[i] == ")" and stack[-1] == "(":
    stack.append(")")
  else:
    stack.insert(0,"(")
    stack.append(")")
if stack.count("(") != stack.count(")"):
  X = stack.count("(") - stack.count(")")
  for i in range(X):
    stack.append(")")
print(*stack,sep="")

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    S = str(input())
    l,r = 1,1
    left = []
    right = []
    if S[0] == ")":
        left.append(0)
    for i in range(N-1):
        if S[i] == ")" and S[i+1] == ")":
            r += 1
        elif S[i] == ")" and S[i+1] == "(":
            right.append(r)
            r = 1
        elif S[i] == "(" and S[i+1] == "(":
            l += 1
        else:
            left.append(l)
            l = 1
    if S[-1] == ")":
        right.append(r)
    else:
        left.append(l)
        right.append(0)
    a = len(left)
    lc,rc = 0,0
    for i in range(a):
        if right[i]-left[i] > 0:
            lc += right[i]-left[i]
        else:
            rc += left[i]-right[i]

    print("("*lc+S+")"*rc)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
l = s.count("(")
r = s.count(")")
lcount = 0
rcount = 0
if n == 1:
    print("()")
elif l == 0:
    print("("* r + s)
elif r == 0:
    print(s + ")"*l)
else:
    while s[lcount] == ")":
        lcount += 1

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

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

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

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

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

    print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input().rstrip()
res = ''
remaining_l = 0
remaining_r = 0
left = 0
right = 0
index = 0
while index < n:
    while index < n and s[index] == '(':
        left += 1
        index += 1
    while index < n and s[index] == ')':
        right += 1
        index += 1
    if left > right:
        remaining_r += left - right
    elif left < right:
        k = right - left
        if remaining_r <= k:
            remaining_r = 0
            remaining_l += k - remaining_r
        else:
            remaining_r -= k
    res += '(' * left + ')' * right
    left = right = 0
res = '(' * remaining_l + res + ')' * remaining_r
print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input().rstrip()
res = ''
remaining_l = 0
remaining_r = 0
left = 0
right = 0
index = 0
while index < n:
    while index < n and s[index] == '(':
        left += 1
        index += 1
    while index < n and s[index] == ')':
        right += 1
        index += 1
    if left > right:
        remaining_r += left - right
    elif left < right:
        remaining_l += right - left
    res += '(' * left + ')' * right
    left = right = 0
res = '(' * remaining_l + res + ')' * remaining_r
print(res)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
import collections

def main():
    _ = int(input())
    S = input().strip()
    st = collections.deque()
    ans = ""
    for c in S:
        if c == "(":
            st.append(c)
        elif c == ")":
            if not st:
                ans = "(" + ans + ")"
            else:
                st.pop()
                ans = ans + "()"
    if st:
        ans = ans + "(" * len(st) + ")" * len(st)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

def main():
    _ = int(input())
    S = input().strip()
    n = 0
    for c in S:
        if c == "(":
            S = "("*n + S
            break
        else:
            n += 1
    n = 0
    for c in S[::-1]:
        if c == ")":
            S = S + ")"*n
            break
        else:
            n += 1
    n = 0
    for c in S:
        if c == "(":
            n += 1
        else:
            n -= 1
    if n > 0:
        S = S + ")" * n
    if n < 0:
        S = "(" * -n + S
    print(S)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = str(input())
cnt = 0
lst = []
for i in s:
  if i == "(":
    cnt += 1
  else:
    cnt -= 1
  lst.append(cnt)
#print(lst)
if lst.count(0) >0:
  zidx = -(lst[::-1].index(0))-1
  lst = lst[zidx:]
  #print(lst)

mlst, mmax = 0, 0
if min(lst) < 0:
  mlst = min(lst)*-1
if max(lst) > 0:
  mmax = max(lst)

print(mlst * "(" + s + mmax * ")")

Submission status: Wrong Answer

Solution code:
n = int(input())
s = str(input())
cnt = 0
lst = []
for i in s:
  if i == "(":
    cnt += 1
  else:
    cnt -= 1
  lst.append(cnt)

mlst, mmax = 0, 0
if min(lst) < 0:
  mlst = min(lst)*-1
if max(lst) > 0:
  mmax = max(lst)

print(mlst * "(" + s + mmax * ")")

Submission status: Wrong Answer

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


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
_,s=open(0)
x=y=0
for c in s:
	if c=="(":
		x+=1
	else:
		x-=1
	y=max(y,-x)
print("("*y+s+")"*(x+y))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
T = []
c = 0
m = 0
for s in S:
  if s == ")":
    c += 1
  else:
    if c > 0:
      m += c #先頭につける"("の数
      c = 0
    c -= 1
print("("*m + S + ")"*(-c))

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
T = []
for s in S:
  if s == "(":
    T.append(-1)
  else:
    T.append(1)
c = 0
U = ""
for i in range(N):
  c += T[i]
  if c > 0:
    U += "("
    c -= 1
  if T[i] == -1:
    U += "("
  else:
    U += ")"
print(U + ")"*(-c))

Submission status: Wrong Answer

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

ss=s.split("()")
ss="".join(s)

left=ss.count(")")
right=ss.count("(")
ans="("*left + s + ")"*right
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
r=0;l=0
for i in s:
    if i=="(":
        r+=1
    else:
        l+=1
print("("*l+s+")"*r)

Submission status: Wrong Answer

Solution code:

n = int(input())
s = input()
l = s.count("(")
r = s.count(")")
if l > r:
    print(s + ")" * (l-r))
elif l < r:
    print("(" * (r-l) + s)
else:
    print(s)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
a=b=0
for i in range(n):
	if s[i]=="(":
		a+=1
	else:
		b+=1
if a>=b:
	print(s+")"*(a-b))	
else:
	print("("*(b-a)+s)

Submission status: Wrong Answer

Solution code:
N, S = open(0)

cnt = left = 0
for s in S:
    if s == "(":
        cnt += 1
    elif s == ")":
        cnt -= 1

        if cnt < 0:
            left = max(left, -cnt)

S = "(" * left + S

right = 0
for s in S:
    if s == "(":
        right += 1
    elif s == ")":
        right -= 1

S = S + ")" * right

print(S)

Submission status: Wrong Answer

Solution code:
N, S = open(0)

cnt = left = 0
for s in S:
    if s == "(":
        cnt += 1
    else:
        cnt -= 1

        if cnt < 0:
            left = max(left, -cnt)

S = "(" * left + S

right = 0
for s in S:
    if s == "(":
        right += 1
    else:
        right -= 1

S = S + ")" * right

print(S)

Submission status: Wrong Answer

Solution code:
N, S = open(0)

cnt = left = 0
for s in S:
    if s == "(":
        cnt += 1
    else:
        cnt -= 1

    if cnt < 0:
        left = max(left, -cnt)

S = "(" * left + S

right = 0
for s in S:
    if s == "(":
        right += 1
    else:
        right -= 1

S = S + ")" * right

print(S)

Submission status: Wrong Answer

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

l = [0]
for i in range(N-1):
    if S[i] == ')' and S[i+1] == '(':
        l.append(i+1)
l.append(N)
#print(l)

ans = ''

S = ''.join(S)

for i in range(len(l)-1):
    tmp = S[l[i]:l[i+1]]
    #print(tmp)
    a = list(tmp).count('(')
    b = list(tmp).count(')')
    tmp = max(0, b-a) * '(' + tmp + max(0, a-b) * ')'
    #print(tmp)
    ans += tmp

print(ans)

Submission status: Wrong Answer

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

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

if S.count('(')!= 0 and S.count(')') != 0:
    a = [i for i, x in enumerate(S) if x == '('][0]
    b = [i for i, x in enumerate(S) if x == ')'][-1]

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

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

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

elif S.count('(')!= 0:
    S = ''.join(S) + ')'*N
    print(S)
elif S.count(')')!= 0:
    S =   '('*N +''.join(S)
    print(S)

Submission status: Wrong Answer

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

  x = s.replace("()", "")
  a = x.count(")")
  b = x.count("(")
  if a > b:
    a -= b
    b = 0
  elif a < b:
    b -= a
    a = 0
  print(a * "(" + s + ")" * b)

main()

Submission status: Wrong Answer

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

  x = s.replace("()", "")
  a = x.count(")")
  b = x.count("(")
  print(a * "(" + s + ")" * b)

main()

Submission status: Wrong Answer

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# ABC064D - Insertion
def main():
    # divide into partial strings -> restore shortages
    N = int(input())
    S = input().rstrip().replace(")(", ") (").split()
    ans = ""
    for i in S:
        l, r = i.count("("), i.count(")")
        ans += "(" * max(0, r - l) + i + ")" * max(0, l - r)
    print(ans)
    


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

needleft = 0
needright = 0
ans = ''

for i in range(N):
    if S[i] == ')':
        ans += '(' * needright
        ans += ')' * needright
        needleft += 1
        needright = 0
    elif S[i] == '(':
        ans += '(' * needleft
        ans += ')' * needleft
        needright += 1
        needleft = 0
    if i == N-1:
        if needleft:
            ans += '(' * needleft
            ans += ')' * needleft
        else:
            ans += '(' * needright
            ans += ')' * needright

print(ans)

Submission status: Wrong Answer

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

needleft = 0
needright = 0
ans = ''

for i in range(N):
    if S[i] == ')':
        ans += '(' * needright
        ans += ')' * needright
        if needright == 0:
            needleft += 1
        needright = 0
    elif S[i] == '(':
        ans += '(' * needleft
        ans += ')' * needleft
        if needleft == 0:
            needright += 1
        needleft = 0
    if i == N-1:
        if needleft:
            ans += '(' * needleft
            ans += ')' * needleft
        else:
            ans += '(' * needright
            ans += ')' * needright

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

p = 0
for i in S:
    if i == '(':
        p += 1
    else:
        p -= 1

if p > 0:
    S = S + ')'*abs(p)
else:
    S = '('*abs(p) + S

print(S)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
cntl=0
cntr=0
c0=0
c1=0
a0=0
a1=0
for i in range(n):
    if s[i]=="(":
        c0+=1
    if s[i]==")":
        c1+=1
for i in range(n):
    if s[i]=="(":
        break
    if s[i]==")":
        cntl+=1
for i in range(n-1,0,-1):
    if s[i]==")":
        break
    if s[i]=="(":
        cntr+=1
if c0>c1:
    a1=c0-c1
elif c1>c0:
    a0=c1-c0
appendl=max(cntl,a0)
appendr=max(cntr,a1)
#print(cntl,cntr,a0,a1,c0,c1)
for i in range(appendr):
    s=s+")"
for i in range(appendl):
    s="("+s
print(s)

Submission status: Wrong Answer

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

cnt_l = 0
min_h = 0

for ch in S:
    if ch == '(':
        cnt_l += 1
    else:
        cnt_l -= 1
    min_h = min(min_h, cnt_l)
    
print('('*(-min_h) + S + ')'*(cnt_l+min_h))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=input()
LIST=[]

i=0
while i<N:
    if i<=N-2 and S[i]=="(" and S[i+1]==")":
        i+=2
    else:
        LIST.append(S[i])
        i+=1

print("("*LIST.count(")")+S+")"*LIST.count("("))

Submission status: Wrong Answer

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

cnt = 0
ex = 0
flag = True
for i,s in enumerate(S):
    if flag and s == ')':
        ex += 1
    else:
        flag = False
        if s == '(':
            cnt += 1
        else:
            cnt -= 1
if ex> 0:
    ans = ['('] * ex + ans
if cnt> 0:
    ans = ans + [')'] * cnt
elif cnt < 0:
    ans = ['('] * (-cnt) + ans
print(''.join(ans))

Submission status: Wrong Answer

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

cnt = 0
ex = 0
flag = True
for i,s in enumerate(S):
    if flag and s == ')':
        ex += 1
    else:
        flag = False
        if s == '(':
            cnt += 1
        else:
            cnt -= 1
if ex> 0:
    ans = ['('] * ex + ans
if cnt> 0:
    ans = ans + [')'] * cnt

print(''.join(ans))

Submission status: Wrong Answer

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

cnt = 0
for s in S:
    if s == '(':
        cnt -= 1
    else :
        cnt += 1
if cnt>0:
    ans = ['('] * cnt + ans
               
S = ans
cnt = 0
for s in S:
    if s == ')':
        cnt += 1
    else :
        cnt -= 1
if cnt<0:
    ans =  ans + [')'] * (-cnt) 

print(''.join(ans))

Submission status: Wrong Answer

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

cnt = 0
idx = 0
for s in S:
    if s == ')':
        cnt += 1
        if cnt > 0:
            ans = ans[:idx] + ['('] + ans[idx:]
            idx += 1
            cnt = 0
    else :
        cnt -= 1
    idx += 1
if cnt<0:
    for i in range(-cnt):
        ans = ans[:idx] + [')'] + ans[idx:]
        idx += 1
        
print(''.join(ans))

Submission status: Wrong Answer

Solution code:


def main():
    num = int(input())
    data = list(input())

    left, righ = 0, 0
    for i in range(num)[::-1]:
        ele = data[i]
        if ele == ')':
            righ += 1
        elif ele == '(':
            if righ > 0:
                righ -= 1
            else:
                data[i] = '()'
    add_data = ['(' for i in range(righ)]
    data = add_data + data
    print(''.join(data))




if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

lf, ll, c = True, 0, 0
for s in S:
	if s == "(":
		lf = False
		c += 1
	else:
		if lf:
			ll += 1
		else:
			c -= 1

if c <= 0:
	print("(" * (ll + abs(c)) + S)
else:
	print("(" * ll + S + ")" * c)

Submission status: Wrong Answer

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

lf, ll, c = True, 0, 0
for s in S:
	if s == "(":
		lf = False
		c += 1
	else:
		if lf:
			ll += 1
		else:
			c -= 1

if c <= 0:
	print("(" * (ll + abs(c)) + S)
	exit()

if 0 < c:
	print("(" * ll + S + ")" * c)
	exit()

print(S)

Submission status: Wrong Answer

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

lf, ll, c = True, 0, 0
for s in S:
	if s == "(":
		lf = False
		c += 1
	else:
		if lf:
			ll += 1
		else:
			c -= 1

if c < 0:
	print("(" * (ll + abs(c)) + S)
	exit()

if 0 < c:
	print("(" * ll + S + ")" * c)
	exit()

print(S)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=input()
ans=0
r=0
for i in range(n):
    if s[n-1-i]==")":
        r=n-i
        break
x=s[:r].count(")")-s[:r].count("(")
if x>0:
    s="("*x+s
    p=0
else:
    p=abs(x)
y=s[r:].count("(")+p
s=s+")"*y
print(s)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy

N = int(input())
S = list(input())
newS = deepcopy(S)

i = 0
while 1:
    if i >= len(S):
        break
    if S[i] == "(":
        j = i
        while 1:
            if j >= len(S):
                break
            if S[j] == ")":
                S.pop(j)
                S.pop(i)
                i = -1
            j += 1
    i += 1

y = S.count("(")
x = S.count(")")

print("(" * x + "".join(newS) + ")" * y)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy

N = int(input())
S = list(input())
newS = deepcopy(S)

i = 0
while 1:
    if i >= len(S):
        break
    print(S)
    if S[i] == "(":
        j = i
        while 1:
            if j >= len(S):
                break
            if S[j] == ")":
                S.pop(j)
                S.pop(i)
                i = -1
            j += 1
    i += 1

y = S.count("(")
x = S.count(")")

print("(" * x + "".join(newS) + ")" * y)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy

N = int(input())
S = list(input())
newS = deepcopy(S)

i = 0
while 1:
    if i >= len(S):
        break
    if S[i] == "(":
        j = i
        while 1:
            if j >= len(S):
                break
            if S[j] == ")":
                S.pop(j)
                S.pop(i)
            j += 1
    i += 1

y = S.count("(")
x = S.count(")")

print("(" * x + "".join(newS) + ")" * y)

Submission status: Wrong Answer

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

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

if count > 0:
    S = "(" * count + S

count = 0

for i in range(len(S)):
    if S[i] == "(":
        count += 1
    else:
        count -= 1

if count > 0:
    S += ")" * count

print(S)

Submission status: Wrong Answer

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

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

if maxcount > 0:
    S = "(" * maxcount + S

count = 0
maxcount = 0

for i in range(len(S)):
    if S[i] == "(":
        count += 1
        maxcount = max(count, maxcount)
    else:
        count -= 1

if maxcount > 0:
    S += ")" * maxcount

print(S)

Submission status: Wrong Answer

Solution code:
N = input()

cnt = 0
for x in input():
  if x == "(":
    cnt += 1
  else:
    cnt -= 1
    if cnt < 0:
      cnt += 1
      print("(", end="")
  print(x, end="")
for _ in range(cnt):
  print(")", end="")
print()

Submission status: Wrong Answer

Solution code:
N = input()

cnt = 0
for x in input():
  if x == "(":
    cnt += 1
  else:
    cnt -= 1
    if cnt < 0:
      cnt += 1
      print("(", end="")
  print(x, end="")
print()

Submission status: Wrong Answer

Solution code:
N = input()

cnt = 0
ans = 0
for x in input():
  if x == "(":
    cnt += 1
  else:
    cnt -= 1
    if cnt < 0:
      cnt += 1
      ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
kakko=[0]*(int(input())+1)
S=input()
kakkoSum=0
for n,s in enumerate(S):
    if s=="(":
        kakkoSum +=1
    else:
        kakkoSum -=1
    kakko[n+1] = kakkoSum
print(kakko)
D=min(kakko)
if kakko[-1] ==0:print(S)
elif D<0:
    d=kakko[-1]
    kakkoleft=-D
    kakkoright=-D+d
    print("(" * kakkoleft + S + ")" * kakkoright)
else:
    d=kakko[-1]
    print(S + ")"* d)

Submission status: Wrong Answer

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

left = 0
max_left = 0

for i in S:
    if i == ')':
        left += 1
    else:
        left -= 1
    max_left = max(max_left, left)

right = 0
max_right = 0

for i in S[::-1]:
    if i == '(':
        right += 1
    else:
        right -= 1
    max_right = max(max_right, right)

ans = '(' * left  + S +  ')' * right

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
countleft = 0
countright = 0
for i in range(0, N):
	if S[i] == '(':
		countleft += 1
	if S[i] == ')':
		countright += 1
ans = S
for i in range(0, countleft):
	ans = ans + ')'
for i in range(0, countright):
	ans = '(' + ans
print(ans)

Submission status: Wrong Answer

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

left = 0
right = 0

for i in S:
    if i == ')':
        left += 1
    else:
        break

for i in S[::-1]:
    if i == '(':
        right += 1
    else:
        break

left2 = 0
right2 = 0

for i in S[ left : len(S)-right ]:
    if i == '(':
        left2 += 1
    else:
        right2 += 1

if left2 < right2:
    ans = '(' * left + '(' * (right2 - left2) + S + ')' * right
else:
    ans = '(' * left + S + ')' * (left2 - right2)  + ')' * right

print(ans)

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [input() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N = I()
    S = ST()
    imos = []
    for s in S:
        if s == "(":
            imos.append(1)
        else:
            imos.append(-1)
    status = [imos[0]]
    head = ""
    tail = ""
    for imo in imos[1:]:
        appp = status[-1] + imo
        if appp < 0:
            head += "("*abs(appp)
            appp = 0
        status.append(appp)
    if status[-1] > 0:
        tail = ")" * status[-1]
    print(head+S+tail)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [input() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N = I()
    S = ST()
    imos = []
    for s in S:
        if s == "(":
            imos.append(1)
        else:
            imos.append(-1)
    status = [imos[0]]
    head = ""
    tail = ""
    for imo in imos[1:]:
        appp = status[-1] + imo
        if appp < 0:
            head += "("
            appp = 0
        status.append(appp)
    if status[-1] > 0:
        tail = ")" * status[-1]
    print(head+S+tail)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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

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

Submission status: Wrong Answer

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

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

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

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

Submission status: Wrong Answer

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

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

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

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

Submission status: Wrong Answer

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

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


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

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

Submission status: Wrong Answer

Solution code:
import collections

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

num_open = 0
num_close = 0

q = collections.deque([])

for i in range(N):
  if S[i] == "(":
    q.append("(")
  if S[i] == ")":
    if len(q) == 0:
      num_close += 1
    else:
      q.pop()

str_close = "(" * num_close
str_open =  ")" * num_open


ans = str_close + S + str_open

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
x, y, a = 0, 0, 0

for char in s:
    if char == '(': x += 1
    else: y += 1
    a = min(a, x-y)
    b = x-y
ans = '('*(-b) + s + ')'*(a-b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
x, y = 0, 0

for char in s:
    if char == '(': x += 1
    else: y += 1

if x < y: ans = '('*(y-x)+s
else: ans = s+')'*(x-y)
print(ans)

Submission status: Wrong Answer

Solution code:
def generate(n, m):
    x = max(n, m)
    ret = ('('*x)+(')'*x)
    return ret

n = int(input())
s = list(input().replace(")(", ") (").split())
ans = ""

for i in s:
    x, y = 0, 0
    for char in i:
        if char == '(': x += 1
        else: y += 1
    ans += generate(x, y)

print(ans)