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())
R = 0
L = 0
flag = 0
M = []
for _ in range(n):
    s = input()
    right = 0
    left = 0
    for w in s:
        if w == "(":
            left += 1
        if w == ")":
            if left > 0:
                left -= 1
            else:
                right += 1
    if left > 0 and right > 0:
        M.append((right, left))
    elif left == 0 and right > 0:
        R += right
    elif left > 0 and right == 0:
        L += left
ML = 0
MR = 0
for mr, ml in M:
    if MR == 0 and ML == 0:
        MR += mr
        ML += ml
    elif MR == 0:
        if ML > mr:
            ML -= mr
        else:
            ML = 0
            MR += mr - ML
        MR += mr
    elif ML == 0:
        if MR > ml:
            MR -= ml
        else:
            MR = 0
            ML += ml - MR
        ML += ml
    else:
        if ML > mr:
            ML -= mr
            ML += ml
        elif MR > ml:
            MR -= ml
            MR += mr
        elif ML <= mr:
            ML = 0
            MR += mr - ML
            ML += ml
        else:
            MR = 0
            ML += ml - MR
            MR += mr

if ML == 0 and MR > 0:
    R += MR
elif MR == 0 and ML > 0:
    L += ML
elif MR > 0 and ML > 0:
    L -= MR
    if L < 0:
        flag = 1
    L += ML


if L != R:
    flag = 1
if flag:
    print("No")
else:
    print("Yes")

Submission status: Wrong Answer

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

T = [0]*N
M = [0]*N
for i in range(N):
    res = 0
    idx = 0
    s = S[i]
    l = len(s)
    m = 0
    while idx<l:
        if s[idx]==')':
            res -= 1
            m = min(res,m)
        else:
            res += 1
        idx += 1
    
    M[i] = -m
    T[i] = res-m

MT = []
for i in range(N):
    MT.append([M[i],-T[i]])

MT.sort()

if MT[0][0] != 0:
    print('No')
    exit()

res = 0
for m,t in MT:
    res -= m
    if res<0:
        print('No')
        exit()
    res -= t
if res!=0:
    print('No')
else:
    print('Yes')

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
from bisect import bisect_left
import sys
readlines = sys.stdin.buffer.readlines
readline = sys.stdin.buffer.readline


class SegmentTree:
    """
    演算子は要素とセットでモノイドを形成するようなものでなければならない。
    すなわち、結合律が成り立ち単位元が存在する必要がある。

    equalityはsetを高速化するために使う。めんどい場合はNoneにしてもOK
    """
    @classmethod
    def all_identity(cls, operator, equality, identity, size):
        return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length()))

    @classmethod
    def from_initial_data(cls, operator, equality, identity, data):
        size = 1 << (len(data)-1).bit_length()
        temp = [identity]*(2*size)
        temp[size:size+len(data)] = data
        data = temp

        for i in reversed(range(size)):
            data[i] = operator(data[2*i],data[2*i+1])
        return cls(operator, equality, identity, data)

    # これ使わずファクトリーメソッド使いましょうね
    def __init__(self, operator, equality, identity, data):
        if equality is None:
            equality = lambda a,b: False
        self.op = operator
        self.eq = equality
        self.id = identity
        self.data = data
        self.size = len(data)//2

    def _interval(self, a, b):
        a += self.size
        b += self.size
        ra = self.id
        rb = self.id

        data = self.data
        op = self.op
        while a < b:
            if a & 1:
                ra = op(ra,data[a])
                a += 1
            if b & 1:
                b -= 1
                rb = op(data[b],rb)
            a >>= 1
            b >>= 1
        return op(ra,rb)

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self._interval(
                                    0 if i.start is None else i.start,
                                    self.size if i.stop is None else i.stop)
        elif isinstance(i, int):
            return self.data[i+self.size]

    def __setitem__(self, i, v):
        i += self.size
        data = self.data
        op = self.op
        eq = self.eq
        while i and not eq(data[i],v):
            data[i] = v
            v = op(data[i^1],v) if i & 1 else op(v,data[i^1])
            i >>= 1

    def __iter__(self):
        return self.data[self.size:]

from operator import eq

N = int(readline())

memo = [None]*N

for i,s in enumerate(readlines()):
    s = s.rstrip().decode()
    memo[i] = (min(0,min(accumulate(1 if c =='(' else -1 for c in s))),sum(1 if c =='(' else -1 for c in s))

memo.sort()
def solve():
    min_acc = [v for v,_ in memo]
    delta = [(v,i) for i,(_,v) in enumerate(memo)]
    identity = (-float('inf'), -1)

    seg = SegmentTree.from_initial_data(max, eq, identity, delta)

    cur = 0
    for cnt in range(N):
        ind = bisect_left(min_acc, -cur)
        d, i = seg[ind:]
        seg[i] = identity
        cur += d
        if (d,i) == identity or cur < 0:
            return False
    return cur == 0

