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

-----Sample Output-----
(())


Difficulty: interview

Starter code:

Solutions:
n=int(input())
S=input()
x=y=0
for i,s in enumerate(S):
  y=y-1 if s=='(' else y+1
  x=max(x,y)
print('('*x+S+')'*(x-y))

n = int(input())
s = input()
while True:
  c = 0
  for i in range(len(s)):
    if s[i] == "(":
      c += 1
    else:
      c -= 1
    if c < 0:
      s = "(" + s
      break
  if c > 0:
    s = s + ")"
  if c == 0:
    print(s)
    break
  


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

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

def __starting_point():
    main()
__starting_point()

import sys
input = sys.stdin.readline
from collections import deque


def read():
    N = int(input().strip())
    S = input().strip()
    return N, S


def solve(N, S):
    rank = 0
    q = deque()
    for s in S:
        if rank == 0:
            if s == ")":
                q.appendleft("(")
                q.append(")")
            else:
                q.append("(")
                rank += 1
        else:
            if s == ")":
                q.append(")")
                rank -= 1
            else:
                q.append("(")
                rank += 1
    while rank > 0:
        q.append(")")
        rank -= 1
    return "".join(q)


def __starting_point():
    inputs = read()
    print((solve(*inputs)))

__starting_point()

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

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

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

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

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

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

import sys
input = sys.stdin.readline

n = int(input())
S = input().rstrip()
b = 0
q = 0

for s in S:
    if s == '(':
        b +=1
    else:
        if b>0:
            b -= 1
        else:
            q += 1
print(('('*q+S+')'*b))


icase=0
if icase==0:
    n=int(input())
    s=input()
elif icase==1:
    n=3
    s="())"
elif icase==2:
    n=6
    s=")))())"
elif icase==3:
    n=8
    s="))))(((("

l=[]
r=[]
sim=s[0]
if sim=="(":
    lidx=0
    l.append(1)
    ridx=-1
elif sim==")":
    lidx=0
    l.append(0)
    ridx=0
    r.append(1)

for i in range(1,len(s)):
    if s[i]=="(" and s[i-1]=="(":
        l[lidx]+=1
    elif s[i]=="(" and s[i-1]==")":
        lidx+=1
        l.append(1)
    elif s[i]==")" and s[i-1]==")":
        r[ridx]+=1
    elif s[i]==")" and s[i-1]=="(":
        ridx+=1
        r.append(1)

ll=sum(l)
rr=sum(r)
ds=ll-rr

if len(l)>len(r):
    r.append(0)
xmin=0
x=0
for i in range(len(l)):
    x=x+l[i]-r[i]
    xmin=min(x,xmin)
    
strs="("*(-xmin) + s + ")"*(ds-xmin)
print(strs)
    


n = int(input())
s = input()
cnt, L = 0, 0
for i in range(len(s)):
    if s[i] == '(':
        cnt += 1
    else:
        cnt -= 1

    if cnt < 0:
        L = min(L, cnt)

ans = '('*abs(L) + s
R = ans.count('(') - ans.count(')')
ans += ')'*R

print(ans)


n = int(input())
s = input()
l, r, c = 0, 0, 0
for a in s:
    if a == '(':
        c += 1
    elif c:
        c -= 1
    else:
        l += 1
r = c
print(("("*l + s + ")"*r))


N = int(input())
motoS = input()
S = list(motoS)
start = 0
end = 0
for i in range(N):
    if S[i] == '(':
        end += 1
    else:
        end -= 1
    if end < 0:
        start += 1
        end = 0
print('('*start+motoS+')'*end)

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

lp=0
rp=0
for i in range(n):
  if s[i]=='(':
    rp+=1
  else:
    rp=rp-min(rp,1)
for i in range(n-1,-1,-1):
  if s[i]==')':
    lp+=1
  else:
    lp=lp-min(lp,1)

print('('*max(0,lp)+s+max(0,rp)*')')

