Problem:


Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No



Sample input:
2
)
(()


Sample output:
Yes

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [[0]*2 for i in range(N)]
for i in range(N):
    S = input()
    M = len(S)
    L = 0
    R = 0
    R0 = 0
    t = 0
    if S[0]==")":
        while t<M:
            if S[t]==")":
                R0+=1
                t+=1
            else:
                t+=1
                break
    while t<M:
        if S[t]=="(":
            t+=1
            L+=1
        else:
            t+=1
            R+=1
    if L>R:
        LR[i][0]=L-R
        LR[i][1]=R0
    if L<R:
        LR[i][0]=0
        LR[i][1]=R0+R-L
    if L==R:
        LR[i][0]=0
        LR[i][1]=R0

LP = 0
RP = 0
LS = 0
RS = 0
for i in range(N):
    L = LR[i][0]
    R = LR[i][1]
    if (L==0)and(R==0):
        continue
    elif L==0:
        RP += R
    elif R==0:
        LP += L
    else:
        LS += L
        RS += R
if (LS==RP)and(RS==LP):
    print("Yes")
elif (LP==RP)and(LS==0)and(RS==0):
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import Counter, defaultdict, deque

(N,) = [int(x) for x in input().split()]
brackets = [input() for i in range(N)]

delta = []
minDelta = []
for s in brackets:
    balance = 0
    mn = 0
    for c in s:
        if c == "(":
            balance += 1
        else:
            balance -= 1
        mn = min(mn, balance)
    delta.append(balance)
    minDelta.append(mn)

if sum(delta) == 0:
    posIndices = [i for i in range(N) if delta[i] > 0]
    posIndices.sort(key=lambda i: -minDelta[i])

    eqIndices = [i for i in range(N) if delta[i] == 0]

    negIndices = [i for i in range(N) if delta[i] < 0]
    negIndices.sort(key=lambda i: (minDelta[i], delta[i]))
    balance = 0
    for i in posIndices + eqIndices + negIndices:
        if balance + minDelta[i] < 0 or balance + delta[i] < 0:
            print("No")
            exit()
        balance += delta[i]
    assert balance == 0

    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
N = int(input())
left = []
right = []
lst = []
for i in range(N):
    S = input()
    st, st2, t = 0, 0, 0
    for c in S:
        if c == '(':
            st += 1
            t -= 1
        else:
            if st > 0:
                st -= 1
            else:
                st2 += 1
            t += 1
    if S[0] == '(' and st2 == 0:
        left.append((t, i))
    if S[-1] == ')' and st == 0:
        right.append((t, i))
    lst.append((t, i))
left.sort()
right.sort(reverse=1)
lst.sort()
if left[0][1] == right[0][1]:
    if len(right) > 1:
        l = left[0][1]
        r = right[1][1]
        cnt = 0
        for (t, i) in lst:
            if i == l or i == r:
                continue
            cnt += t
        if cnt == 0:
            print('Yes')
            exit()
    if len(left) > 1:
        l = left[1][1]
        r = right[0][1]
        cnt = 0
        for (t, i) in lst:
            if i == l or i == r:
                continue
            cnt += t
        if cnt == 0:
            print('Yes')
            exit()
else:
    l = left[0][1]
    r = right[0][1]
    cnt = 0
    for (t, i) in lst:
        if i == l or i == r:
            continue
        cnt += t
    if cnt == 0:
        print('Yes')
        exit()
print('No')

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import heapq
n = int(input())
sss = [input() for _ in range(n)]

a = []
b = []
ss = 0
for i in sss:
    mi = 0
    ma = 0
    s = 0
    for j in i:
        if j == "(":
            s += 1
        else:
            s -= 1
        mi = min(mi, s)
        ma = max(ma, s)
    ss += s
    if s >= 0:
        a.append([-s, mi, ma, i])
    else:
        mi = 0
        ma = 0
        s = 0
        for j in reversed(i):
            if j == ")":
                s += 1
            else:
                s -= 1
            mi = min(mi, s)
            ma = max(ma, s)
        b.append([-s, mi, ma, i])


if ss != 0:
    print("No")
    exit()
a.sort(reverse=1, key=lambda x: x[1])
b.sort(reverse=1, key=lambda x: x[1])


def ok1(a):
    s = 0
    heap = []
    i = 0
    while True:
        while i < len(a) and a[i][1] + s >= 0:
            heapq.heappush(heap, a[i])
            i += 1
        if i < len(a) and not heap:
            print("No")
            exit()
        if not heap:
            break
        kkk = 0
        for j in heapq.heappop(heap)[-1]:
            kkk += 1
            if j == "(":
                s += 1
            else:
                s -= 1
            if s < 0:
                print("No")
                exit()


def ok(a):
    s = 0
    heap = []
    i = 0
    while True:
        while i < len(a) and a[i][1] + s >= 0:
            heapq.heappush(heap, a[i])
            i += 1
        if i < len(a) and not heap:
            print("No")
            exit()
        if not heap:
            break
        kkk = 0
        for j in reversed(heapq.heappop(heap)[-1]):
            kkk += 1
            if j == ")":
                s += 1
            else:
                s -= 1
            if s < 0:
                print("No")
                exit()


ok1(a)
ok(b)
print("Yes")

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for i in range(N)]

