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 (((())))(((())))

Solution (Python):
N, S = int(input()), input()
stk = []
for s in S:
    if len(stk) == 0 or stk[-1] == ')' or s == '(':
        stk.append(s)
    else:
        stk.pop()

print('(' * stk.count(')') + S + ')' * stk.count('('))

Solution (Python):
def main():
    N = int(input())
    S = input()
    cnt = 0
    pre = 0
    for i in range(len(S)):
        if S[i] == '(':
            cnt += 1
        else:
            cnt -= 1
            if cnt < 0:
                pre = max(pre, -cnt)
    
    ans = "(" * pre + S
    cnt = 0
    for j in range(len(ans)):
        if ans[j] == '(':
            cnt += 1
        else:
            cnt -= 1

    print(ans + ')' * cnt)

main()

Solution (Python):
N = int(input())
S = input()
stack = []
for s in S:
    if s == '(':
        stack.append('(')
    elif s == ')':
        if len(stack) == 0 or stack[-1] == ')':
            stack.append(')')
        elif stack[-1] == '(':
            stack.pop()

l, r = sum([1 for s in stack if s == '(']), sum([1 for s in stack if s == ')'])
print('(' * r + S + ')' * l)

Solution (Python):
N, S = open(0)
S = S.strip()

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)

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

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)

Solution (Python):


import sys


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



rcount=0
rcountmax=0
for i in range(0,n):
	if(s[i]==")"):
		rcount+=1
		rcountmax=max(rcountmax,rcount)
	else:
		rcount-=1
lcount=0
lcountmax=0
for i in range(0,n):
	if(s[n-1-i]=="("):
		lcount+=1
		lcountmax=max(lcountmax,lcount)
	else:
		lcount-=1
ans=""
for i in range(0,rcountmax):
	ans+="("
ans+=s
for i in range(0,lcountmax):
	ans+=")"




print(ans)

Solution (Python):
N=int(input())
s=(input())
org=s

while "()" in s:
    s=s.replace("()","")


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

Solution (Python):
N = int(input())
S = input()
state = [0]
for s in S:
    state.append(state[-1] + (1 if s == '(' else -1))
ans = - min(state)*'(' + S + (state[-1] - min(state)) * ')'
print(ans)

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

T = S
while "()" in S:
    S = S.replace("()", "")

left = S.count(")")
right = S.count("(")

ans = "(" * left + T + ")" * right

print(ans)

Solution (Python):
N, S = open(0).read().split()

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)

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

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)

Solution (Python):

import sys, itertools


def solve(N: int, S: str):
    c = [0] * N
    counter = 0
    for i in range(N):
        if S[i] == '(':
            counter += 1
        else:
            counter -= 1
        c[i] = counter

    m = min(c)
    if m < 0:
        S = "("*abs(m) + S
        c = list(range(1, abs(m)+1)) + [cc+abs(m) for cc in c]
    
    S = "("*(c[0]-1) + S + ")"*c[-1]
    print(S)
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    S = next(tokens)  
    solve(N, S)

if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
s = input()
left = 0
right = 0
left_t = 0
right_t = 0
t = "".join(list(reversed(s)))
for i in range(n):
    if s[i] == ")":
        if left == 0:
            right += 1
        else:
            left -= 1
    if s[i] == "(":
        left += 1
    if t[i] == "(":
        if right_t == 0:
            left_t += 1
        else:
            right_t -= 1
    if t[i] == ")":
        right_t += 1
ans = ("(" * right) + s + ")" * left_t
print(ans)

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

Solution (Python):
from collections import deque

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


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

for i in range(len(S)):
    if S[i] == ")":
        ans.appendleft("(")
    elif S[i] == "(":
        ans.append(")")
print("".join(ans))

Solution (Python):
n=int(input())
s=input()
x=s
while(1):
  a=s.find('()')
  if a==-1:
    break
  s=s[:a]+s[a+2:]
for i in range(len(s)):
  if s[i]==')':
    x='('+x
  else:
    x=x+')'
print(x)

Solution (Python):

from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')


def A():
    _, b, c = LS()
    x = int(b[0] + c[0]) % 4
    if not x:
        print("YES")
    else:
        print("NO")
    return


def B():
    II()
    a = LI()
    a.sort()
    print(a[-1]-a[0])
    return