def main():
    import sys

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

    n = int(input())
    s = input()
    cnt = 0
    m = 0
    for i in range(n):
        if s[i] == '(':
            cnt += 1
        else:
            cnt -= 1
        m = min(m, cnt)
    ans = '('*(-m)+s+')'*(cnt-m)
    print(ans)


def __starting_point():
    main()
__starting_point()

n=int(input())
s=input()
l=[]
for i in s:
  if i==')':
    if len(l)>0:
      if l[-1]=='(':
        l.pop()
      else:
        l.append(i)
    else:
      l.append(i)
  else:
    l.append(i)
print((l.count(')')*'(' + s +l.count('(')*')'))


def main2():
    input()
    s = input()
    pair = [-1] * 2
    ans = s
    idx = 0
    for idx in range(0, len(s)):
        for i in range(idx, len(s)):
            if s[i] == '(':
                pair[0] = i if pair[0] == -1 else pair[0]
            elif s[i] == ')':
                pair[1] = i
                break
        if pair[0] != -1 and pair[1] != -1:
            s = s[:pair[0]] + ' ' + s[pair[0]+1:pair[1]] + ' ' + s[pair[1]+1:]
        elif pair[0] != -1 and pair[1] == -1:
            s = s[:pair[0]] + ' ' + s[pair[0]+1:]
            ans = ans + ')'
        elif pair[0] == -1 and pair[1] != -1:
            s = s[:pair[1]] + ' ' + s[pair[1]+1:]
            ans = '(' + ans
        pair = [-1] * 2
    print(ans)


def __starting_point():
    main2()
__starting_point()

n = input()
s = input()
ss = s
for i in range(50):
  s = s.replace('()','')
l = s.count(')')
r = s.count('(')
print('('*l+ss+')'*r)

def main():
    n = int(input())
    s = input()
    l, r, c = 0, 0, 0
    for a in s:
        if a == '(':
            c += 1
        elif c:
            c -= 1
        else:
            l += 1
    r = c
    print(("("*l + s + ")"*r))


def __starting_point():
    main()

__starting_point()

import sys, math, re
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

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

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N = ii()
    S = input()
    l = [0]
    for i in range(N):
        if S[i] == '(':
            l.append(l[-1]+1)
        else:
            l.append(l[-1]-1)

    m = min(l)

    if m < 0:
        l = list(map(lambda x: x-m, l))

    print('('*l[0] + S + ')'*l[-1])

def __starting_point():
    main()
__starting_point()

N=int(input())
S=input()
i=0
hidari=str()
migi=str()
a=0
while i<N:
  if S[i]==")":
    hidari+="("
    i+=1
  else:
    break
while i<N:
  if S[i]=="(":
    a+=1
  else:
    a-=1
  i+=1
if a<0:
  hidari+=abs(a)*"("
elif a>0:
  migi+=a*")"
s=hidari+S+migi


i=0
hidari=str()
migi=str()
a=0
while i<N:
  if S[i]==")":
    hidari+="("
    i+=1
  else:
    break
while i<N:
  if S[i]=="(":
    if a<0:
      a=0
    a+=1
    mina=0
  else:
    a-=1
    if a<0:
      if mina>a:
        hidari+="("
  i+=1
if a>0:
  migi+=a*")"
t=hidari+S+migi
if len(s)==len(t):
  print(s)
elif len(s)>len(t):
  print(s)
else:
  print(t)

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

# In[1]:


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


# In[2]:


l = 0
r = 0
for s in S:
    if s == "(":
        r += 1
    else:
        if r > 0:
            r -= 1
        else:
            l += 1
ans = "".join(["("*l , S, ")"*r])
print(ans)


# In[ ]:






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

while s_.count('()'):
    s_ = s_.replace('()', '')

l = s_.count(')')
r = len(s_) - l

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


n = int(input())
S = input()
T = S.replace('()', '')
for _ in range(50):
  T = T.replace('()', '')
print('(' * T.count(')') + S + ')' * T.count('('))

