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):
def main():

    S = list(input())
    checklist = [0 for i in range(26)]
    for i in S:
        checklist[ord(i) - ord("a")] += 1
    ans = True

    for i in checklist:
        if i > 1:
            ans = False

    if not ans:
        print(-1)
        return 0
    else:
        ans = False
        for i in range(len(checklist)):
            if checklist[i] == 0:
                for i in S:
                    print(i, end="")
                print(chr(i + ord("a")), end = "")
                print()
                ans = True
                break

        if not ans:
            new_S = []
            for i in S:
                new_S.append(ord(i))

            for i in range(len(new_S) - 1):
                if new_S[i] > new_S[i + 1]:
                    for j in range(i - 1):
                        print(S[j], end = "")
                    print(chr(new_S[i - 1] + 1), end = "")
                    print()
                    ans = True
                    break

            if not ans:
                print(-1)


def ABC069D():

    H, W = map(int, input().split())
    N = int(input())
    a = list(map(int, input().split()))
    ans = []
    for i in range(N):
        for j in range(a[i]):
            ans.append(i + 1)
    printlist = [[0 for i in range(W)] for j in range(H)]
    k = 0
    for i in range(H):
        for j in range(W):
            printlist[i][j] = ans[k]
            k += 1
        if i % 2 != 0:
            printlist[i] = printlist[i][::-1]

    for i in range(H):
        for j in range(W):
            print(printlist[i][j], end = "")
            if j != W:
                print(" ", end = "")
        print()
    print()