os = cs = 0
zo = []
zc = []
for i,s in enumerate(S):
    op = 0
    for c in s:
        if c=='(':
            op += 1
        else:
            if op: op -= 1
    cl = 0
    for c in s[::-1]:
        if c==')':
            cl += 1
        else:
            if cl: cl -= 1
    os += op
    cs += cl
    if op==0:
        zo.append(i)
    if cl==0:
        zc.append(i)

if os != cs or len(zo) != len(zc):
    print('No')
else:
    if len(zo)==0 :
        print('No')
    elif len(zo) >= 2:
        print('Yes')
    else:
        assert len(zo)==1 and len(zc)==1
        print('Yes' if zo[0] != zc[0] else 'No')

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


def main():
    n = int(input().strip())
    s_list = []
    for _ in range(n):
        s_list.append(input().strip())

    pi_list = []
    sum_cp = 0
    for s in s_list:
        cp = 0
        m_min = 0
        for c in s:
            if c == "(":
                cp += 1
            else:
                cp -= 1
                m_min = min(m_min, cp)

        pi_list.append([m_min, cp - m_min])
        sum_cp += cp

    pi_list =[x for x in pi_list if x != [0, 0]]
    if any(x[0] == 0 for x in pi_list) and \
        any(x[1] == 0 for x in pi_list) and \
        sum_cp == 0:
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s_ls = []
for i in range(n):
    s_ls.append(input())

t_ls = []

for item in s_ls:
    stk = []
    left = 0
    for ch in item:
        if ch == ')' and len(stk) == 0:
            left += 1
        elif ch == ')':
            stk.pop()
        else:
            stk.append('(')
    right = len(stk)
    t_ls.append([left, -right])

t_ls.sort()

cnt = 0

for item in t_ls:
    cnt += item[0]
    if cnt > 0:
        print('No')
        exit()
    else:
        cnt += item[1]

if cnt == 0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque

def count(s):
    ret = 0
    max_down = 0
    for c in s:
        if c=="(": ret += 1
        else: ret -= 1
        max_down = min(max_down,ret)
    return ret, max_down

n = int(input())
s_count = []
for i in range(n):
    si = input()
    s_count.append(count(si))

s_count.sort(reverse = True)
s_count = deque(s_count)

ans = "No"
count_sum = 0
s_count_stack = deque([])
for _ in range(n):
    
    flag = 1
    while s_count:
        num, down = s_count.popleft()
        if count_sum + down >=0 :
            count_sum += num
            flag = 0
            break
    if flag: break
    while s_count_stack:
        num, down = s_count_stack.pop()
        s_count.appendleft(num,down)
else:
    if count_sum == 0: ans = "Yes"

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S_info = []

print("No")

Submission status: Wrong Answer

Solution code:
#かっこ列とは…( = +1 ) = -1「途中でマイナスにならない」
N = int(input())
AllMin = []
for n in range(N):
    S = input()
    minkakko = 10000000
    cur = 0
    for s in S:
        if s == "(":
            cur += 1
        else:
            cur -= 1
        minkakko = min(minkakko,cur)
    AllMin.append((cur,minkakko))
AllMin.sort(key = lambda x:1000000*(x[1]>0) + abs(x[1]),reverse=True)
if sum([x[0] for x in AllMin]) == 0:
    pos = 0
    for a,m in AllMin:
        if pos < -m:
            print("No")
            exit()
        pos += a
        if pos < 0:
            print("No")
            exit()        
    #プラス組のなかでMinが大きい順に積んでいく
    #マイナス組のなかでMinが小さい順に積んでいく
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
cnt = int(input())
bracket_list = [input() for _ in range(cnt)]