n = int(input())
s = input()
left = 0
right = 0
for i in range(n):
    if s[i] == '(':
        right += 1
    else:
        if right > 0:
            right -= 1
        else:
            left += 1
print((left * '(' + s + right * ')'))


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

l = 0
r = 0

L = ''
for i in S:
    if i == '(':
        l += 1
    else:
        r += 1

    if l < r:
        L += '('
        l += 1
R = ')'*(l-r)
print((L+S+R))


def main():
    n = int(input())
    s = input()
    l, r, c = 0, 0, 0
    for a in s:
        if a == '(':
            c += 1
        else:
            if c:
                c -= 1
            else:
                l += 1
    r = c
    print(("("*l + s + ")"*r))


def __starting_point():
    main()

__starting_point()

import math
from math import gcd,pi,sqrt
INF = float("inf")

import sys
sys.setrecursionlimit(10**6)
import itertools
from collections import Counter,deque
def i_input(): return int(input())
def i_map(): return list(map(int, input().split()))
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]


def main():
    n = i_input()
    s = input()

    l = 0
    r = 0

    for i in s:
        if i == ")" and r > 0:
            r -= 1
        elif i == ")":
            l += 1
        if i == "(":
            r += 1
    print(("("*l + s + ")"*r))




def __starting_point():
    main()

__starting_point()

from collections import deque

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


left=0
right=0
for i in range(n):
  if s[i]=="(":
    left+=1
  else:
    if left>0:
      left-=1
    else:
      right+=1
    
      

for _ in range(left):
    s.append(")")
    

for _ in range(right):
    s.appendleft("(")

print(("".join(s)))


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

stack = []
for c in S:
    if len(stack) > 0:
        last = stack[-1]
        if last == '(' and c == ')':
            stack = stack[:-1]
            continue
    stack.append(c)

left = stack.count(')')
right = stack.count('(')

print(left * '(' + S + right * ')')

import re

N = int(input())
s = input()[:N]
s_check = s
s_check = re.sub('\(\)', '', s_check)

while len(s_check) > 0:
    for i in range(len(s_check)):
        if s_check[i] == ')':
            s = '(' + s
            s_check = '(' + s_check
            break
        elif s_check[i] == '(':
            break

    for i in range(len(s_check)):
        if s_check[-i-1] == '(':
            s = s + ')'
            s_check = s_check + ')'
            break
        elif s_check[-i-1] == ')':
            break

    s_check = re.sub('\(\)', '', s_check)

print(s)

N = int(input())
S = input()
left_cnt = 0
right_cnt = 0
for s in S:
    if s == '(':
        left_cnt += 1
    else:
        if left_cnt == 0:
            right_cnt += 1
        else:
            left_cnt -= 1
S = '(' * right_cnt + S + ')' * left_cnt
print(S)


N = int(input())
s = input()

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


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

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

def __starting_point():
    main()

__starting_point()

N = int(input())
S = input()
l = r = 0
L = ""
for i in S:
    if i == "(":
        l += 1
    else:
        r += 1
    if l < r:
        L += "("
        l += 1
R = ")"* (l-r)
print(L+S+R)

_,S,l,r=input(),input(),'(',')'
t=S
while t.count(l+r):
 t=t.replace(l+r,'')
print(l*t.count(r)+S+r*t.count(l))

N = int(input())
S = input()
now = 0
right = 0
left = 0
add_left = 0
while now < N:
    if S[now] == '(':
        left += 1
    else:
        if left:
            left -= 1
        else:
            add_left += 1
    now += 1
for _ in range(add_left):
    print('(', end='')
print(S, end='')
for _ in range(left):
    print(')', end='')



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

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

ans += (")"*l)

print(ans)


n=int(input())
s=input()
ans=[]
minscore=0
score=0
for i in range(n):
  if s[i]=='(':
    score+=1
  else:
    score-=1
  minscore=min(minscore,score)