print('Yes' if solve() else 'No')

Submission status: Wrong Answer

Solution code:
import itertools

n=int(input())
S=[]
for i in range(n):
    s=input()
    count=0
    mins=0
    for j in range(len(s)):
        if s[j]=='(':
            count+=1
        elif s[j]==')':
            count-=1
            if count<mins:
                mins=count
    S.append([count,mins*-1])
    
S.sort(reverse=True)
print(S)

count=0
flag=True

for i in range(n):
    if count>=S[i][1]:
        count+=S[i][0]
    else:
        flag=False
        break

if flag and count==0:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
cnt=[]
for i in range(n):
	s=input().rstrip()
	l=s.count("(")
	r=s.count(")")
	minus=0
	now=0
	for j in range(len(s)):
		if s[j]=="(":
			now+=1
		else:
			now-=1
			minus=min(minus,now)
	cnt.append((l,r,s,minus))
cnt.sort(key=lambda x:x[1]-x[0])
plus=[]
minus=[]
for x in cnt:
	if x[0]-x[1]>=0:
		plus.append(x)
	else:
		minus.append(x)
plus.sort(key=lambda x:-x[3])
minus.sort(key=lambda x:(x[1]-x[0],x[3]))#ここが誤り?
l=r=0
for x in plus:
	for i in range(len(x[2])):
		if x[2][i]=="(":
			l+=1
		else:
			r+=1
		if l<r:
			print("No")
			exit()
for x in minus:
	for i in range(len(x[2])):
		if x[2][i]=="(":
			l+=1
		else:
			r+=1
		if l<r:
			print("No")
			exit()
if l==r:
	print("Yes")
else:
	print("No")

Submission status: Wrong Answer

Solution code:
def main():

    N = int(input())
    S = []
    pos = []
    neg1 = []
    neg2 = []
    tot_v = 0
    for _ in range(N):
        t = input()
        S.append(t)
        v = 0
        min_v = float('inf')
        for c in t:
            if c == '(': v += 1
            else: v -= 1
            min_v = min(min_v, v)
        tot_v += v
        if min_v >=0:
            pos.append([min_v, v])
        else:
            if v > 0:
                neg1.append([v - min_v, min_v, v])
            else:
                neg2.append([min_v, v])

    if tot_v !=  0: return "No"

    u = 0
    for _, v in pos:
        u += v

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

    for _, min_v, v in neg1:
        if u + min_v < 0:
            return "No"
        else:
            u += v

    # neg2.sort(key = lambda x: x[0])
    for min_v, v in neg2:
        if u + min_v < 0:
            return "No"
        else:
            u += v

    return "Yes"


if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
n = int(input())
start = 0
end = 0
left = 0
double = []
right = 0
for i in range(n):
    s = str(input())
    kienaileft = 0
    kienairight = 0
    for j in range(len(s)):
        if s[j] == ")":
            kienaileft += 1
        else:
            break
    for j in range(len(s)):
        if s[-(j+1)] == "(":
            kienairight += 1
        else:
            break
    nowleft = 0
    nowright = 0
    for j in range(kienaileft,len(s)-kienairight):
        if s[j] == ")":
            nowleft += 1
        else:
            nowright += 1
    num = min(nowleft,nowright)
    kienaileft += nowleft -num
    kienairight += nowright -num
    if kienaileft != 0:
        if kienairight != 0:
            double.append([kienaileft,kienairight])
        else:
            left += kienaileft
    else:
        if kienairight != 0:
            right += kienairight
  # print(left,double,right)
if left + sum([double[i][0] for i in range(len(double))]) != sum([double[i][1] for i in range(len(double))]) + right:
    print("No")
    exit()
if len(double) != 0:
    if not left or not right:
        print("No")
        exit()
else:
    if left == right:
        print("Yes")
        exit()
double.sort(key=lambda x:x[1],reverse=True)
double.sort()
now = left
for a,b in double:
    if now < a:
        print("No")
        exit()
    now += (b-a)
print("Yes")

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    S = [input() for _ in [0]*n]
    s2 = []
    s3 = []
    for s in S:
        temp = [0, 0]
        m = 0
        now = 0
        for i in s:
            if i == "(":
                now += 1
            else:
                now -= 1
            m = min(m, now)
        temp[0] = m
        temp[1] = (s.count("(")-s.count(")"))
        if temp[1] >= 0:
            s2.append(temp)
        else:
            s3.append(temp)
    s2.sort(key=lambda x: x[0])
    s3.sort(key=lambda x: -x[0])
    cnt = 0
    for i, j in s2:
        if cnt+i < 0:
            print("No")
            return
        cnt += j
    for i, j in s3:
        if cnt+i < 0:
            print("No")
            return
        cnt += j
    if cnt != 0:
        print("No")
        return
    print("Yes")