def loop_replace(s):
    output = ''
    while output != s:
        output = s
        s = s.replace('()', '')
    return output


b_list = []
for b in bracket_list:
    b = loop_replace(b)
    if b != '':
        b_list.append(b)

if len(b_list) == 0:
    b_str = ''
elif len(b_list) == 1:
    b_str = '('
else:
    b_str = b_list[0]
    for b in b_list[1:]:
        if b_str == '':
            b_str = b
        elif b_str[0] == '(':
            b_str = loop_replace(b_str + b)
        else:
            b_str = loop_replace(b + b_str)

if b_str == '':
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
from math import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
s=[input() for i in range(n)]
lst=[[0]*2 for i in range(n)]

for i in range(n):
    l,r=0,0
    for j in range(len(s[i])):
        if s[i][j]==")":
            if r==0:
                l+=1
            else:
                r-=1
        if s[i][j]=="(":
            r+=1
    lst[i][0]=l
    lst[i][1]=r
# print(lst)
lst.sort(key=lambda x: x[0])
# print(lst)
tmp=0
for i in range(n):
    tmp-=lst[i][0]
    if tmp<0:
        print("No")
        break
    tmp+=lst[i][1]
else:
    if tmp==0:
        print("Yes")
    else:
        print("No")

Submission status: Wrong Answer

Solution code:
N = int(input())

S = [input() for i in range(N)]

C = [[0,0] for i in range(N)]

for i in range(N):
    for j in range(len(S[i])):
        if S[i][j] == '(':
            C[i][0] += 1
        else:
            C[i][0] -= 1
        C[i][1] = min(C[i][0],C[i][1])

if sum(C[i][0] for i in range(N)) != 0:
    print('No')
    exit()

C.sort(key=lambda x : (x[1], x[0]), reverse=True)

now = 0
ans = 'Yes'
for i in range(N):
    if now + C[i][1] < 0:
        ans = 'No'
        break

    now += C[i][0]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def input():return sys.stdin.readline().strip()

def main():
    N = int(input())
    SS = [input() for _ in range(N)]
    left = 0
    right = 0
    left_f = 0
    right_f = 0

    for s in SS:
        left += s.count("(")
        right += s.count(")")
        if s[0] == "(" :
            left_f += 1
        if s[-1] == ")":
            right_f += 1

    if left == right and left_f >= 2 and right_f >= 2:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

N = int(input())
pos = []
zero = []
neg = []
for _ in range(N):
    S = input().rstrip()
    m = s = 0
    for c in S:
        if c == '(':
            s += 1
        else:
            s -= 1
            m = min(m, s)
    if s > 0:
        heappush(pos, (-m, s)) # take larger mins first
    elif s == 0:
        heappush(zero, (m, s))
    else:
        heappush(neg, (m, s)) # take smaller mins first
num = 0
while pos:
    m, s = heappop(pos)
    if num - m < 0:
        print('No')
        exit()
    num += s
while zero:
    m, s = heappop(zero)
    if num + m < 0:
        print('No')
        exit()
while neg:
    m, s = heappop(neg)
    if num + m < 0:
        print('No')
        exit()
    num += s
if num == 0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    S=[input() for i in range(N)]
    lp=[]
    lm=[]
    lpm=[]
    for i,s in enumerate(S):
        p=0
        m=0
        for x in s:
            if x=='(':
                p+=1
            else:
                if p>0:
                    p-=1
                else:
                    m+=1
        if m==0 and p>0:
            lp.append(p)
        elif p==0 and m>0:
            lm.append(m)
        elif p>0 and m>0:
            lpm.append((p,m))
    P=sum(lp)
    M=sum(lm)
    lpm.sort(key=lambda t:t[0])
    for t in lpm:
        P-=t[1]
        if P<0:
            print('No')
            exit()
        P+=t[0]
    P-=M
    YesNo(P==0)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
S = list(input() for _ in range(N))
X = []
for s in S:
    l,r = 0,0
    for c in s:
        if c == ")":
            if r > 0:
                r -= 1
            else:
                l += 1
        else:
            r += 1
    X.append([l,r])
X.sort()
Y = 0
for a,b in X:
    if a > Y:
        print("No")
        quit()
    Y -= a
    Y += b

if Y:
    print("No")
else:
    print("Yes")

Submission status: Wrong Answer

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

N = int(input())
S = [input().rstrip() for _ in range(N)]

def calc(S):
    now = 0
    ret = 0
    for s in S:
        if s == '(':
            now += 1
        else:
            now -= 1
        ret = min(ret, now)
    return ret