finalscore=score
for i in range(-minscore):
  ans.append('(')
for i in range(n):
  ans.append(s[i])
for i in range(-minscore+finalscore):
  ans.append(')')
print(''.join(ans))

N=int(input())
S=input()
A=0 #(
B=0 #)

for s in S:
    if s=='(':
        A+=1
    elif s==')' and A>0:
        A-=1
    else:
        B+=1

print('('*B+S+')'*A)

N = input()
S = input()
s = S
for i in range(50):
  S = S.replace('()','')
l = S.count(')')
r = S.count('(')
print('('*l+s+')'*r)

import copy
N = int(input())
S = list(input())
S_ans = copy.deepcopy(S)
app = 0
q = [0]
save = 0
for i in range(N):
    if S[i] == '(':
        q.append(q[-1] + 1)
        
    else:
        q.append(q[-1] - 1)
        if q[-1] == -1:
            S_ans.insert(app + save,"(")
            app += 1
            q[-1] = 0

for i in range(q[-1]):
    S_ans.append(")")
print("".join(S_ans))

n = int(input())
s = input()
cnt_l, cnt_r = 0, 0

for x in s:
	if x == "(":
		cnt_l += 1
	elif cnt_l > 0:
		cnt_l -= 1
	else:
		cnt_r += 1

print((cnt_r * "(" + s + cnt_l * ")"))


# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""
def main():
    N = int(input())
    S = input()

    solo_close_no = 0
    for i in range(N):
        if S[-i-1] == ")":
            solo_close_no += 1
        elif solo_close_no >= 1:
            solo_close_no -= 1
    
    solo_open_no = 0
    for i in range(N):
        if S[i] == "(":
            solo_open_no += 1
        elif solo_open_no >= 1:
            solo_open_no -= 1

    answer = "("*solo_close_no + S + ")"*solo_open_no
    print(answer)

def __starting_point():
    main()


__starting_point()

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

a = ""

stack = []

for i in range(len(s)):
    if s[i] == "(":
        stack.append("(")
        a += "("
    elif s[i] == ")" and len(stack) == 0:
        stack.append(")")
        a += ")"
    elif s[i] == ")" and stack[-1] == ")":
        stack.append(")")
        a += ")"
    else:  # s[i] == ")" and stack[-1] == "("
        stack.pop(-1)
        a += ")"

while len(stack) > 0:
    if stack[len(stack) - 1] == ")":
        e = len(stack) - 1
        s = e
        while s - 1 >= 0 and stack[s - 1] == ")":
            s -= 1
        a = "(" * (e - s + 1) + a
        stack = stack[:s]
    elif stack[len(stack) - 1] == "(":
        e = len(stack) - 1
        s = e
        while s - 1 >= 0 and stack[s - 1] == "(":
            s -= 1
        a = a + ")" * (e - s + 1)
        stack = stack[:s]

print(a)


N = int(input())
S = input()
T = list(1 if c == "(" else -1 for c in S)
l, l_min = 0, 0
r, r_min = 0, 0
for i in range(N):
    l += T[i]
    l_min = min(l_min, l)
    r -= T[N - i - 1]
    r_min = min(r_min, r)
print("".join(["(" * -l_min, S, ")" * -r_min]))

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

l, r = 0, 0
p, m = 0, 0
for i in range(N):
  if S[i] == "(":
    l += 1
  else:
    r += 1
  if l < r:
    p += 1
    l += 1

m = l - r

for i in range(p):
  print("(", end = "")
print(S, end ="")
for i in range(m):
  print(")", end = "")

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

for n in range(N):
  T = T.replace("()","")

L = T.count("(")
R = T.count(")")
S = R*"("+S+L*")"
print(S)

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

l = 0
r = 0
p = []
for i in range(n):
  if s[i] == "(": p.append("(")
  else:
    if p == []: l += 1
    else: p.pop()
r = p.count("(")
print("("*l + s + ")"*r)

_ = input()
S = input()