main()

Submission status: Wrong Answer

Solution code:
N = int(input())
S_info1 = []
S_info2 = []

tot = 0

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)
    tot += score
    if minv >= 0:
        S_info1.append([s, score, maxv, minv])
    else:
        S_info2.append([s, score, maxv, minv])

if tot != 0:
    print("No")
else:
    S_info1.sort(key = lambda x:(-x[3], -x[1]))
    #print(S_info1)
    tot = 0
    flag = True
    for i in range(len(S_info1)):
        s, score, maxv, minv = S_info1[i]
        if tot < -minv:
            flag = False
            break
        tot += score
    if not flag:
        print("No")
    else:
        S_info = S_info1 + S_info2
        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 Maxscore >= -Minv:
            print("Yes")
        else:
            print("No")

Submission status: Wrong Answer

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

def main():
    N0 = 2 ** (n - 1).bit_length()
    data = [float('inf')] * (2 * N0)

    def update(k, x):
        k += N0 - 1
        data[k] = x
        while k >= 0:
            k = (k - 1) // 2
            data[k] = min(data[2 * k + 1], data[2 * k + 2])
    def query(l, r):
        L = l + N0
        R = r + N0
        s = float('inf')
        while L < R:
            if R & 1:
                R -= 1
                s = min(s, data[R - 1])

            if L & 1:
                s = min(s, data[L - 1])
                L += 1
            L >>= 1
            R >>= 1
        return s

    dl = []
    for i in range(n):
        dd = 0
        dd_min = 0
        for x in s[i]:
            if x == '(':
                dd += 1
            else:
                dd -= 1
            dd_min = min(dd_min, dd)

        dl.append([dd, dd_min])

    d = [_dl[0] for _dl in dl]
    if sum(d) != 0:
        print('No')
    else:
        dl.sort(key=lambda x:x[1]) # sorted by d_min
        d = [_dl[0] for _dl in dl]
        d_min = [_dl[1] for _dl in dl]

        from collections import defaultdict
        d_to_idx = defaultdict(list)
        for i in range(n):
            d_to_idx[d[i]].append(i)

        for i in range(len(d)):
            update(i, -d[i])

        from bisect import bisect_left
        f = True
        carry = 0
        for i in range(n):
            # print(carry, d, d_min)
            if d_min[-1] + carry < 0:
                f = False
                break

            idx = bisect_left(d_min, -carry)

            dd = -query(idx, n)
            if dd == -float('inf'):
                f = False
                break

            idx2 = d_to_idx[dd][-1]
            d_to_idx[dd].pop()

            carry += dd
            update(idx2, float('inf'))


        if f:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())

all_change_depth = 0
required_depth = []

change_posi_zero = []
change_nega = []

for i in range(n):
    paren = input()
    current_depth = 0
    min_depth = 0
    for ch in paren:
        if ch == '(':
            current_depth += 1
        else:
            current_depth -= 1
            min_depth = min(min_depth, current_depth)

    all_change_depth += current_depth
    if current_depth >= 0:
        change_posi_zero.append( (current_depth, -(min_depth)) )
    else:
        change_nega.append( (current_depth, -(min_depth)) )

# まず変化depthの合計が非ゼロならNo。（と）の個数が全体で不一致なので。
if all_change_depth != 0:
    print('No')
    exit()

# 変化depthが0と正の要素を、要求depthが小さい順に投入する。
# 現在depth < 要求depthならアウト
current_depth = 0
change_posi_zero.sort(key=lambda x: x[1])
for paren in change_posi_zero:
    change_depth = paren[0]
    required_depth = paren[1]

    if required_depth > current_depth:
        print('No')
        exit()
    current_depth += change_depth

# 変化depthが負の要素を、要求depthが大きい順に投入する。
# 現在depth < 要求depthならアウト
change_nega.sort(key=lambda x: x[1], reverse=True)

for paren in change_nega:
    change_depth = paren[0]
    required_depth = paren[1]

    if required_depth > current_depth:
        print('No')
        exit()
    current_depth += change_depth

assert(current_depth == 0)
print('Yes')

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'

    sl = sum(l)
    sr = sum(r)
    b.append([sl, 0])
    b.append([0, sr])
    b.sort(key=lambda x: x[1]-x[0])

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

    if b[0][0] == 0 and b[0][0] == 0:
        return 'Yes'

    return 'No'


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:
import sys
def input():
    return sys.stdin.readline().strip()

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

tmp = []
for i,s in enumerate(S):
    tmp.append([s.count("(")-s.count(")"),i])

tmp.sort(reverse=True)

a = 0
b = 0
s = ""
for _,i in tmp:
    s += S[i]
##print(s)
for i in s:
    if i == "(":
        a += 1
    else:
        b += 1
    if b > a:
        print("No")
        exit()