import math
def cc(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def ABC057D():

    N, A, B = map(int, input().split())
    v = list(map(int, input().split()))
    v = sorted(v)[::-1]

    anslist = []
    for i in range(A, B + 1):

        anslist.append([sum(v[0:i]) / i, i, v[i - 1]])
    anslist.sort()
    anslist = anslist[::-1]
    ans = anslist[0][0]
    key = anslist[0][2]
    long = anslist[0][1]
    print(ans)
    for i in range(1, len(anslist)):
        if anslist[i][0] == anslist[i - 1][0]:
            ans = anslist[i][0]
            key = anslist[i][2]
            long = anslist[i][1]
        else:
            break
    
    
    cnt = 0
    for i in v:
        if i == key:
            cnt += 1

    c = 0
    for i in v[:long]:
        
        if i == key:
            c += 1
    
    ans = 0
    if c == long:
        for i in range(A,  min(B + 1, cnt + 1)):
            ans += cc(cnt, i)
    else:
        ans = cc(cnt, c)
    
    
    print(ans)


def ABC104D():
    S = list(input())
    A_cnt = 0
    B_cnt = 0
    C_cnt = 0
    Q_cnt = 0
    ans = 0
    for i in S:
        if i == "A":
            A_cnt += 1
        elif i == "B":
            B_cnt += 1
        elif i == "C":
            C_cnt += 1
        else:
            Q_cnt += 1
    for i in range(Q_cnt + 1):
        for j in range(Q_cnt - i + 1):
            k = Q_cnt - i - j
            if A_cnt + i > 0 and B_cnt + j > 0 and C_cnt + k > 0:
                f_i = math.factorial(i)
                f_j = math.factorial(j)
                f_k = math.factorial(k)
                if f_i == 0:
                    f_i = 1
                if f_j == 0:
                    f_j = 1
                if f_k == 0:
                    f_k = 1
                ans += (A_cnt + i) * (B_cnt + j) * (C_cnt + k) * math.factorial(Q_cnt) // f_i // f_j // f_k
                print(ans, i, j, k, A_cnt + i, B_cnt + j, C_cnt + k)
                print(math.factorial(Q_cnt), f_i, f_j, f_k)
    print(ans)


def ARC082D():
    N = int(input())
    p = list(map(int, input().split()))
    cnt = 0
    if p[N - 1] == N:
        
        p[-2], p[-1] = p[-1], p[-2]
        cnt += 1

    for i in range(N - 1):
        if p[i] == i + 1:
            p[i], p[i + 1] = p[i + 1], p[i]
            cnt += 1
    print(cnt)


from queue import Queue
def ABC070D():
    N = int(input())
    a, b, c =map(int, input().split())
    Q, K = map(int, input().split())
    xy = [list(map(int, input().split())) for i in range(Q)]
    x = [[] for i in range(N)]
    for i, j in xy:
        x[i - 1].append(j - 1)
        x[j - 1].append(i - 1)

    q = Queue()
    visited = [0 for i in range(N)]

def ABC076D():
    N = int(input())
    t = list(map(int, input().split()))
    v = list(map(int, input().split()))
    speed_lim = [0]
    speed_list = [0 for i in range(sum(t) + 1)]
    for i in range(N):
        for j in range(t[i]):
            speed_lim.append(v[i])
    print(speed_lim)
    for i in range(1, sum(t) + 1):
        speed_list[i] = speed_list[i - 1] + 1
        if speed_list[i] > speed_lim[i]:
            speed_list[i] = speed_lim[i]
    print(speed_list)
    speed_list[-1] = 0
    for i in range(sum(t) - 1, -1, -1):
        speed_list[i] = min(speed_list[i + 1] + 1, speed_list[i])
        if speed_list[i] > speed_lim[i + 1]:
            speed_list[i] = speed_lim[i + 1]
    print(speed_list)
    ans = 0
    for i in speed_list:
        ans += i

    print(ans)


def ABC085D():
    N, H = map(int, input().split())
    ab = [list(map(int, input().split())) for i in range(N)]
    a = []
    b = []
    for i, j in ab:
        a.append(i)
        b.append(j)
    a.sort()
    b.sort()
    a = a[::-1]
    b = b[::-1]
    damage = 0
    cnt = 0
    for i in b:
        if i < a[0]:
            break
        damage += i
        cnt += 1
        if damage >= H:
            break
    key = 0
    if damage < H:
        key = (H - damage) / a[0]
        if int(key) != key:
            key += 1
        key = int(key)

    cnt += key

    print(cnt)


def ARC068D():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    count_list = []
    cnt = 1
    
    for i in range(1, N):
        if A[i] == A[i - 1]:
            cnt += 1
        else:
            count_list.append(cnt)
            cnt = 1
    count_list.append(cnt)
    ans_cnt = 0
    
    for i in range(len(count_list)):
        if count_list[i] > 2:
            ans_cnt += (count_list[i] % 2) - 1
            count_list[i] %= 2
            if count_list[i] == 0:
                count_list[i] = 2
    
    count_list = sorted(count_list)[::-1]
    for i in range(len(count_list) - 1):
        if count_list[i] == 2 and count_list[i + 1] == 2:
            ans_cnt += 1
            count_list[i] = 1
            count_list[i + 1] = 1
    count_list = sorted(count_list)[::-1]
    if count_list[0] == 2:
        count_list[0] = 0
    
    
    print(sum(count_list))


def ARC073D():
    N, W = map(int, input().split())
    wv = [list(map(int, input().split())) for i in range(N)]
    wv.sort()
    count_list = []
    cnt = 1
    weight_list = []
    s = 0
    g = 0
    for i in range(N - 1):
        if wv[i][0] != wv[i + 1][0]:
            g = i
            count_list.append(cnt)
            weight_list.append([wv[i][0], s, g, cnt])
            s = i + 1
            g = i + 1
            cnt = 1
        else:
            g = i
            cnt += 1

    count_list.append(cnt)
    weight_list.append([wv[-1][0], s, g, cnt])
    print(weight_list)
    wl = []
    for i in weight_list:
        this_weight = i[0]
        this_list = []
        for j in wv[i[1]:i[2] + 1]:
            this_list.append(j[1])
        this_list = sorted(this_list)[::-1]
        print(this_list)
        wl.append([this_weight, this_list])

def ARC081D():
    pattern = []
    N = int(input())
    S1 = list(input())
    S2 = list(input())
    i = 0
    while i < N:
        if S1[i] == S2[i]:
            pattern.append("X")
        else:
            pattern.append("Y")
            i += 1
        i += 1
    ans_list = []
    for i in range(len(pattern)):
        if i == 0:
            if pattern[i] == "X":
                ans_list.append(3)
            else:
                ans_list.append(6)
        else:
            if pattern[i] == "X":
                if pattern[i - 1] == "X":
                    ans_list.append(2)
                else:
                    ans_list.append(1)
            elif pattern[i] == "Y":
                if pattern[i - 1] == "X":
                    ans_list.append(2)
                elif pattern[i - 1] == "Y":
                    ans_list.append(3)
    
    
    ans = 1
    for i in ans_list:
        ans *= i
    print(ans % (1000000007))


def ARC090D():
    N, M = map(int, input().split())
    LRD = [list(map(int, input().split())) for i in range(M)]
    L = []
    R = []
    D = []
    LRD.sort()
    root = [[] for i in range(N)]
    for i, j, k in LRD:
        L.append(i)
        R.append(j)
        D.append(k)
        root[i - 1].append(j - 1)
    print(root)


def ABC073D():
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    ABC = [list(map(int, input().split())) for i in range(M)]
    root = [[1000000000 for i in range(N)] for j in range(N)]
    for i, j, k in ABC:
        root[i - 1][j - 1] = k
        root[j - 1][i - 1] = k

    import itertools
    def kumiawase(list_name):  
        return itertools.permutations(list_name)

    
     
      
       
        

    for i in range(N):
        for j in range(N):
            for k in range(N):
                if root[N - i - 1][N - j - 1] > root[N - i - 1][N - k - 1] + root[N - k - 1][N - j - 1]:
                    root[N - i - 1][N - j - 1] = root[N - i - 1][N - k - 1] + root[N - k- 1][N - j - 1]

    a = kumiawase(r)
    ans = float("inf")
    for i in a:
        key = 0
        for j in range(len(i) - 1):
            key += root[i[j] - 1][i[j + 1] - 1]
        if ans > key:
            ans = int(key)
    
    print(ans)


def ARC061D():
    H, W, N = map(int, input().split())
    ab = [list(map(int, input().split())) for i in range(N)]
    ab.sort()
    tmp_list = []
    ans_list = [0 for i in range(10)]
    for x, y, in ab:
        for i in range(x - 3, x):
            for j in range(y - 3, y):
                if 0 <= i < H - 2 and 0 <= j < W - 2:
                    
                    tmp_list.append([i, j])
    
    tmp_list.sort()
    temp = 1
    
    cnt = 0
    for i in range(1, len(tmp_list) + 1):
        if i != len(tmp_list):
            if tmp_list[i] == tmp_list[i - 1]:
                temp += 1
            else:
                ans_list[temp] += 1
                temp = 1
                cnt += 1
        else:
            ans_list[temp] += 1
            cnt += 1
    

    key = 0
    for i in range(len(ans_list)):
        key += i * ans_list[i]
    ans_list[0] = (H - 2) * (W - 2) - cnt
    
    

    for i in range(10):
        print(ans_list[i])


from scipy.sparse import csgraph


def ABC079D():
    H, W = map(int, input().split())
    c = [list(map(int, input().split())) for i in range(10)]
    A = [list(map(int, input().split())) for i in range(H)]
    
    for k in range(10):
        for i in range(10):
            for j in range(10):
                c[i][j] = min(c[i][j], c[i][k] + c[k][j])
    
    ans = 0
    for i in A:
        for j in i:
            if j != -1 and j != 1:
                ans += c[j][1]
                
    print(int(ans))


import fractions
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

def AGC028A():
    N, M = map(int, input().split())
    S = input()
    T = input()

    key = lcm(N, M)
    n = key // N
    m = key // M
    n_list = []
    for i in range(0, key, n):
        n_list.append(i)
    m_list = []
    for j in range(0, key, m):
        m_list.append(j)

    
    i = 0
    j = 0
    while True:
        if i >= len(n_list) or j >= len(m_list):
            break
        if i >= len(S) or j >= len(T):
            break
        if n_list[i] == m_list[j]:
            if S[i] != T[j]:
                print(-1)
                return 0
        if n_list[i] > m_list[j]:
            j += 1
        elif n_list[i] < m_list[j]:
            i += 1
        else:
            i += 1
            j += 1
    print(key)


import math
def AGC028B():
    N = int(input())

    A = list(map(int, input().split()))
    import copy
    a = copy.deepcopy(A)
    for i in range(1, N):
        A[i] += A[i - 1]
    ans = 0
    for i in range(1, N):
        key = A[i] * 2 - A[0] - (A[i] - A[i - 1])
        ans += math.factorial(N - i) * i * key
        
    print(ans)
    A = copy.deepcopy(a[::-1])
    for i in range(1, N):
        A[i] += A[i - 1]
    print(A)
    for i in range(1, N):
        key = A[i] * 2 - A[0] - (A[i] - A[i - 1])
        ans += math.factorial(N - i) * i * key
        
    ans += A[N - 1] * math.factorial(N - 1)

    print(ans)


def AGC028B2():
    N = int(input())

    A = list(map(int, input().split()))
    import copy
    a = copy.deepcopy(A)
    for i in range(1, N):
        A[i] += A[i - 1]
    ans = 0
    for i in range(1, N):
        A[i] = A[i] * (i + 1) - A[i - 1]
    for i in range(1, N):
        ans += math.factorial(N - i) * i * A[i - 1]

    print(ans)
    ans += A[N - 1] * N

    print(ans)


def CF18QBA():
    N = int(input())
    print(100 - 100 // N)


def CF18QBB():
    N, X = map(int, input().split())
    ab = [list(map(int, input().split())) for i in range(N)]
    key = ab[0][1]
    ans = 0
    for i, j in ab:
        if j > key:
            key = j
            key2 = i
        ans += i * j
    ans += key * X
    print(ans)


def CF18QBC():
    N = int(input())
    ans_list = [[0 for i in range(N)] for j in range(N)]
    key1 = 1
    key2 = key1
    for i in range(N):
        
        for j in range(N):
            if key2 == j:
                ans_list[i][j] = 1
                key2 += 5
        if key1 == 1:
            key1 = 3
        elif key1 == 3:
            key1 = 0
        elif key1 == 0:
            key1 = 2
        elif key1 == 2:
            key1 = 4
        elif key1 == 4:
            key1 = 1
        key2 = key1
    cnt = 0
    for i in range(N):
        for j in range(N):
            OK = 0
            if i > 0:
                if ans_list[i - 1][j] == 1:
                    OK = 1
            if i < N - 1:
                if ans_list[i + 1][j] == 1:
                    OK = 1
            if j > 0:
                if ans_list[i][j - 1] == 1:
                    OK = 1
            if j < N - 1:
                if ans_list[i][j + 1] == 1:
                    OK = 1
            if OK == 0:
                
                ans_list[i][j] = 1
                1

    for i in ans_list:
        for j in i:
            if j == 0:
                print(".", end = "")
            if j == 1:
                print("X", end = "")
                cnt += 1
        print()


def CF18QBE():
    N = int(input())
    ans = 10000
    tmp_list = []
    key = 69720375229712477164533808935312303556800
    for i in range(1, N + 1):
        tmp_list.append([key // i, i])
    ans = tmp_list[0][0]
    cnt = 0
    ans_list = []
    ans_list.append(["+", 1])
    key = []
    while True:
        if ans < 1 / N:
            print(1)
            break
        if cnt >= 320:
            print(2)
            break
        
        
        for i in range(len(tmp_list)):
            if tmp_list[i][0] < ans:
                key = tmp_list[i]
        if key:
            ans_list.append(["-", key[1]])
        if key:
            ans -= key[0]
        
        key = []
        cnt += 1
    
    print(len(ans_list))
    for i, j in ans_list:
        print(i, j)


def niconicoB():
    N, C = map(int, input().split())
    L = [int(input()) for i in range(N)]
    L.sort()
    cnt = 0
    while len(L) > 0:
        if len(L) == 1:
            cnt += 1
            break
        if L[-1] + L[0] + 1 <= C:
            cnt += 1
            del L[0]
            del L[-1]
        else:
            cnt += 1
            del L[-1]
    print(cnt)


def ABC064D():
    N = int(input())
    S = list(input())
    cnt = 0
    start = 0
    for i in S:
        if i == "(":
            cnt += 1
        elif i == ")":
            cnt -= 1
        if cnt < 0:
            start += 1
            cnt += 1
    tmp = []
    for i in range(start):
        tmp.append("(")
    S = tmp + S
    cnt_start = 0
    cnt_end = 0
    for i in S:
        if i == "(":
            cnt_start += 1
        elif i == ")":
            cnt_end += 1
    tmp = []
    for i in range(cnt_start - cnt_end):
        tmp.append(")")
    S = S + tmp

    for i in S:
        print(i, end = "")
    print()
ABC064D()

Solution (Python):
N = int(input())
s = input()
l = 0
t = 0
for v in s:
    if v == '(':
        t += 1
    else:
        t -= 1
        if t < 0:
            t = 0
            l += 1
if t > 0:
    s += ')' * t
print('(' * l + s)

Solution (Python):
N = int(input())
S = input()
R = S[::-1]

if S.count(")") == 0:
    print(S+")"*N)
    exit(0)
elif S.count("(") == 0:
    print("("*N+S)
    exit(0)

f = R.index(")")
g = S.index("(")

t = [0 for k in range(N)]
l = 0
for k in range(N-f):
    if S[k] == ")":
        l += 1
    else:
        l -= 1
    t[k] = l

s = [0 for k in range(N)]
m = 0
for k in range(len(S)-g):
    if S[-1-k] == "(":
        m += 1
    else:
        m -= 1
    s[k] = m

print("("*max(t)+S+")"*max(s))

Solution (Python):
n = int(input())
s = input()
cnt = 0
pre = 0
for i in range(n):
    if s[i] == "(":
        cnt += 1
    else:
        cnt -= 1
        if cnt < 0:
            pre = max(pre, -cnt)
s = "(" * pre + s
s = s + ")" * (cnt + pre)
print(s)

Solution (Python):
n = int(input())
s = list(input())
pl = 0
for i in range(n):
    if s[i] == "(":
        pl += 1
    elif pl >= 1:
        pl -= 1
if pl >= 0:
    s += [")"] * pl
pl = 0
for i in range(1, len(s)+1):
    if s[-i] == ")":
        pl += 1
    elif pl >= 1:
        pl -= 1
if pl >= 0:
    s.insert(0, "(" * pl)
print("".join(s))

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

pre = ''
post = ''

lp = 0
rp = 0

for c in s:
    if c == '(':
        lp += 1
    elif c == ')':
        if lp != 0:
            lp -= 1
        else:
            pre += '('
post = ')'*lp
ans = pre + s + post
print(ans)

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

left = 0
for i in s:
    if i == ")":
        left += 1
    else:
        break

left1 = 0
right1 = 0

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

left1 += left
for i in range(right1):
    s += ")"
for i in range(left1):
    s = "(" + s

print(s)

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

op1 = 0
l_lack = 0
for c in S:
    if c == '(':
        op1 += 1
    else:
        op1 -= 1
        l_lack = min(l_lack, op1)

op2 = 0
r_lack = 0
for c in S[::-1]:
    if c == ')':
        op2 += 1
    else:
        op2 -= 1
        r_lack = min(r_lack, op2)

print('(' * -l_lack + S + ')' * -r_lack)

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

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n = ni()
s = lc()

left = 0
right = 0

cnt = 0

for si in s:
    if si == "(":
        right += 1
        
    elif si == ")":
        right -= 1
        
    if right < 0:
        left += 1
        right = 0
        
print("("*left + "".join(s) + ")"*right)

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

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

l = []
r = []
for i in q:
    if i == ")":
        l.append("(")
    else:
        break

for i in q:
    if i == "(":
        r.append(")")

ans = l + list(S) + r
print("".join(map(str, ans)))

Solution (Python):
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


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


def ceil(a, b):
    return (a + b - 1) // b


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

    que = deque()
    for s in S:
        if len(que) == 0:
            que.append(s)
        elif que[-1] == "(" and s == ")":
            que.pop()
        else:
            que.append(s)

    d = defaultdict(int)
    while len(que):
        d[que[-1]] += 1
        que.pop()

    print("(" * d[")"] + S + ")" * d["("])


if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
a = input()
b = a

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

left = b.count(")")
right = b.count("(")
l = []
r = []

for i in range(left):
    l.append("(")

for j in range(right):
    r.append(")")

ans = ["".join(l), a, "".join(r)]
print("".join(ans))

Solution (Python):

n = input()
s = input()
num = 0
l = 0
for c in s:
    if c=="(":
        num += 1
    else:
        if num>0:
            num -= 1
        else:
            l += 1
r = num

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

Solution (Python):

N = int( input())
S = list( input())
X = [0]
now = S[0]
cnt = 0
for k in S:
    if k != now:
        X.append(cnt)
        now = k
    if k == '(':
        cnt += 1
    else:
        cnt -= 1
else:
    if X[-1] != cnt:
        X.append(cnt)
m = min(X)

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

if X[0] != 0:
    if X[0] <= X[1]:
        X[0] = 0
    else:
        X.insert(0,0)
if X[-1] != 0:
    if X[-2] <= X[-1]:
        X.append(0)
    else:
        X[-1] = 0
L = len(X)
up = 'up'
down = 'down'
updown = up

ans = ''
L = len(X)
for i in range(1,L):
    if updown == up:
        ans += '('*(X[i] - X[i-1])
        updown = down
    else:
        ans += ')'*(X[i-1] - X[i])
        updown = up
print(ans)

Solution (Python):
input()
s = input()
kakko =""
num =0
for c in s:
    if c=="(":
        num += 1
    elif num == 0:
        kakko += "("
    else:
        num -=1
print(kakko+s+(")"*num))

Solution (Python):
_ = int(input())
s = input()
a = lambda q: q.count('(')-q.count(')')

while True:
    flag = True
    for i in range(len(s)):
        if a(s[:i])<0:
            flag = False
            s = '(' + s
        elif a(s[:i])+a(s[i:])!=0:
            flag = False
            if a(s[:i]) > -a(s[i:]):
                s = s + ')'
            else:
                s = '(' + s
            break
    if flag:
        print(s)
        break

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

l = 0
r = 0

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

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

Solution (Python):
input()

t = ''
c = 0
stock = 0
for s in input():
    if s == ')':
        if c == 0:
            stock += 1
        else:
            t += ')'
            c -= 1
    else:
        if stock:
            t = '(' * stock + t + ')' * stock
            stock = 0
        c += 1
        t += '('
t = '(' * stock + t + ')' * stock + ')' * c
print(t)

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

right, left = 0, 0
for s in S:
    if s == '(':
        right += 1
    else:
        if right <= 0:
            left += 1
        else:
            right -= 1
print('(' * left + S + ')' * right)

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

count,left,right = 0, 0, 0
for i in s:
    if i == ")" and count != 0:
        count -= 1
        right -= 1
    elif i == ")" and count == 0:
        left += 1
    elif i == "(":
        count += 1
        right += 1
print("(" * left + s + ")" * right)

Solution (Python):
N = int(input())
S = input()
T = S
while '()' in T:
    T = T.replace('()', '')
print('(' * T.count(')') + S + ')' * T.count('('))

Solution (Python):
from collections import deque

n=int(input())
s=input()
q=deque([])
t=""

for i in s:
  if i=="(":
    q.append(i)
  else:
    if q:
      q.pop()
    else:
      t+="("
u=")"*len(q)
print(t+s+u)

Solution (Python):
import sys
import math
import collections
import itertools
import array
import inspect


sys.setrecursionlimit(1000000)



def chkprint(*args):
    names = {
        id(v): k
        for k, v in inspect.currentframe().f_back.f_locals.items()
    }
    print(', '.join(
        names.get(id(arg), '???') + ' = ' + repr(arg) for arg in args))



def to_bin(x):
    return bin(x)[2:]


def li_input():
    return [int(_) for _ in input().split()]


def gcd(n, m):
    if n % m == 0:
        return m
    else:
        return gcd(m, n % m)


def gcd_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = gcd(v, L[i])

    return v


def lcm(n, m):
    return (n * m) // gcd(n, m)


def lcm_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = lcm(v, L[i])

    return v



def wfs_d(D, N, K):
    """
    D: 隣接行列(距離付き)
    N: ノード数
    K: 始点ノード
    """

    dfk = [-1] * (N + 1)
    dfk[K] = 0

    cps = [(K, 0)]
    r = [False] * (N + 1)
    r[K] = True
    while len(cps) != 0:
        n_cps = []
        for cp, cd in cps:
            for i, dfcp in enumerate(D[cp]):
                if dfcp != -1 and not r[i]:
                    dfk[i] = cd + dfcp
                    n_cps.append((i, cd + dfcp))
                    r[i] = True

        cps = n_cps[:]

    return dfk



def dfs_d(v, pre, dist):
    """
    v:  現在のノード
    pre: １つ前のノード
    dist: 現在の距離

    以下は別途用意する
    D: 隣接リスト(行列ではない)
    D_dfs_d: dfs_d関数で用いる，始点ノードから見た距離リスト
    """

    global D
    global D_dfs_d

    D_dfs_d[v] = dist

    for next_v, d in D[v]:
        if next_v != pre:
            dfs_d(next_v, v, dist + d)

    return


def sigma(N):
    ans = 0
    for i in range(1, N + 1):
        ans += i
    return ans


class Combination:
    def __init__(self, n, mod):

        g1 = [1, 1]
        g2 = [1, 1]
        inverse = [0, 1]
        for i in range(2, n + 1):
            g1.append((g1[-1] * i) % mod)
            inverse.append((-inverse[mod % i] * (mod // i)) % mod)
            g2.append((g2[-1] * inverse[-1]) % mod)
        self.MOD = mod
        self.N = n
        self.g1 = g1
        self.g2 = g2
        self.inverse = inverse

    def __call__(self, n, r):
        if (r < 0 or r > n):
            return 0
        r = min(r, n - r)
        return self.g1[n] * self.g2[r] * self.g2[n - r] % self.MOD




dp = None


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

    open, close = 0, 0

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

    print("(" * close + S + ")" * open)


main()

Solution (Python):
n = int(input())
s = input()
try:
  migi = s.count("(")
except:
  migi = 0
try:
  hidari = s.count(")")
except:
  hidari = 0
kasa = 0
ans = 0
for i in range(n):
  if s[i] == "(":
    kasa += 1
  else:
    if kasa >= 1:
      ans += 1
      kasa -= 1
migi -= ans
hidari -= ans
print("(" * hidari + s + ")"* migi)

Solution (Python):

n = int(input())

s = list(raw_input())
stk = []

i = 0
while i<len(s):
	if s[i] == ')' and not stk:
		s.insert(0,"(")
		i += 1

	if s[i] == ')' and  stk:
		stk.pop()

	if s[i] == '(':
		stk.append('(')
	i += 1

for i in range(len(stk)):
	stk[i] = ')'

print ''.join(s) + ''.join(stk)

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

cnt = 0
ans = ''
for ch in S:
    if ch == '(':
        cnt = cnt + 1
    if ch == ')':
        cnt = cnt - 1
        
    if cnt == -1:
        cnt = 0
        ans = '(' + ans

    ans = ans + ch


while cnt:
    cnt = cnt - 1
    ans = ans + ')'

print (ans)

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_s(): return list(input().split())

N = int(input())
S = input()
tmp = 0
MIN = 0
for s in S:
	if s == '(':
		tmp += 1
	else:
		tmp -= 1
	MIN = min(tmp,MIN)

ans1 = ''
if MIN < 0:
	for i in range(-MIN):
		ans1 = ans1 + '('

ans2 = ''
tmp -= MIN
if tmp > 0:
	for i in range(tmp):
	 	ans2 = ans2 + ')'

print(ans1+S+ans2)

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

level=[0]
for c in S:
	if c=='(':
		level.append(level[-1] + 1)
	else:
		level.append(level[-1] - 1)
numL = min(level)*(-1)
numR = numL + level[-1]
S    = "(" * numL + S + ")" * numR




print(S)

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

ans = s
n_left, n_right = 0, 0
for ss in s:
    if ss == '(':
        n_left += 1
    else:
        if n_left > 0:
            n_left -= 1
        else:
            ans = '('+ans
if n_left > 0:
    for _ in range(n_left): ans += ')'

print(ans)