def C():
    II()
    a = LI()
    a = list(map(lambda x: x // 400, a))
    d = defaultdict(int)
    for ai in a:
        d[ai] += 1
    ans1 = 0
    ans2 = 0
    for key, value in d.items():
        if key <= 7:
            ans1 += 1
            ans2 += 1
        else:
            ans2 += value
    if ans1 == 0:
        ans1 = 1
    print(ans1, ans2)
    return


def D():
    n = II()
    s = S()
    ans = deque(s[::1])
    f = 0
    for i in s:
        if i == "(":
            f += 1
        else:
            f -= 1
        if f < 0:
            ans.appendleft("(")
            f += 1
    ans.append(")" * f)
    print("".join(ans))

    return


if __name__ == '__main__':
    D()

Solution (Python):
N = int(input())
S = input()
nl = 0
for c in reversed(S):
  if c == "(":
    nl = max(0, nl-1)
  if c == ")":
    nl += 1
nr = 0
for c in S:
  if c == ")":
    nr = max(0, nr-1)
  if c == "(":
    nr += 1
r = "("*nl + S + ")"*nr
print(r)

Solution (Python):
from collections import deque
n = int(input())
s = input()

stack = deque()
for i in range(n):
    if len(stack) > 0:
        stack_last = stack.pop()
        if stack_last == "(" and s[i] == ")":
            continue
        else:
            stack.append(stack_last)
            stack.append(s[i])
    else:
        stack.append(s[i])


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

print(s)

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

l = 0
r = 0
for i in range(N):
    if S[i] == '(':
        r += 1
    else:
        if r > 0:
            r -= 1
        else:
            l += 1
ans = '('*l + S + ')'*r
print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007


def A():
    n,m = LI()
    a = LIR(n)
    ans = 0
    for i in range(2):
        for j in range(2):
            for k in range(2):
                a.sort(key = lambda x:(-1)**i*x[0]+(-1)**j*x[1]+(-1)**k*x[2])
                p = [0,0,0]
                for l in range(m):
                    p[0] += a[l][0]
                    p[1] += a[l][1]
                    p[2] += a[l][2]
                p = abs(p[0])+abs(p[1])+abs(p[2])
                if p > ans:
                    ans = p
    print(ans)
    return


def B():
    def root(x):
        if x == par[x]:
            return x
        par[x] = root(par[x])
        return par[x]

    def unite(x,y,su):
        x = root(x)
        y = root(y)
        su += comb_2(s[x])+comb_2(s[y])
        if rank[x] < rank[y]:
            s[y] += s[x]
            su -= comb_2(s[y])
            par[x] = y
        else:
            s[x] += s[y]
            su -= comb_2(s[x])
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1
        return su

    def comb_2(a):
        return a*(a-1)//2

    n,m = LI()
    v = LIR(m)
    par = [i for i in range(n)]
    rank = [0]*n
    s = [1]*n
    su = comb_2(n)
    ans = [su]
    for a,b in v[:0:-1]:
        a -= 1
        b -= 1
        if root(a) != root(b):
            su = unite(a,b,su)
        ans.append(su)
    for i in ans[::-1]:
        print(i)
    return


def C():
    def root(x):
        if par[x] == x:
            return par[x]
        r = root(par[x])
        d[x] += d[par[x]]
        par[x] = r
        return par[x]

    def weight(x):
        root(x)
        return d[x]

    def unite(x,y,w):
        w += weight(x)
        w -= weight(y)
        x = root(x)
        y = root(y)
        if rank[x] < rank[y]:
            par[x] = y
            d[x] = -w
        else:
            par[y] = x
            d[y] = w
            if rank[x] == rank[y]:
                rank[x] += 1
    n,m = LI()
    par = [i for i in range(n)]
    rank = [0]*n
    d = [0]*n
    for i in range(m):
        l,r,w = LI()
        l -= 1
        r -= 1
        if root(l) != root(r):
            unite(l,r,w)
        else:
            if weight(r)-weight(l) != w:
                print("No")
                return
    print("Yes")
    return


def D():
    h,w = LI()
    n = I()
    a = LI()
    ans = [0]*h*w
    p = 0
    for i in range(n):
        for j in range(a[i]):
            ans[p+j] = i+1
        p += a[i]
    for i in range(h):
        s = ans[i*w:(i+1)*w]
        if i%2:
            print(*s[::-1])
        else:
            print(*s)
    return


def E():
    n,k = LI()
    s = [int(x) for x in input()]
    f = [0]*n
    j = 0
    su = 1
    p = s[0]
    for i in range(1,n):
        if s[i] != p:
            f[j] = su
            j += 1
            su = 1
            p = s[i]
        else:
            su += 1
    f[j] = su
    f.append(0)
    if s[0]:
        m = sum(f[:2*k+1])
        ans = m
        for i in range(2*k+1,n):
            m -= f[i-2*k-1]
            if not i%2:
                m += f[i-1]
                m += f[i]
            ans = max(m,ans)
    else:
        m = sum(f[:2*k])
        ans = m
        for i in range(2*k,n):
            m -= f[i-2*k]
            if not i%2:
                m += f[i]
                m += f[i+1]
            ans = max(m,ans)
    print(ans)
    return


def F():
    n = I()
    a = LI()
    s = [0,0,0]
    for i in a:
        if i%4 == 0:
            s[0] += 1
        elif i%2 == 0:
            s[1] += 1
        else:
            s[2] += 1
    a = [0]
    while 1:
        if s[2]:
            if a[-1] == 2:
                print("No")
                return
            s[2] -= 1
            a.append(2)
            if s[0]:
                s[0] -= 1
                a.append(0)
        elif s[1]:
            if a[-1] == 2:
                print("No")
            else:
                print("Yes")
            return
        else:
            print("Yes")
            return
    return


def G():
    n,m,l = LI()
    r = LI()
    for i in range(l):
        r[i] -= 1
    d = [[float("inf")]*n for i in range(n)]
    for i in range(n):
        d[i][i] = 0
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        d[a][b] = c
        d[b][a] = c
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    m = 1<<l
    dp = [[float("inf")]*l for i in range(m)]
    for i in range(l):
        dp[1<<i][i] = 0
    for b in range(m):
        for i in range(l):
            x = r[i]
            if not b&(1<<i):
                continue
            for j in range(l):
                if b&(1<<j):
                    continue
                nb = b|(1<<j)
                y = r[j]
                res = dp[b][i]+d[x][y]
                if res < dp[nb][j]:
                    dp[nb][j] = res
    print(min(dp[m-1]))
    return


def H():
    n,m,q = LI()
    f = [[0]*(n+1) for i in range(n+1)]
    for i in range(m):
        l,r = LI()
        f[l][r] += 1
    for i in range(n+1):
        for j in range(n):
            f[i][j+1] += f[i][j]

    for j in range(n+1):
        for i in range(n):
            f[i+1][j] += f[i][j]
    for i in range(q):
        l,r = LI()
        print(f[r][r]-f[r][l-1]-f[l-1][r]+f[l-1][l-1])
    return


def I_():
    n = I()
    s = input()
    a = ""
    q = 0
    for i in s:
        if i == "(":
            q += 1
        else:
            if q:
                q -= 1
            else:
                a += "("
    print(a+s+")"*q)
    return


if __name__ == "__main__":
    I_()

Solution (Python):
n=input()
s=input()
t=s
while '()' in s:s=s.replace('()','')
print('('*s.count(')')+t+')'*s.count('('))

Solution (Python):

import bisect
import collections
import itertools

def getint(): return int(input())
def getints(): return list(map(int, input().split()))
def getint2d(rows): return [getints() for _ in range(rows)]
def getgrid(rows): return [input() for _ in range(rows)]
def array1d(n, value): return [value for _ in range(n)]
def array2d(n, m, value): return [array1d(m, value) for _ in range(n)]

n=input()
s=input()

l,r=0,0
for c in s:
    if c == '(':
        r += 1
    else:
        if r:
            r -= 1
        else:
            l += 1
res = "(" * l + s + ")" * r
print(res)

Solution (Python):

import sys
from collections import deque
INF = float("inf")


def solve(N: int, S: str):
    X = ""
    counter = 0                 
    for i, c in enumerate(S):
        if c == ')' and counter == 0:
            X = '(' + X + ')'
        elif c == ')' and counter > 0:
            X = X + ')'
            counter -= 1
        elif c == '(':
            X = X + '('
            counter += 1
    X += ')'*counter
    print(X)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    S = next(tokens)  
    solve(N, S)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline

N = int(input())
S = input()
S = S[:-1]
m = 0
diff = 0
for s in S :
    if s == '(' :
        diff += 1
    elif s == ')' :
        diff -= 1
    m = min(m, diff)
print(('('*(-m))+S+(')'*(diff-m)))

Solution (Python):


def main():
    N = int(input())
    S = input().rstrip()
    l, r = 0, 0
    for i in S:
        if i == "(":
            r += 1
        else:
            if r:
                r -= 1
            else:
                l += 1
    ans = "(" * l + S + ")" * r
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):


def main():
    N = int(input())
    S = input().rstrip()
    cnt, pre = 0, 0
    for i in S:
        if i == "(":
            cnt += 1
        else:
            cnt -= 1
            if cnt < 0:
                pre = max(pre, abs(cnt))
    S = "(" * pre + S
    cnt = 0
    for i in S:
        if i == "(":
            cnt += 1
        else:
            cnt -= 1
    S += ")" * cnt
    print(S)
    


if __name__ == "__main__":
    main()

Solution (Python):
n=int(input())
s=input()
c1=0
c2=0
p=10**100
q=10**100
for i in s:
    if i=="(":
        c1+=1
    else:
        c1-=1
    p=min(p,c1)
if p<0:
    s="("*abs(p)+s

for i in range(1,len(s)+1):
    if s[-i]==")":
        c2+=1
    else:
        c2-=1
    q=min(q,c2)
if q<0:
    s=s+")"*abs(q)
print(s)

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n = int(input())
s = input()
cnt = 0
ans = s
while 1:
    f = 0
    for i in range(len(ans)):
        cnt = 0
        for j in range(i+1):
            if ans[j] == ')':
                cnt += 1
        if i+1-cnt < cnt:
            ans = '(' + ans
            f = 1
    if not f:
        break
while 1:
    f = 0
    for i in range(len(ans))[::-1]:
        cnt = 0
        for j in range(i,len(ans))[::-1]:
            if ans[j] == '(':
                cnt += 1
        if len(ans) - i - cnt < cnt:
            ans += ')'
            f = 1
    if not f:
        break
print(ans)

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

n_c = 0
min_n_c = 0
for s in S:
    if s == "(":
        n_c += 1
    else:
        n_c -= 1
    min_n_c = min(min_n_c, n_c)
ans = S
for _ in range(-min_n_c):
    ans = "("+ans
for _ in range(n_c-min_n_c):
    ans += ")"

print(ans)

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

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

print(s)

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


f = 0
b = 0
count = 0
for i in range(N-1, -1, -1):
    if S[i] == '(':
        if count > 0:
            count -= 1
        else:
            b += 1
    else:
        count += 1


for i in range(count):
    print ('(', end = '')
for i in S:
    print (i, end = '')
for i in range(b):
    print (')', end = '')
print ()

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

left = 0
right = 0

for letter in S:
    if letter == '(':
        left += 1
    if letter == ')':
        right += 1
        if left < right:
            S = '(' + S
            left += 1

if right < left:
    S = S + abs(right - left) * ')'
print(S)

Solution (Python):
n = int(input())
s = list(input())
ok_list = []
min_length = 10**9
for i in range(len(s)+1):
    for j in range(len(s)+1):
        s_part = s
        s_part = ["("] * i + s_part + [")"] * j

        if s_part[0] == "(" and s_part[-1] == ")":
            f = 0
            fmin = 0
            ng = 0
            for k in s_part:
                if k == "(":
                    f += 1
                else:
                    f -= 1
                if f < 0:
                    ng = 1
            if f == 0 and ng == 0:
                ok_list.append("".join(s_part))

minl = min(map(len,ok_list))
ok_list = [ i for i in ok_list if len(i) == minl ]
print(sorted(ok_list)[0])

Solution (Python):
import sys
input=sys.stdin.readline
n=int(input())
s=input().rstrip()
r=0
l=0
for i in s:
    if i=='(':
        r+=1
    else:
        if r>0:
            r-=1
        else:
            l+=1
ans='('*l+s+')'*r
print(ans)

Solution (Python):
n = int(input())
s = input()
a = [0]
for i in range(n):
    if s[i] == "(":
        a.append(a[-1] + 1)
    else:
        a.append(a[-1] - 1)
left = -min(a)
right = a[-1] + left
print("(" * left + s + ")" * right)

Solution (Python):
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))