if a-b == 0:
    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],-x[1]))
# print(lst)

cnt=0
last=defaultdict(int)
for i in range(n):
    if lst[i][1]==0:
        last[i]+=1
        cnt+=lst[i][0]

tmp=0
for i in range(n):
    if i in last:
        continue
    tmp-=lst[i][0]
    if tmp<0:
        print("No")
        break
    tmp+=lst[i][1]
else:
    tmp-=cnt
    if tmp==0:
        print("Yes")
    else:
        print("No")

Submission status: Wrong Answer

Solution code:
n = int(input())
start = 0
end = 0
left = 0
double = []
right = 0
for i in range(n):
    s = str(input())
    kienaileft = 0
    kienairight = 0
    for j in range(len(s)):
        if s[j] == ")":
            kienaileft += 1
        else:
            break
    for j in range(len(s)):
        if s[-(j+1)] == "(":
            kienairight += 1
        else:
            break
    nowleft = 0
    nowright = 0
    for j in range(kienaileft,len(s)-kienairight):
        if s[j] == ")":
            nowleft += 1
        else:
            nowright += 1
    num = min(nowleft,nowright)
    kienaileft += nowleft -num
    kienairight += nowright -num
    if kienaileft != 0:
        if kienairight != 0:
            double.append([kienaileft,kienairight])
        else:
            left += kienaileft
    else:
        if kienairight != 0:
            right += kienairight
  # print(left,double,right)
if left + sum([double[i][0] for i in range(len(double))]) != sum([double[i][1] for i in range(len(double))]) + right:
    print("No")
    exit()
if len(double) != 0:
    if not left or not right:
        print("No")
        exit()
else:
    if left == right:
        print("Yes")
        exit()
double.sort(key=lambda x:x[0]-x[1],reverse=True)
double.sort()
now = left
for a,b in double:
    if now < a:
        print("No")
        exit()
    now += (b-a)
print("Yes")

Submission status: Wrong Answer

Solution code:
n,*s=open(0)
n=int(n)
f=g=h=a=b=m=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
    if x==0:f=1
    elif y==0:g=1
    else:m+=1
    a+=x
    b+=y
if (h>1 or f and g) and a==b and m < n / 5 * 4:
    print('Yes')
else:
    print('No')

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])
    L+=l
    R+=r

if L!=R:
    print("No")
else:
    first=[]
    last=[]
    for i in range(N):
        yabai,gap=S[i]
        if gap>0:
            first.append(S[i])
        else:
            last.append([gap,yabai])
    first.sort(reverse=True)
    last.sort(reverse=True)
    G=0
    for i in range(len(first)):
        yabai,gap=first[i]
        if 0>G+yabai:
            print("No")
            exit()
        else:
            G+=gap
    for j in range(len(last)):
        gap,yabai=last[j]
        if 0>G+yabai:
            print("No")
            break
        else:
            G+=gap
    else:
        print("Yes")

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(1,0),(-1,0),(0,1),(0,-1)];EightNb=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('EWNS',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def __str__(self):
        return  str(self.edges)

    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v

    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]

class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1

        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][r-(1<<N)])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][r-(1<<N)]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][r-(1<<N)]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])

    def print(self):
        for i in self.table:
            print(*i)

class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]

    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

show_flg=False
show_flg=True
ans=0

mo=998244353

n=I()
b=[]
L,R=0,0
for i in range(n):
    s=S_()
    ns=len(s)
    a=[0]
    m,M=0,0
    l,r=0,0
    lv=0
    for j in s:
        if j=='(':
            lv+=1
            l+=1
            x=a[-1]+1
            a+=[a[-1]+1]
            if M<x:
                M=x
        else:
            lv-=1
            r+=1
            x=a[-1]-1
            a+=[a[-1]-1]
            if m>x:
                m=x
    y=( (M)*10**7+m,lv,l,r,m,M)
    #b+=[(l,r,m,M,s)]
    b+=[y]
    L+=l
    R+=r

if L!=R:
    print('No')
    exit()
b.sort(key=lambda x:-x[0])

x=0

for i in b:
    sc,lv,l,r,m,M=i
    if x+m<0:
        print('No')
        exit()
    x+=lv

#    print(i)

if x==0:
    print('Yes')

Submission status: Wrong Answer

Solution code:
N = int(input())
A = 0
B = []
for i in range(N):
  S = input()
  a = 0
  m = 0
  for s in S:
    if s == '(':
      a = a + 1
    else:
      a = a - 1
      if a < m:
        m = a
  if m == 0:
    A += a
  else:
    B.append([m, a])
B.sort()
f = 0
for b in B:
  if A + b[0] >= 0:
    A = A + b[1]
  else:
    print("No")
    f = 1
    break
if f == 0:
  print("Yes")