needs_right = 0
needs_left = 0

for c in S:
    if c == '(':
        needs_right += 1
    else:
        if needs_right == 0:
            needs_left += 1
        else:
            needs_right -= 1

print(('(' * needs_left + S + ')' * needs_right))



n = int(input())
s = list(input())
d = [0]
x = 0

for i in range(len(s)):
    if s[i] == '(':
        x += 1
    else:
        x -= 1
    d.append(x)

ans = []
x = min(d)

for i in range(max(0,(-1*x))):
    ans.append('(')

for i in s:
    ans.append(i)

for i in range(max(d[len(d)-1]-x,0)):
    ans.append(')')

a = ''.join(ans)

print(a)


with open(0) as f:
    N, S = f.read().split()
N = int(N)
S += '_'
left = 0
right = 0
cnt = 0
for i in range(N):
    cnt += {'(':1, ')':-1}[S[i]]
    if S[i] == ')' and S[i+1] != ')':
        if cnt < 0:
            left += -cnt
            cnt = 0
    if i == N-1 and cnt > 0:
        right += cnt
ans = '(' * left + S[:N] + ')' * right
print(ans)

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

def add1(S):
  cum=[0]
  for i in range(len(S)):
    if S[i]=='(':cum.append(cum[-1]+1)
    else:cum.append(cum[-1]-1)
  if min(cum)>=0:return S
  out = '('*(-min(cum))
  out += S
  return out

def add2(S):
  cum=[0]
  for i in range(len(S)):
    if S[i]=='(':cum.append(cum[-1]+1)
    else:cum.append(cum[-1]-1)
      
  if cum[-1]==0:return S
  n = cum[-1]
  out = S + ')'*n
  return out

S = add1(S)
S = add2(S)
print(S)

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

ans = S
count = 0

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

count = 0

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

    if(count>0):
        ans = ans + ")"
        count -= 1

print(ans)


n = int(input())
s = str(input())
l = []
left, right = 0, 0
for c in s:
    if c == ')':
        if l == []:
            left += 1
        else:
            l.pop()
    else:
        l.append(1)
right = len(l)
print('(' * left + s + ')' * right)

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

s=s[::-1]
balance = 0
i = 0
while i < len(s):
    if s[i] == ')':
        balance+=1
    else:
        balance-=1
    if balance<0:
        s.insert(0, ')')
        balance+=1
        i+=1
    i+=1


balance = 0
i = 0
s=s[::-1]
while i < len(s):
    if s[i] == '(':
        balance+=1
    else:
        balance-=1
    if balance<0:
        s.insert(0, '(')
        balance+=1
        i+=1
    i+=1

print((''.join(s)))
    


def main():
    #input data
    import sys
    input = lambda:sys.stdin.readline().strip()
    N = int(input())
    S = input()
    
    #solve
    right=0
    left=0

    for i in range(N):
        if S[i]=='(':
            right+=1
        else:
            if right:
                right-=1
            else:
                left+=1
    print(left*'('+S+right*')')

def __starting_point():
    main()
__starting_point()

N = int(input())
S = input()
l = 0
r = 0
for i in range(N):
    if S[i] == ")":
        r -= 1
        if r < 0:
            l += 1
            r += 1
    else:
        r += 1
print("("*l+S+")"*r)

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

# (
x = 0
y = 0
for i in range(n):
    if s[i] == '(':
        x += 1

    if s[i] == ')':
        if x >= 1:
            x -= 1
        else:
            y += 1

for _ in range(x):
    s.append(')')

for _ in range(y):
    s.insert(0,'(')
ans = ''.join(s)
print(ans)


N = int(input())
S = input()
nS = S
for i in range(50):
    nS = nS.replace("()", "")
r = nS.count(")")
l = nS.count("(")
print("(" * r + S + ")" * l)

from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n = INT()
s = input()

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

s += ')'*count
        
count = 0
for i in range(n-1, -1, -1):
    if s[i] == ')':
        count += 1
    else:
        count = max(0, count-1)