Solution (Python):
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))

Solution (Python):
import math
import copy
from operator import mul
from functools import reduce
from collections import defaultdict
from collections import Counter
from collections import deque

from itertools import product

from itertools import permutations

from itertools import combinations

from itertools import accumulate
from bisect import bisect_left, bisect_right

import re




def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
 
def i_inpl(): return int(input())
def l_inpl(): return list(map(int, input().split()))
def line_inpl(x): return [i_inpl() for _ in range(x)]

INF = int(1e18)
MOD = int(1e9)+7 



N = i_inpl()
S = input()

r, l = 0, 0

for i in range(N):
    si = S[i]
    if si == "(":
        l += 1
    elif si == ")":
        if l > 0:
            l -= 1
        else:
            r += 1

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

Solution (Python):
n = int(input())
s = input()
ans = ''
cnt = 0
for i in s:
  if i == ')' and cnt == 0:
    ans = '(' + ans + ')'
  elif i == ')' and cnt > 0:
    cnt -= 1
    ans = ans + ')'
  else:
    cnt += 1
    ans = ans + '('
if cnt > 0:
  ans = ans + ')'*cnt
print(ans)

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

Solution (Python):
n = int(input())
s = list(input())
l = []
count1 = 0
count2 = 0
for i in range(n):
    if s[i] == ")":
        if count2 == 0:
            l.append("(")
        else:
            count2 = count2 - 1
    else:
        count2 = count2 + 1