H = []
P = []
L = []

for s in S:
    less = -calc(s)
    if less == 0:
        H.append(s)
    else:
        l = s.count('(')
        r = len(s) - l
        if l >= r:
            P.append((less, s))
        else:
            L.append((less, s))

P.sort(key=lambda a: a[0])
L.sort(key=lambda a: a[0], reverse=True)
P = [s for _, s in P]
L = [s for _, s in L]

ans = ''.join(H + P + L)
l = ans.count('(')
r = ans.count(')')

if l == r and calc(ans) == 0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for i in range(N)]

def bend(s):
    res = 0
    k = 0
    for th in s:
        if th == '(':
            k += 1
        else:
            k -= 1
        res = min(k,res)
    return res

LmR = [(-bend(s),-(s.count('(') - s.count(')'))) for s in S]

LmR.sort()

cumsum = 0
for b,k in LmR:
    b,k = -b,-k
    if cumsum + b < 0:
        print('No')
        exit()
    cumsum += k
    if cumsum < 0:
        print('No')
        exit()
if cumsum == 0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import sys

st = []
n = int(input())
for i in range(n):
    s = input()
    bal = 0
    min_bal = float('inf')
    for c in s:
        bal += 1 if c == '(' else -1
        min_bal = min(bal, min_bal)

    st.append((min_bal, bal))

st.sort(reverse=True)

cur = 0
for m, e in st:
    if cur + m < 0:
        print("No")
        sys.exit()

    cur += e

print("Yes" if cur == 0 else "No")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd

N=int(input())
S = [input() for _ in range(N)]
a = [(0,0,0)]*N
p1 = []
p2 = []
p3 = []
for i,s in enumerate(S):
    depth = 0
    max_depth = 0
    min_depth = 0
    for chr in s:
        if chr=='(':
            depth += 1
            if depth > max_depth:
                max_depth = depth
        else:
            depth -= 1
            if depth < min_depth:
                min_depth = depth
    a[i] = (depth, max_depth, min_depth)
    if depth >= 0 and min_depth >= 0:
        p1.append((depth,min_depth))
    elif min_depth < 0:
        p2.append((min_depth,depth))
    else:
        p3.append((depth,min_depth))
pp1 = sorted(p1,reverse=True)
pp2 = sorted(p2,reverse=True)
pp3 = sorted(p3,reverse=True)
# print(p1)
# print(p2)
# print(p3)

depth = 0
for p in pp1:
    depth += p[0]
for p in pp2:
    if depth+p[0] < 0:
        print('No')
        exit()
    depth += p[1]
for p in pp3:
    if depth < -p[1]:
        print('No')
        exit()
    depth += p[0]
if depth != 0:
    print('No')
else:
    print('Yes')

Submission status: Wrong Answer

Solution code:
N = int(input())
S_info = []
for _ in range(N):
    s = input()
    score = 0
    maxv = 0
    minv = 0
    for c in s:
        if c == "(":
            score += 1
        else:
            score -= 1
        maxv = max(maxv, score)
        minv = min(minv, score)
    S_info.append([s, score, maxv, minv])

flag = True
tot = 0
Maxv = 0
Minv = 0
Maxscore = 0
for i in range(N):
    s, score, maxv, minv = S_info[i]
    tot += score
    Maxv = max(Maxv, maxv)
    Minv = min(Minv, minv)
    if score > 0:
        Maxscore += score
if tot == 0 and Maxscore >= -Minv:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:

"""

大事な要素
深さと高低差
まず、高低差の話が0であることは必須

もう一つ、現状が深さ以上ないと設置できない。
まず、高くするやつで置けるやつはどんどんおいていい。
置いたもん勝ち
→つまり、+で深さが浅い順においていけばいい

降りるときは、深い→浅いが置けない場合で浅い→深いが置ける場合はない
→深い順に億


"""


N = int(input())

ans = 0

pl_d = [] 
mi_d = []

for lp in range(N):

    S = input()

    dep = 0
    mindep = 0

    for i in S:
        if i == "(":
            dep += 1
        else:
            dep -= 1

        mindep = min(dep,mindep)

    if dep >= 0:
        pl_d.append([mindep,dep])
    else:
        mi_d.append([mindep-dep,-1 * dep])

pl_d.sort()
mi_d.sort()

#print (pl_d,mi_d)

nowp = 0

import sys
for i in range(len(pl_d)):

    nd,np = pl_d[i]

    if nowp + nd < 0:
        print ("No")
        sys.exit()

    nowp += np