s = '('*count + s
print(s)

n = int(input())
s = input()
R, L = 0, 0
for i in range(len(s)):
    if s[i] == '(':
        R += 1
    else:
        if R:
            R -= 1
        else:
            L += 1

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


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

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


import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    S = input()

    right = 0
    left = 0
    for i in range(n):
        if S[i] == "(":
            left += 1
        else:
            if left:
                left -= 1
            else:
                right += 1
    res = "(" * right + S + ")" * left
    print(res)


def __starting_point():
    resolve()

__starting_point()

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

c0 = 0
c1 = 0
z0 = 0
z1 = 0
for i in range(n):
    if s[i] == "(":
        c0 += 1
    else:
        if c0 > 0:
            c0 -= 1
        else:
            c1 += 1
ans = ["("]*c1 + s + [")"]*c0
print("".join(ans))

def main():
	N = int(input())
	S = input()
	brackets = [0, 0]
	for i in range(len(S)):
		if S[i] == ")":
			if brackets[0] > 0:
				brackets[0] -= 1
			else:
				brackets[1] += 1
		elif S[i] == "(":
			brackets[0] += 1
	print(brackets[1] * "(" + S + brackets[0] * ")")

main()

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

c0 = 0
c1 = 0
z0 = 0
z1 = 0
for i in range(n):
    if s[i] == "(":
        c0 += 1
    else:
        if c0 > 0:
            c0 -= 1
        else:
            c1 += 1
z0 = c1
s = s[::-1]
c0 = 0
c1 = 0
for i in range(n):
    if s[i] == ")":
        c0 += 1
    else:
        if c0 > 0:
            c0 -= 1
        else:
            c1 += 1
z1 = c1
s = s[::-1]
ans = ["("]*z0 + s + [")"]*z1
print("".join(ans))


icase=0
if icase==0:
    n=int(input())
    s=input()
elif icase==1:
    n=3
    s="())"
elif icase==2:
    n=6
    s=")))())"
elif icase==3:
    n=8
    s="))))(((("

l=[]
r=[]
sim=s[0]
if sim=="(":
    lidx=0
    l.append(1)
    ridx=-1
elif sim==")":
    lidx=0
    l.append(0)
    ridx=0
    r.append(1)

for i in range(1,len(s)):
    if s[i]=="(" and s[i-1]=="(":
        l[lidx]+=1
    elif s[i]=="(" and s[i-1]==")":
        lidx+=1
        l.append(1)
    elif s[i]==")" and s[i-1]==")":
        r[ridx]+=1
    elif s[i]==")" and s[i-1]=="(":
        ridx+=1
        r.append(1)

ll=sum(l)
rr=sum(r)
ds=ll-rr

if len(l)>len(r):
    r.append(0)
elif len(l)<len(r):
    l.append(0)
xmin=100
x=0
for i in range(len(l)):
    x=x+l[i]-r[i]
    xmin=min(x,xmin)
if xmin>0:
    xmin=0
    
strs="("*(-xmin) + s + ")"*(ds-xmin)
print(strs)


#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
    return int(readline())
n = I()
S = input()
left = 0
right = 0
for i in range(n):
    if S[i] == '(':
        right += 1
    elif S[i] == ')':
        if right >= 1:
            right -=1
        else:
            left += 1
print(('('*left + S + ')'*right))


#!/usr/bin/env python3
input()
s = input()
c = 0
for i in s:
    if i == "(":
        c += 1
    else:
        if c > 0:
            c -= 1
d = 0
for i in s[::-1]:
    if i ==")":
        d += 1
    else:
        if d > 0:
            d -= 1
print(("("*d+s+")"*c))




n = int(input())
s = input()
ans = s
while s.count("()")>0:
    s = s.replace("()", "")
cnt_l = s.count(")")
cnt_r = s.count("(")
print(cnt_l * "(" + ans + cnt_r * ")")

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

oS = S
S = list(S)

