Problem:


Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:  

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))



Sample input:
3
())


Sample output:
(())

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
c = 0
d = 0
for i in range(n):
    if s[i] == '(':
        c += 1
    else:
        d += 1
used_c = [False]*n
used_d = [False]*n
for i in range(n):
    if s[i] == '(':
        for j in range(i+1, n):
            if s[j] == ')' and not used_c[j]:
                c -= 1
                used_c[j] = True
    if s[i] == ')':
        for j in range(i):
            if s[j] == '(' and not used_d[j]:
                d -= 1
                used_d[j] = True
print('('*d+s+')'*c)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
c = 0
d = 0
for i in range(n):
    if s[i] == ')':
        c += 1
    else:
        d += 1

for i in range(n):
    if s[i] == '(':
        for j in range(i+1, n):
            if s[j] == ')':
                c -= 1
    if s[i] == ')':
        for j in range(i):
            if s[j] == '(':
                d -= 1
print('('*c+s+')'*d)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
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

print('(' * count, end='')
print(*S, sep='', end='')
print(')' * b)

Submission status: Wrong Answer

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n = int(input())
    S = input()
    # parenthness
    # 完成したらくっつけるようにするかや～～
    k = 0
    v = 0
    ans = ""
    i = 0
    nya = 0
    p = ""
    while i < n:
        if k != 0 and v == 0 and S[i] == '(':
            for l in range(k):
                ans += '('
            ans += S[:i]
            #print('?',ans)
            k = 0
            nya = i
            continue
        # if v != 0 and k == 0 and S[i] == ')':
        #     ans += S[nya:i]
        #     #print('!',ans)
        #     for r in range(v):
        #         ans += ')'
        #     v = 0
        #     continue
        if S[i] == ')':
            if v == 0:
                k += 1
            else:
                v -= 1
        elif S[i] == '(':
            if k == 0:
                v += 1
            else:
                k -= 1
        i += 1
    #print(k,v)
    for j in range(k):
        p += '('
    ans += S[nya:]
    for j in range(v):
        ans += ')'
    print(p+ans)

if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n = int(input())
    S = input()
    # parenthness
    # 完成したらくっつけるようにするかや～～
    k = 0
    v = 0
    ans = ""
    i = 0
    nya = 0
    while i < n:
        if k != 0 and v == 0 and S[i] == '(':
            for l in range(k):
                ans += '('
            ans += S[:i]
            #print('?',ans)
            k = 0
            nya = i
            continue
        # if v != 0 and k == 0 and S[i] == ')':
        #     ans += S[nya:i]
        #     #print('!',ans)
        #     for r in range(v):
        #         ans += ')'
        #     v = 0
        #     continue
        if S[i] == ')':
            if v == 0:
                k += 1
            else:
                v -= 1
        elif S[i] == '(':
            if k == 0:
                v += 1
            else:
                k -= 1
        i += 1
    #print(k,v)
    for j in range(k):
        ans += '('
    ans += S[nya:]
    for j in range(v):
        ans += ')'
    print(ans)

if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input().split(")(")
l = ""
ans = ""
for i in range(len(s)):
    if len(s) != 1:
        if i % 2 == 0: s[i] += ")"
        else: s[i] = "(" + s[i]
    R = s[i].count(")")
    L = s[i].count("(")
    if R < L: ans += s[i] +  ")" * (L-R)
    elif L < R: ans += "(" * (R-L) + s[i]
    else: ans += s[i]
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
t = 0
ss = 0
ee = 0

if s[0] == ')' or s[-1] == '(':
    for i in range(n):
        if s[i] == ')':
            ss += 1
        else:
            break
    st = s[::-1]
    for i in range(n):
        if st[i] == '(':
            ee += 1
        else:
            break

for i in range(n):
    if s[i] == '(':
        t += 1
    else:
        t -= 1
t -= (ee-ss)
if t >= 0:
    tail = ')'*(t)
    ans = s+tail