if count2 > 0:
    l2 = [")"]*count2
    ans = l + s + l2
    for i in ans:
        print(i, end = "")
else:
    ans = l + s
    for i in ans:
        print(i, end = "")

Solution (Python):
N = int(input())
S = input()
T = S
k = 0
for s in S:
    if s=="(":
        k+=1
    else:
        k-=1
        if k==-1:
            T = "("+T
            k=0
print(T+")"*k)

Solution (Python):
n = int(input())
s = input()
r = 0
l = 0
cnt = 0
for i in s:
    if i==')':
        cnt+=1
        if cnt>0:
            cnt-=1
            l+=1
    else:
        cnt-=1
print(l*'('+s+')'*(-cnt))

Solution (Python):
N = int(input())
S = input()
front = ""
rangle = 0
langle = 0
for i in range(N):
    if S[i] == ")":
        if langle == 0:
            front = "("+front
        else:
            langle -= 1
    else:
        langle += 1
print(front+S+")"*langle)

Solution (Python):
import copy
n = int(input())
s = input()
ans = copy.deepcopy(s) 
flag = True
while flag:
    flag = False
    for i in range(len(s)-1):
        if s[i] == '(' and s[i+1] == ')':
            s = s[:i] + s[i+2:]
            flag = True
            break


for i in range(len(s)):
    if s[i] == "(":
        ans += ")"
    elif s[i] == ")":
        ans = "(" + ans