nowm = 0

import sys
for i in range(len(mi_d)):

    nd,np = mi_d[i]

    if nowm + nd < 0:
        print ("No")
        sys.exit()

    nowm += np


if nowp != nowm:
    print ("No")
else:
    print ("Yes")

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
ls = [0] * N
rs = [0] * N
a = []
for x in range(N):
  S = list(input())[: -1]
  for i in range(len(S)):
    if S[i] == "(": rs[x] += 1
    if S[i] == ")":
      if rs[x]: rs[x] -= 1
      else: ls[x] += 1
  a.append((ls[x], rs[x]))
if sum(ls) != sum(rs):
  print("No")
  exit(0)
if sum(ls) == 0:
  print("Yes")
  exit(0)
l = 0
r = 0
for i in range(N):
  if ls[i] == 0 and (rs[i] > 0): l = 1
  if rs[i] == 0 and (ls[i] > 0): r = 1
if l & r == 0:
  print("No")
  exit(0)

a.sort(key = lambda x: (x[0], -x[1]))
#print(a)
l = 0
for i in range(len(a)):
  l -= a[i][0]
  if l < 0:
    print("No")
    exit(0)
  l += a[i][1]
print("Yes")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 998244353
INF = float('inf')
# ----------------------------------------------------------- #

n = I()
s = []
su = 0
for i in range(n):
    mi_ = 0
    tmp = 0
    s_ = input()
    for x in s_:
        if x == "(":
            tmp += 1
        else:
            tmp -= 1
        mi_ = min(mi_, tmp)
    s.append((tmp, mi_))
    su += tmp

if su != 0:
    print("No")
    exit()

s.sort(key=itemgetter(0, 1), reverse=True)
# print(s)

acc = 0
for i in range(n):
    if acc + s[i][1] < 0:
        print("No")
        exit()
    acc += s[i][0]

print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(10**9)
from collections import deque
import heapq
from itertools import combinations
import bisect

n=int(input())
l=[]
for i in range(n):
    l.append(list(input()))

p=0
q=0
for i in range(n):
    for j in l[i]:
        if j=='(':
            p+=1
        else:
            q+=1
if p!=q:
    print('No')
    exit()
pl=[]
ql=[]
ml=[]
for i in range(n):
    a=l[i]
    p=0
    q=0
    for j in a:
        if j=='(':
            p+=1
        else:
            q+=1
    if p>q:
        pl.append(a)
    elif p<q:
        ql.append(a)
    else:
        ml.append(a)
if pl:
    pl.sort()
if ql:
    ql.sort()
if ml:
    ml.sort()
if pl:
    if pl[0][0]==')':
        print('No')
        exit()
else:
    if ml[0][0]==')':
        print('No')
        exit()

if ql:
    if ql[-1][-1]=='(':
        print('No')
        exit()
else:
    if ml[-1][-1]=='(':
        print('No')
        exit()

print('Yes')

Submission status: Wrong Answer

Solution code:
n,*s=open(0)
n=int(n)
f=g=h=a=b=0
for t in s:
    c=l=r=d=0
    for u in t[:-1]:
        if u=='(':
            if d<0:d=0
            d+=1
            r+=1
        else:
            d-=1
            if d>=0:c+=1
            l+=1
    x=r-c
    y=l-c
    if x==y==0:h+=1
    elif x==0:f=1
    elif y==0:g=1
    a+=x
    b+=y
if (f and g or h and (f or g) or h > 1) and a==b:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for i in range(n)]

a = []

for x in s:
    b = [0,0]
    c = [0,0]
    l = len(x)
    for j in range(l):
        if x[j]=='(':
            c[0]+=1
        else:
            c[1]+=1
        b[0] = max(c[1] - c[0], b[0])

    c = [0,0]
    for j in range(l):
        if x[l-j-1]=='(':
            c[0]+=1
        else:
            c[1]+=1
        b[1] = max(c[0]-c[1],b[1])
    a.append(b+[b[0]-b[1]]+[x])

a.sort()

b = 0

for i in range(n):
    x = a[i][3]
    l = len(x)
    flag= 1
    for j in range(l):
        if x[j]=='(':
            b+=1
        else:
            b-=1
        if b<0:
            flag = 0
if b!=0:
    flag = 0