else:
    head = '('*(-t)
    ans = head+s
print('('*ss+ans+')'*ee)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input().split(")(")
l = ""
ans = ""
for i in range(len(s)):
    if len(s) != 1:
        if i % 2 == 0: s[i] += ")"
        else: s[i] = "(" + s[i]
    R = s[i].count(")")
    L = s[i].count("(")
    if R < L: ans += s[i] +  ")" * (L-R)
    elif L < R: 
        ans += s[i]
        l += "(" * (R-L)
    else: ans += s[i]
print(l + ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input().split(")(")
l = ""
r = ""
for i in range(len(s)):
    if len(s) != 1:
        if i % 2 == 0: s[i] += ")"
        else: s[i] = "(" + s[i]
    R = s[i].count(")")
    L = s[i].count("(")
    if R < L: r += ")" * (L-R)
    elif L < R: l += "(" * (R-L)
print(l + "".join(s) + r)

Submission status: Wrong Answer

Solution code:
from collections import Counter
n = int(input())
s = input().split(")(")
l = ""
r = ""
for i in range(len(s)):
    if len(s) != 1:
        if i % 2 == 0: s[i] += ")"
        else: s[i] = "(" + s[i]
    a = Counter(s[i])
    if "(" not in a: l += "(" * a[")"]
    elif a[")"] > a["("]: l += "(" * (a[")"] - a["("])
    elif a["("] > a[")"]: r += ")" * (a["("] - a[")"])
print(l + "".join(s) + r)

Submission status: Wrong Answer

Solution code:
a = int(input())
s= input()
c = [0,0]
ch = ['(',')']
l =[0]
t = 0
ans = 0 
R = 0
for i,j in zip(s,s[1:]+'s'):
  if i == ch[0]:
    R+=1
  else:
    ans+=1
    ans-=R
    R = 0
S = s[::-1]
Ans = 0 
R = 0
for i,j in zip(S,S[1:]+'s'):
  if i == ch[1]:
    R+=1
  else:
    Ans+=1
    Ans-=R
    R = 0
#     R = 0
# for i,j in zip(s,s[1:]+'s'):
#   if i == j:
#     t+=1
#   elif i == ch[0]:
#     ans += l[-]
#     l.append(t+1)
#     t =0
#   else:
#     l.append(-1*(t+1))
#     t= 0

print(ch[0]*ans+s+ch[1]*Ans)

Submission status: Wrong Answer

Solution code:
a = int(input())
s= input()
c = [0,0]
ch = ['(',')']
l =[0]
t = 0
ans = 0 
R = 0
for i,j in zip(s,s[1:]+'s'):
  if i == ch[0]:
    R+=1
  else:
    ans+=1
    ans-=R
    R = 0
# S = s[::-1]
# Ans = 0 
# R = 0
# for i,j in zip(S,S[1:]+'s'):
#   if i == ch[0]:
#     R+=1
#   else:
#     Ans+=1
#     Ans-=R
#     R = 0
#     R = 0
# for i,j in zip(s,s[1:]+'s'):
#   if i == j:
#     t+=1
#   elif i == ch[0]:
#     ans += l[-]
#     l.append(t+1)
#     t =0
#   else:
#     l.append(-1*(t+1))
#     t= 0

print(ch[0]*ans+s+ch[1]*R)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
t = 0
ss = 0
ee = 0

if s[0] == ')' and s[-1] == '(':
    for i in range(n):
        if s[i] == ')':
            ss += 1
        else:
            break
    st = s[::-1]
    for i in range(n):
        if st[i] == '(':
            ee += 1
        else:
            break

for i in range(n):
    if s[i] == '(':
        t += 1
    else:
        t -= 1
t -= (ee-ss)
if t >= 0:
    tail = ')'*(t)
    ans = s+tail
else:
    head = '('*(-t)
    ans = head+s
print('('*ss+ans+')'*ee)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
t = 0
ss = 0
ee = 0

if s[0] == ')' and s[-1] == '(':
    for i in range(n):
        if s[i] == ')':
            ss += 1
        else:
            break
    st = s[::-1]
    for i in range(n):
        if st[i] == '(':
            ee += 1
        else:
            break

for i in range(n):
    if s[i] == '(':
        t += 1
    else:
        t -= 1
if t >= 0:
    tail = ')'*(t)
    ans = s+tail
else:
    head = '('*(-t)
    ans = head+s
print('('*ss+ans+')'*ee)

Submission status: Wrong Answer

Solution code:
# 解説解法

# ちゃんとした括弧列 s=(s1,...,sn):
# - '('と')'の個数は等しい
# - 任意のprefixにおいて，'('の個数 >= ')'の個数 (これがないと閉じない)
#
# di = (s1,...,si)の '('の個数 - ')'の個数
# x = min(d1, ..., dn)
# 
# '('を1つ入れる → dnは1増える xは0 or 1増える (場所による)
# ')'を1つ入れる → dnは1減る xは0 or 1減る (場所による)
#
# 2つの値(a=dn, b=x)を管理する
#
# 4つの操作を考える
#  [a] a += 1
#  [b] a += 1, b += 1
#  [c] a -= 1
#  [d] a -= 1, b -= 1
#
# - b <= 0 から b == 0にしないといけないので，[b]を-b回行う (dはムダなのでやらない)
# - aの値が a + bになっている， a >= bよりa >= 0
# - 次にaを0にしたい．そのため，cを a + b回やる
# - つまり挿入回数は a - 2b = dn - x 回数未満
#
# 構成法
# - 一番左に '(' を -x 回
# - 一番右に ')' を dn - x回

n = int(input())
s = list(input())
d = []
co, cc = 0, 0
for ch in s:
    if ch == '(':
        co += 1
    elif ch == ')':
        cc += 1
    d.append(co - cc)

# 計算
x = min(d)

str_left = '(' * (-x)
str_right = ')' * (d[-1] - x)

print("{}{}{}".format(str_left, "".join(s), str_right))

Submission status: Wrong Answer

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

a = 0
b = 0
aa = []
for i in range(n-1):
    if s[i] == "(":
        a += 1
        
    elif s[i] == ")" and s[i+1] == "(":
        b += 1
        aa.append((a,b))
        a,b = 0,0
        
    else:
        b += 1
        
if s[n-1] == "(":
    a += 1
else:
    b += 1
aa.append((a,b))

ans = ""
for i in aa:
    bb = max(i)
    ans = ans + "("*bb + ")"*bb
    
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
left = 0
right = 0
cnt1 = 0
for i in S:
    if i == '(':
        left += 1
    else:
        right += 1
    cnt1 = max(cnt1, right - left)
cnt2 = 0
for i in S[::-1]:
    if i == ')':
        left += 1
    else:
        right += 1
    cnt2 = max(cnt2, right - left)
ans = '(' * max(0, cnt1) + S + ')' * max(0, cnt2)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
nl = 0
nr = 0
for i in S:
    if i == ')':
        if nr > 0:
            nr -= 1
        else:
            nl += 1
    else:
        nr += 1
print(nr)
print(nl)
print('('*nl + S + ')'*nr)

Submission status: Wrong Answer

Solution code:
# =map(int,input().split())
n=int(input())
a=input()
cnt_1=0
cnt_2=0
ans_1=0
ans_2=0
merter=1
for i in range(n):
    if (i==0)and(a[i]=='('):
        cnt_1+=1
        merter=1
    elif (i==0)and(a[i]==')'):
        cnt_2+=1
        merter=-1
    elif (i>0)and(a[i]=='(')and(a[i-1]=='('):
        cnt_1+=1
    elif (i>0)and(a[i-1]=='(')and(a[i]==')'):
        cnt_2+=1
    elif (i>0)and(a[i]==')')and(a[i-1]==')'):
        cnt_2+=1
        # print('1',cnt_1)
        # print('2',cnt_2)
    elif (i>0)and(a[i-1]==')')and(a[i]=='('):
        if merter==-1:
            ans_2+=cnt_2
            cnt_2=0
            cnt_1=1
            merter=1
            # print(ans_2)
        else:
            if cnt_2>cnt_1:
                ans_2+=(cnt_2-cnt_1)
                cnt_1=1
                cnt_2=0
                merter=1
            elif cnt_1>cnt_2:
                ans_1+=(cnt_1-cnt_2)
                cnt_1=1
                cnt_2=0
                merter=1
            else:
                cnt_1=1
                cnt_2=0
                merter=1
    if i==n-1:
        if merter==(-1):
            if a[i]==')':
                ans_2+=cnt_2
        else:
            if a[i]=='(':
                ans_1+=cnt_1
            else:
                if cnt_2>cnt_1:
                    # print(cnt_1)
                    # print(cnt_2)
                    # print(ans_2)
                    ans_2+=(cnt_2-cnt_1)
                elif cnt_1>cnt_2:
                    ans_1+=(cnt_1-cnt_2)
ans=('('*ans_2)+(a)+(')'*ans_1)
# print(ans_1)
# print(ans_2)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys


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


sys.setrecursionlimit(10 ** 9)


def main():
    N = int(input())
    S = list(input())
    answer = ""
    cnt = 0
    for s in S:
        if s == "(":
            cnt += 1
            answer += "("
        else:
            if cnt > 0:
                answer += ")"
                cnt -= 1
            else:
                answer += "()"
    if cnt > 0:
        answer += ")" * cnt
    print(answer)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
T = deque(S[:])
ins = []
pointer = 0
a = 0
for i in range(N-1):
  if S[i] == ')':
    if pointer == 1:
      pointer -= 1
    else:
      T.appendleft('(')
  
a = 0
b = 0
for t in T:
  if t == ')':
    b += 1
  else:
    a += 1

for i in range(max(a-b, 0)):
  T.append(')')
print(''.join(T))

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
T = deque(S[:])
ins = []
for i in range(N-1):
  if not (S[i]=='(' and S[i+1]==')'):
    if S[i] == '(':
      T.append(')')
    else:
      T.appendleft('(')
if S[N-1] == '(':
  T.append(')')

print(''.join(T))

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
S = list(input())
T = deque(S[:])
ins = []
for i in range(N-1):
  if not (S[i]=='(' and S[i+1]==')'):
    if S[i] == '(':
      T.append(')')
    else:
      T.appendleft('(')

print(''.join(T))

Submission status: Wrong Answer

Solution code:
import copy
n = int(input())
list_S = list(input())
list_N = list()
d = 0

for i in range(n-1):

    if list_S[i] == ")" and list_S[i+1] == "(":
        list_N.append(list_S[d:i+1])
        d = i + 1

    if i + 1 == n - 1:
        list_N.append(list_S[d:n])

if n == 1:
    list_N.append(list_S)

list_ANS = copy.deepcopy(list_N)

for l in list_N:

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

    if left - right > 0:
        for _ in range(left-right):
            list_ANS[-1].append(")")

    if right - left > 0:
        for _ in range(right-left):
            list_ANS[0].insert(0, "(")


ans = str()

for l in list_ANS:
    ans += "".join(l)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
list_S = list(input())
list_N = list()
d = 0

for i in range(n-1):

    if list_S[i] == ")" and list_S[i+1] == "(":
        list_N.append(list_S[d:i+1])
        d = i + 1

    if i + 1 == n - 1:
        list_N.append(list_S[d:n])

if n == 1:
    list_N.append(list_S)


for l in list_N:

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

    if left - right > 0:
        for _ in range(left-right):
            list_N[-1].append(")")

    if right - left > 0:
        for _ in range(right-left):
            list_N[0].insert(0, "(")


ans = str()

for l in list_N:
    ans += "".join(l)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
list_S = list(input())
list_N = list()
d = 0

for i in range(n-1):

    if list_S[i] == ")" and list_S[i+1] == "(":
        list_N.append(list_S[d:i+1])
        d = i + 1

    if i + 1 == n - 1:
        list_N.append(list_S[d:n])

for l in list_N:

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

    if left - right > 0:
        for _ in range(left-right):
            list_N[-1].append(")")

    if right - left > 0:
        for _ in range(right-left):
            list_N[0].insert(0, "(")

ans = str()

for l in list_N:
    ans += "".join(l)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
l = 0
r = 0
lp = 0
rp = 0
for i in range(len(s)):
    if s[i] == '(':
        if r != 0:
            if r > l:
                lp += r-l
            elif l > r:
                rp += l-r
            l, r = 0, 0
        l += 1
    if s[i] == ')':
        r += 1

if r > l:
    lp += r-l
elif l > r:
    rp += l-r
print('('*lp+s+')'*rp)

Submission status: Wrong Answer

Solution code:
n = int(input())
list_S = list(input())
list_N = list()
d = 0

for i in range(n-1):

    if list_S[i] == ")" and list_S[i+1] == "(":
        list_N.append(list_S[d:i+1])
        d = i + 1

    if i + 1 == n - 1:
        list_N.append(list_S[d:n])

for l in list_N:

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

    if left - right > 0:
        for _ in range(left-right):
            l.append(")")

    if right - left > 0:
        for _ in range(right-left):
            l.insert(0, "(")

if len(list_N) != 1:

    if len(list_N[0]) == 2:
        list_N[0].insert(0, "(")
    else:
        list_N[0].pop(-1)

    if len(list_N[-1]) == 2:
        list_N[-1].append(")")
    else:
        list_N[-1].pop(0)

ans = str()

for l in list_N:
    ans += "".join(l)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
leng = []
cnt = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        cnt += 1
    else:
        leng.append([s[i], cnt])
        cnt = 1
if s[-1] == "(":
    leng.append(["(", cnt])
else:
    leng.append([")", cnt])
if s[0] == ")":
    leng.insert(0,["(", leng[0][1]])
if s[-1] == "(":
    leng.insert(len(leng),[")", leng[-1][1]])

leng2 = []
for i in range(0, len(leng), 2):
    l = leng[i]
    r = leng[i+1]
    if l[1] == r[1]:
        pass
    elif l[1] < r[1]:
        leng2.append([")",r[1]-l[1]])
    else:
        leng2.append(["(", l[1]-r[1]])

lc = 0
rc = 0
while leng2:
    if leng2[0][0] == ")":
        leng[0][1] += leng2[0][1]
        u = leng2.pop(0)
    else:
        break
while leng2:
    if leng2[-1][0] == "(":
        leng[-1][1] += leng2[-1][1]
        u = leng2.pop()
    else:
        break

lc = 0
rc = 0
for i in range(len(leng2)):
    tar = leng2[i]
    if tar[0] == "(":
        lc += tar[1]
    else:
        rc += tar[1]
if lc > rc:
    leng[-1][1] += lc-rc
elif lc < rc:
    leng[0][1] += rc-lc

ans = []
for i in range(len(leng)):
    tar = leng[i]
    for j in range(tar[1]):
        ans.append(tar[0])
print("".join(ans))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
leng = []
cnt = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        cnt += 1
    else:
        leng.append([s[i], cnt])
        cnt = 1
if s[-1] == "(":
    leng.append(["(", cnt])
else:
    leng.append([")", cnt])
if s[0] == ")":
    leng.insert(0,["(", leng[0][1]])
if s[-1] == "(":
    leng.insert(len(leng),[")", leng[-1][1]])

lc = 0
rc = 0
for i in range(0, len(leng), 2):
    l = leng[i]
    r = leng[i+1]
    if l[1] == r[1]:
        pass
    elif l[1] < r[1]:
        lc += r[1]-l[1]
    else:
        rc += l[1] - r[1]

if lc == rc:
    pass
elif lc > rc:
    leng[0][1] += lc -rc
else:
    leng[-1][1] += rc -lc

ans = []
for i in range(len(leng)):
    tar = leng[i]
    for j in range(tar[1]):
        ans.append(tar[0])
print("".join(ans))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
leng = []
cnt = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        cnt += 1
    else:
        leng.append([s[i], cnt])
        cnt = 1
if s[-1] == "(":
    leng.append(["(", cnt])
else:
    leng.append([")", cnt])
if s[0] == ")":
    leng.insert(0,["(", leng[0][1]])
if s[-1] == "(":
    leng.insert(len(leng),[")", leng[-1][1]])

lc = 0
rc = 0
for i in range(0, len(leng), 2):
    l = leng[i]
    r = leng[i+1]
    if l[1] == r[1]:
        pass
    elif l[1] < r[1]:
        lc += r[1]-l[1]
    else:
        rc += l[1] - r[1]

leng[0][1] += lc
leng[-1][1] += rc

ans = []
for i in range(len(leng)):
    tar = leng[i]
    for j in range(tar[1]):
        ans.append(tar[0])
print("".join(ans))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
leng = []
cnt = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        cnt += 1
    else:
        leng.append([s[i], cnt])
        cnt = 1
if s[-1] == "(":
    leng.append(["(", cnt])
else:
    leng.append([")", cnt])
if s[0] == ")":
    leng.insert(0,["(", leng[0][1]])
if s[-1] == "(":
    leng.insert(len(leng),[")", leng[-1][1]])

for i in range(0, len(leng), 2):
    l = leng[i]
    r = leng[i+1]
    if l[1] == r[1]:
        pass
    elif l[1] < r[1]:
        leng[0][1] += r[1]-l[1]
    else:
        leng[-1][1] += l[1]-r[1]
ans = []
for i in range(len(leng)):
    tar = leng[i]
    for j in range(tar[1]):
        ans.append(tar[0])
print("".join(ans))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = list(input())
leng = []
cnt = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        cnt += 1
    else:
        leng.append([s[i], cnt])
        cnt = 1
if s[-1] == "(":
    leng.append(["(", cnt])
else:
    leng.append([")", cnt])
if s[0] == ")":
    leng.insert(0,["(", leng[0][1]])
if s[-1] == "(":
    leng.insert(len(leng),[")", leng[-1][1]])
print(leng)

for i in range(0, len(leng), 2):
    l = leng[i]
    r = leng[i+1]
    if l[1] == r[1]:
        pass
    elif l[1] < r[1]:
        leng[0][1] += r[1]-l[1]
    else:
        leng[-1][1] += l[1]-r[1]
ans = []
for i in range(len(leng)):
    tar = leng[i]
    for j in range(tar[1]):
        ans.append(tar[0])
print("".join(ans))

Submission status: Wrong Answer

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

L = [0] * N
R = [0] * N
for i, s in enumerate(S):
    L[i] += L[i - 1]
    if s == '(':
        L[i] += 1
for i, s in enumerate(S[::-1]):
    R[i] += R[i - 1]
    if s == ')':
        R[i] += 1
R = R[::-1]

l, r = 0, 0
for i in range(N):
    l = max(l, R[i] - L[i])
    r = max(r, L[i] - R[i])

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

Submission status: Wrong Answer

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

T = []
while S and S[-1] == '(':
    T.append(S.pop())
S = S[::-1]
T = T + [')'] * len(T)

H = []
while S and S[-1] == ')':
    H.append(S.pop())
S = S[::-1]
H = ['('] * len(H) + H

l = S.count('(')
r = S.count(')')
d = l - r

S = H + S + T

if d > 0:
    S = S + [')'] * d
if d < 0:
    S = ['('] * (-d) + S

print(''.join(S))

Submission status: Wrong Answer

Solution code:
n, s = int(input()), input()
t = s.lstrip(")").rstrip("(")
a, b = map(t.count, "()")
x, y = map(s.count, "()")
x -= a
y -= b
if a>b:
        a -= b
        b = 0
else:
        b -= a
        a = 0
print("("*(b+y) + s + ")"*(a+x))

Submission status: Wrong Answer

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

T = []
while S and S[-1] == '(':
    T.append(')')
    S.pop()
T = ['('] * len(T) + T

S = ''.join(S + T)

l = S.count('(')
r = S.count(')')
d = l - r

if d > 0:
    S = S + ')' * d
if d < 0:
    S = '(' * abs(d) + S

print(S)

Submission status: Wrong Answer

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

ans = []
while S and S[-1] == '(':
    ans.append(')')
    S.pop()
ans = '(' * len(ans) + ''.join(ans)

cnt = 0
for s in S[::-1]:
    if s == ')':
        cnt += 1
    else:
        cnt -= 1

if cnt > 0:
    ans = '(' * cnt + ''.join(S) + ans
if cnt < 0:
    ans = ''.join(S) + ans + ')' * cnt

print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=input()
i=0
flag=1#1なら(,-1なら)が来てて欲しい
rcnt=0
lcnt=0
ns=S
while i<N:
    if (flag==1)and(S[i]=="("):
        lcnt=lcnt+1
    elif (flag==1)and(S[i]==")"):
        rcnt=rcnt+1
        flag=-1
    elif (flag==-1)and(S[i]==")"):
        rcnt=rcnt+1
    elif (flag==-1)and(S[i]=="("):
        flag=1
        i=i-1
        if rcnt>lcnt:
            for k in range(rcnt-lcnt):
                ns="".join(("(",ns))
        elif rcnt<lcnt:
            for k in range(lcnt-rcnt):
                ns="".join((ns,")"))
        rcnt=0
        lcnt=0
    i=i+1
    #print(ns,lcnt,rcnt,flag)
    #input()
if rcnt>lcnt:
    for k in range(rcnt - lcnt):
        ns = "".join(("(", ns))
elif rcnt<lcnt:
    for k in range(lcnt - rcnt):
        ns = "".join((ns, ")"))
print(ns)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = input()
a = '('
b = ')'

i = 0
X = []
cnt = 0
for s in S:
    if i == 0:
        if s == a:
            cnt += 1
        else:
            i ^= 1
            cnt -= 1
    else:
        if s == b:
            cnt -= 1
        else:
            i ^= 1
            X.append(cnt)
            cnt = 1
else:
    X.append(cnt)

for x in X:
    if x < 0:
        S = '(' * abs(x) + S
    elif x > 0:
        S = S + ')' * abs(x)

print(S)

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    n = int(input())
    s = list(input())

    stack = []
    last = []
    ans = deque([])
    for c in s:
        if c == '(':
            stack.append('(')
        else:
            if stack==[]:
                ans.appendleft('(')
                ans.append(')')
            else:
                while(stack!=[]):
                    ans.append(stack.pop())
                    last.append(')')
                last.pop()
                ans.append(')')
                
    ans.extend(stack)
    for c in stack:
        ans.append(')')
    ans.extend(last)

    for c in ans:
        print(c,end="")
    print()

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    n = int(input())
    s = list(input())

    stack = []
    ans = deque([])
    for c in s:
        if c == '(':
            stack.append('(')
        else:
            if stack==[]:
                ans.appendleft('(')
                ans.append(')')
            else:
                t = 0
                while(stack!=[]):
                    ans.append(stack.pop())
                    t+=1
                for _ in [0]*t:
                    ans.append(')')

    t = deque([])
    for _ in stack:
        t.appendleft('(')
        t.append(')')

    for c in ans:
        print(c,end="")
    for c in t:
        print(c,end="")
    print()

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    n = int(input())
    s = list(input())

    stack = []
    ans = deque([])
    for c in s:
        if c == '(':
            stack.append('(')
        else:
            if stack==[]:
                ans.appendleft('(')
                ans.append(')')
            else:
                stack.pop()
                ans.append('()')
    
    t = deque([])
    for _ in stack:
        t.appendleft('(')
        t.append(')')

    for c in ans:
        print(c,end="")
    for c in t:
        print(c,end="")
    print()

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
a = []

count = 1
for i in range(n-1):
    if (s[i] == s[i+1]):
        count += 1
    else:
        a.append(count)
        count = 1
a.append(count)

ans = s
if (s[0] == "("):
    if(s[-1] == ")"):
        for i in range(0,len(a)//2):
            if (a[2*i] > a[2*i+1]):
                ans = ans + ")" * (a[2*i] - a[2*i+1])
            elif (a[2*i] < a[2*i+1]):
                ans = "(" * (a[2*i+1]-a[2*i]) + ans
    else:
        for i in range(0,len(a)//2):
            if (a[2*i] > a[2*i+1]):
                ans = ans + ")" * (a[2*i] - a[2*i+1])
            elif (a[2*i] < a[2*i+1]):
                ans = "(" * (a[2*i+1]-a[2*i]) + ans
        ans = ans + ")" * a[-1] 
else:
    ans = "(" * a[0] + ans
    if(s[-1] == ")"):
        for i in range(0,len(a)//2):
            if (a[2*i+1] > a[2*i+2]):
                ans = ans + ")" * (a[2*i+1] - a[2*i+2])
            elif (a[2*i+1] < a[2*i+2]):
                ans = "(" * (a[2*i+2]-a[2*i+1]) + ans
    else:
        for i in range(0,len(a)//2-1):
            if (a[2*i+1] > a[2*i+2]):
                ans = ans + ")" * (a[2*i+1] - a[2*i+2])
            elif (a[2*i+1] < a[2*i+2]):
                ans = "(" * (a[2*i+2]-a[2*i+1]) + ans
        ans = ans + ")" * a[-1]   

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = input()
a = []

count = 1
for i in range(n-1):
    if (s[i] == s[i+1]):
        count += 1
    else:
        a.append(count)
        count = 1
a.append(count)
b = []
if (s[0] == "("):
    if(s[-1] == ")"):
        for i in range(0,len(a)//2):
            b.append(max(a[2*i],a[2*i+1]))
    else:
        for i in range(0,len(a)//2):
            b.append(max(a[2*i],a[2*i+1]))
        b.append(a[-1])   
else:
    b.append(a[0])
    if(s[-1] == ")"):
        for i in range(0,len(a)//2):
            b.append(max(a[2*i+1],a[2*i+2]))
    else:
        for i in range(0,len(a)//2-1):
            b.append(max(a[2*i+1],a[2*i+2]))
        b.append(a[-1])    
ans = ""
for i in range(len(b)):
    ans = ans + "(" * b[i] + ")" * b[i]
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
n = int(input()) # 入力が1つ
# map(int, input().split()) # 入力が複数
s = list(input())
que = deque()
done = deque()
i = 0
while i < n:
    t = s[i]
    if t == '(':
        if i + 1 < n and s[i + 1] == ')':
            que.append(t)
            i += 1
        else:
            c = i
            while i + 1 < n and s[i + 1] == '(':
                i += 1
            i += 1
            que.append('(' * (i - c))
            que.append(')' * (i - c))
    elif que and que[-1] == '(':
        que.append(t)
        i += 1
        
    else:
        que.appendleft('(')
        que.append(t)
        i += 1

print(''.join(que))

Submission status: Wrong Answer

Solution code:
import sys
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

N = ii()
S = input()

pos = 0
r_cnt = 0

while pos < N and S[pos]==')':
    r_cnt += 1
    pos += 1

l_cnt = 0

for i in range(pos, N):
    if S[i]=='(':
        l_cnt += 1
    else:
        l_cnt -= 1

if l_cnt > 0:
    print('('*r_cnt + S + ')'*l_cnt)
else:
    print('('*(r_cnt-l_cnt) + S)