print(ans)

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

a = []
for i in s:
    if a and a[-1] == "(" and i == ")":
        a.pop()
    else:
        a.append(i)

c = a.count("(")
d = a.count(")")


print("("*d+s+")"*c)

Solution (Python):
import numpy as np
import copy


def dfs(adj_list, cur_node, visited_nodes):
    visited_nodes.append(cur_node)

    
    next_nodes = adj_list[cur_node]

    if len(next_nodes) == 0:
        
        visited_nodes.remove(cur_node)
        return 0

    for tup in next_nodes:
        if tup[0] in visited_nodes:
            visited_nodes.remove(cur_node)
            return np.inf

    
    
    scores = []
    for b, c in next_nodes:
        score = dfs(adj_list, b, visited_nodes) + c
        if np.isinf(score):
            visited_nodes.remove(cur_node)
            return np.inf
        scores.append(score)

    score_max = max(scores)

    visited_nodes.remove(cur_node)
    return score_max


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

    y_max = 0
    y = 0
    for c in S:
        if c == '(':
            y -= 1
        else:
            y += 1

        if y > y_max:
            y_max = y

    S_ans = ''
    if y_max > 0:
        S_ans += '(' * y_max
        y -= y_max

    S_ans += S

    if y < 0:
        S_ans += ')' * (-y)

    
    
    
    
    
    
    
    

    
    

    

    

    print(S_ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    _ = int(input())
    S = input()
    a = 0
    b = 0
    for s in S:
        if s == '(':
            b += 1
            continue
        if s == ')' and b == 0:
            a += 1
            continue
        b -= 1
    print('(' * a + S + ')' * b)


main()

Solution (Python):
_=input()
S=input()
cnt,ladd,radd=0,0,0
for c in S:
    if c=="(":
        cnt+=1
    elif c==")":
        if cnt==0:
            ladd+=1
        else:
            cnt-=1
radd=cnt
print("("*ladd + S + ")"*radd)

Solution (Python):
N = int(input())
S = input()
p = ["(", ")"]
l = 0
n = 0
for i in range(N - 1, -1, -1):
  if S[i] == p[1]:
    l += 1
  else:
    if l > 0:
      n += 2
      l -= 1

r = N - n - l
print(p[0] * l + S + p[1] * r)

Solution (Python):
from collections import Counter
N = int(input())
S = input()
m = Counter(S)
cnt_set = 0
cur = 0
for x in S:
    if x == '(':
        cur += 1
    else:
        if cur > 0:
            cnt_set += 1
            cur -= 1
ans = '('*(m[')']-cnt_set) + S + ')'*(m['(']-cnt_set)
print(ans)

Solution (Python):
from collections import deque
N = int(input())
S = input()
d = deque()
cnt = 0
for x in S:
    if x == '(':
        d.append(1)
    elif x == ')' and d:
        d.pop()
    else:
        cnt += 1
print('(' * cnt + S + ')' * len(d))

Solution (Python):
N = int(input())
S = input()
_S = S
while '()' in S:
    for i in range(len(S)-1):
        if S[i] =='(' and S[i+1] == ')':
            S = S[:i] + S[i+2:]
            break
c1 = S.count(')')
c2 = S.count('(')
print('(' * c1 + _S + ')' * c2)

Solution (Python):
from collections import deque
n = int(input())
s = input()
q = deque()
r = ""
l = ""
for i in s:
    if i == ")":
        if not q:
            r+="("
        else:
            q.pop()
    else:
        q.append("(")
while q:
    q.pop()
    l+=")"
print(r+s+l)

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

back = 0
front = 0
for k in s:
    if k == '(':
        back += 1
    else:
        back -= 1
        while back < 0:
            front += 1
            back += 1
f = ""
for i in range(front):
    f = f + '('
b = ""
for i in range(back):
    b = b + ")"
s = f + s + b

print(s)

Solution (Python):
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))