cnt = 0
while True:
    p_cnt = cnt
    for i in range(len(S) - 1):
        if S[i] == "(" and S[i + 1] == ")":
            S.pop(i + 1)
            S.pop(i)
            cnt += 1
            break

    if cnt == p_cnt:
        break

cnt_open = 0
cnt_close = 0

for s in S:
    if s == "(":
        cnt_open += 1
    else:
        cnt_close += 1

ans = ("(" * cnt_close) + oS + (")" * cnt_open)
print(ans)


N = int(input())
S = input()
l = r = 0
L = ""
for i in S:
    if i == "(":
        l += 1
    else:
        r += 1
    if l < r:
        L += "("
        l += 1
R = ")"* (l-r)
print(L+S+R)

n,s = open(0).read().split()

imp_close = 0
imp_open = 0

for char in s:
    if char == '(':
        imp_open += 1
    else:
        if imp_open:
            imp_open -= 1
        else:
            imp_close += 1

print('('*imp_close + s + ')'*imp_open)

import sys

input = sys.stdin.readline


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

    ans = ""
    n_left = 0
    n_right = 0
    for s in S:
        if s == "(":
            n_left += 1
        else:
            if n_left > 0:
                n_left -= 1
            else:
                n_right += 1

    ans = "".join(("(" * n_right, S, ")" * n_left))
    print(ans)


def __starting_point():
    main()

__starting_point()

n = int(input())
s = input()
ss = s
while ss.count('()'):
    ss = ss.replace('()', '')
left, right = ss.count('('), ss.count(')')
print('(' * right + s + ')' * left)

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

flg_l = False
cnt_r = 0
cnt_l = 0

for i in range(N):
    if(S[i] == "("):
        cnt_r += 1
        flg_l = True            
    else:
        if(flg_l):
            if(cnt_r > 0):
                cnt_r -= 1
            else:
                cnt_l += 1
                flg_l = False
        else:
            cnt_l += 1
    
ans = ""

ans += ("("*cnt_l)+S+(")"*cnt_r)
print(ans)

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

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

        if opens < 0:
            l += 1
            opens = 0

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

n = int(input())
s = input()
countr, countl = 0, 0

for i in range(n-1, -1, -1):
    if s[i] == ')': countr += 1
    elif countr > 0: countr -= 1
s = '('*countr+s
n = len(s)

for i in range(n):
    if s[i] == '(': countl += 1
    elif countl > 0: countl -= 1
s += ')'*countl

print(s)


from collections import deque

N = int(input())
S = input()
que = deque(S)
l = r = 0

for s in S:
    if s == '(':
        l += 1
    else:
        r += 1
    if l < r:
        que.appendleft('(')
        l += 1
else:
    ans = "".join(que)
    if r < l:
        ans = ans + ")" * (l - r)
print(ans)

# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict, namedtuple
import heapq
from math import sqrt, factorial, gcd, ceil, atan, pi
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1] # warning bytes
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8')
import string
import operator
import random
# string.ascii_lowercase
from bisect import bisect_left, bisect_right
from functools import lru_cache, reduce
MOD = int(1e9)+7
INF = float('inf')

sys.setrecursionlimit(int(1e6))

def solve():
    n = int(input())
    s = input()

    stack = [-1]
    for e in s:
        if e == '(':
            stack.append(e)
        else:
            if stack[-1] == '(':
                stack.pop()
            else:
                stack.append(e)
    l = stack.count(')')
    r = stack.count('(')
    print(('(' * l + s + ')' * r))
    

T = 1
# T = int(input())
for case in range(1,T+1):
    ans = solve()


"""

dp[num_changes][blue_placed]


abba



"""


n = int(input())
S = input()
lc = 0
rc = 0
for s in S:
    if s=='(':
        rc += 1
    else:
        if rc:
            rc -= 1
        else:
            lc += 1
print('('*lc+S+')'*rc)