if flag:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    l = []
    r = []
    b = [[0, 0]]
    for s in S:
        stack = []
        for c in s:
            if c == '(':
                stack.append('(')
            else:
                if stack and stack[-1] == '(':
                    stack.pop()
                else:
                    stack.append(')')
        lc = stack.count('(')
        rc = stack.count(')')
        if lc != 0 and rc != 0:
            b.append([lc, rc])
        elif lc != 0:
            l.append(lc)
        elif rc != 0:
            r.append(rc)

    if sum(l) != sum(r):
        return 'No'


    while len(b) > 1:
        x = b.pop()
        y = b.pop()
        if x[1] < y[0]:
            z = [x[0] + y[0]-x[1], y[1]]
        else:
            z = [x[0], y[1]-x[0] + y[1]]
        b.append(z)

    sl = sum(l)
    sr = sum(r)
    sl -= b[0][0]
    sr -= b[0][1]
    if sl != sr:
        return 'No'

    return 'Yes'


def main():
    N = read_int()
    S = [read_str() for _ in range(N)]
    print(slv(N, S))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
brackets_plus = []
brackets_minus = []
right = 0
left = 0
for i in range(n):
    s = input()
    cur = 0
    m = 0
    for j in range(len(s)):
        if s[j] == "(":
            left += 1
            cur += 1
        else:
            right += 1
            cur -= 1
            m = min(m,cur)
    if cur >= 0:
        brackets_plus.append((m,cur))
    else:
        brackets_minus.append((m,cur))
if right != left:
    print("No")
    exit()
cur = 0
brackets_plus.sort(reverse = True)
for i in brackets_plus:
    if i[0] + cur < 0:
        print("No")
        exit()
    cur += i[1]
brackets_minus.sort()
for i in brackets_minus:
    if i[0] + cur < 0:
        print("No")
        exit()
    cur += i[1]
print("Yes")

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[]
L=0
R=0
for i in range(N):
    s=input()
    n=len(s)
    data=[s[j] for j in range(n)]
    l=0
    r=0
    yabai=float("inf")
    for j in range(n):
        l+=(s[j]=="(")
        r+=(s[j]==")")
        yabai=min(l-r,yabai)
    S.append([yabai,l-r,data])
    L+=l
    R+=r

if L!=R:
    print("No")
else:
    ans=[]
    first=[]
    last=[]
    for i in range(N):
        yabai,gap,data=S[i]
        if gap>0:
            first.append(S[i])
        else:
            last.append(S[i])
    first.sort()
    last.sort()
    for i in range(len(first)):
        yabai,gap,data=first[i]
        ans+=data
    for j in range(len(last)):
        yabai,gap,data=last[j]
        ans+=data
    l=0
    r=0
    for i in range(len(ans)):
        l+=(ans[i]=="(")
        r+=(ans[i]==")")
        if 0>l-r:
            print("No")
            break
    else:
        print("Yes")

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]

D = [[0] * 2 for _ in range(N)]

for i in range(N):
  s = S[i]
  ma = 0
  l = 0
  r = 0
  for j in s:
    if j == ")":
      r += 1
    else:
      l += 1
    ma = max(ma, r - l)
  D[i] = [l - r, ma, s]

cnt = 0
P = []
M = []
for x, y ,s in D:
  if x >= 0:
    if y <= 0:
      cnt += x
    else:
      P.append([x, y])
  else:
    M.append([x, y, s])

P.sort(key = lambda x:x[1])

for x, y in P:
  if y > cnt:
    print("No")
    exit()
  cnt += x

if len(M) == 0:
  if cnt == 0:
    print("Yes")
  else:
    print("No")
  exit()

M.sort(key = lambda x:x[1], reverse = True)

for i in range(len(M) -1, -1, -1):
  x, y, s= M[i]
  if x == -y:
    g = x
    M[i] = [0, 0, ""]
    break
else:
  print("No")
  exit()

for x, y, s in M:
  if cnt < y:
    print("No")
    exit()
  cnt += x

if cnt + g == 0:
  print("Yes")
else:
  print("No")

Submission status: Wrong Answer

Solution code:
N = int(input())
Ss = [input() for _ in range(N)]

arr = []
for S in Ss:
    tmp = mi = 0
    for c in S:
        if c == '(':
            tmp += 1
        else:
            tmp -= 1
        mi = mi if mi < tmp else tmp
    arr.append((mi, tmp))
arr.sort(reverse=True)

tmp = 0
for (mi, n) in arr:
    if tmp + mi < 0:
        print('No')
        exit()
    tmp += n

if tmp == 0:
    print('Yes')
else:
    print('No')