Solution (Python):
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
import bisect
import copy
import fractions
import itertools
import math
import queue
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers): return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers): return reduce(LCM, numbers)
def LCM(m, n): return (m * n // fractions.gcd(m, n))
class UnionFind():

    def __init__(self, n):
        self.n = n
        self.node = [i for i in range(n)]
        self.size = [1 for _ in range(n)]

    def same(self, x, y):
        return bool(self.root(x) == self.root(y))

    def root(self, x):
        if self.node[x] == x:
            return x
        else:
            self.node[x] = self.root(self.node[x])  
            return self.node[x]

    def unite(self, x, y):
        x, y = self.root(x), self.root(y)
        if x == y:
            return  
        if self.size[x] < self.size[y]:
            x, y = y, x
        self.node[y] = x
        self.size[x] += self.size[y]

    def return_size(self, x):
        return self.size[self.root(x)]


n = II()
s = IS()
cnt = 0
ans = s
for c in s:
    if c == '(':
        cnt += 1
    else:
        if cnt > 0:
            cnt -= 1
        else:
            ans = '(' + ans
cnt = 0
for c in s[::-1]:
    if c == ')':
        cnt += 1
    else:
        if cnt > 0:
            cnt -= 1
        else:
            ans = ans + ')'
print(ans)

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

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

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

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

ans = ''
l = 0
for i in range(N):
    if S[i] == '(':
        l += 1
        ans = ans + '('
    else:
        if l > 0:
            ans = ans + ')'
            l -= 1
        else:
            ans = '(' + ans + ')'
ans = ans + ')'*l
print(ans)

Solution (Python):
N = int(input())
S = input()
now = [0]
newS = ""
for s in S:
    if s == "(":
        now.append(now[-1] + 1)
    else:
        now.append(now[-1] - 1)
        
if min(now) < 0:
    newS += "(" * abs(min(now))
newS += S
if now[-1]+abs(min(now)) > 0:
    newS += ")" * (now[-1]+abs(min(now)))
print(newS)

Solution (Python):
n=int(input())
s=input()
b=l=r=0
for i in s:
    if(i==")"):
        l+=1
    if(i=="("):
        r+=1
    if(l>r):
        b+=1
        r+=1
print("("*b+s+")"*(r-l))