import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return list(map(int, input().split()))
def MI1(): return list(map(int1, input().split()))
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print((k.join(list(map(str, lst)))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    S = LS()
    q = deque([])
    # print(S)
    cnt = 0
    for s in S:
        if s == '(':
            cnt += 1
            q.append(s)
        else:   # ')'
            if cnt >= 1:
                q.append(s)
                cnt -= 1
            else:
                q.appendleft('(')
                q.append(s)
    for _ in range(cnt):
        q.append(')')

    # print(q)
    printlist(q, '')

def __starting_point():
    solve()

__starting_point()

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

cntr = 0
for i in range(n-1, -1, -1):
    if s[i] == ')':
        cntr += 1
    elif cntr > 0:
        cntr -= 1
s = '(' * cntr + s
n = len(s)

cntl = 0
for i in range(n):
    if s[i] == '(':
        cntl += 1
    elif cntl > 0:
        cntl -= 1
s += ')' * cntl

print(s)

import sys
from collections import deque


def IN_I(): return int(sys.stdin.readline().rstrip())
def IN_LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def IN_S(): return sys.stdin.readline().rstrip()
def IN_LS(): return list(sys.stdin.readline().rstrip().split())


N = IN_I()
S = IN_S()
d = deque(S)

l = 0
for i in range(N):
    if S[i] == '(':
        l += 1
    else:
        if l == 0:
            d.appendleft('(')
        else:
            l -= 1

r = 0
for i in range(N - 1, -1, -1):
    if S[i] == ')':
        r += 1
    else:
        if r == 0:
            d.append(')')
        else:
            r -= 1
print((''.join(d)))


import sys

input = sys.stdin.readline


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

    L = 0
    R = 0
    for s in S:
        if s == "(":
            R += 1
        else:
            if R > 0:
                R -= 1
            else:
                L += 1

    ans = "".join(["(" * L, S, ")" * R])
    print(ans)


def __starting_point():
    main()

__starting_point()

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


n = input()
cnt = 0
S = input()
m = 0
for s in S:
    if s == "(":
        cnt += 1
    else:
        cnt -= 1
    m = min(m, cnt)

left = -min(0, m)
right = abs(cnt - m)
print(("(" * left + S + ")" * right))


N=int(input())
S=input()
x=0
m=0
for i in range(N):
    if S[i]=='(':
        x+=1
    else:
        x-=1
        m=min(x,m)

a=-m
b=x-m
print(('('*a+S+')'*b))


from collections import deque

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

reserveL = deque()
out = deque()
q = deque()

for s in S:
    if s == "(":
        reserveL.append(s)
        out.append("(")
    else:
        # print(len(reserveL))
        if len(reserveL) == 0:
            out.appendleft("(")
            out.append(")")
        else:
            out.append(")")
            reserveL.popleft()

    # print(out)

# print(out)
while reserveL:
    out.append(")")
    reserveL.popleft()
ans = ""
while out:
    ans += out.popleft()
print(ans)


from collections import deque

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


left=0
right=0
for i in range(n):
  if s[i]=="(":
    left+=1
  else:
    if left>0:
      left-=1
    else:
      right+=1
    
      

for _ in range(left):
    s.append(")")
    

for _ in range(right):
    s.appendleft("(")

print("".join(s))

n = int(input())
s = input()
counter_l = 0
pairs = 0
double_check = set()

for i in range(n):
    if s[i] == "(":
        counter_l += 1
        for j in range(i + 1, n):
            if s[j] == ")" and j not in double_check:
                pairs += 1
                double_check.add(j)
                break
counter_r = n - counter_l
s = s + ")" * (counter_l - pairs)
s = "(" * (counter_r - pairs) + s

print(s)


n=int(input())
a=input()
s=list(a)
from copy import copy
ans=copy(s)
left=0
right=0
for i in range(n):
  if s[i]=="(":
    left+=1
  else:
    if left==0:
      right+=1
    else:
      left-=1
print("("*right+str(a)+")"*left)