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: Runtime Error

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():
    class Bit:
        def __init__(self, n):
            self.size = n
            self.tree = [0] * (n + 1)
    
        def sum(self, i):
            s = -(10 ** 18)  # -INF
            while i > 0:
                s = max(s, self.tree[i])
                i -= i & -i
            return s
    
        def add(self, i, x):
            while i <= self.size:
                self.tree[i] = max(x, self.tree[i])
                i += i & -i
    
    N=int(input())
    S=[input() for i in range(N)]
    P=0
    M=0
    c=0
    b=Bit(10**6)
    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:
            P+=p
        elif p==0 and m>0:
            M+=m
        elif p>0 and m>0:
            b.add(m,p-m+10**7)
            c+=1

    def nibutan(ok,ng,x):
        while abs(ok-ng) > 1:
            mid = (ok + ng) // 2
            if solve(mid,x):
                ok = mid
            else:
                ng = mid
        return ok
    
    def solve(mid,x):
        return b.sum(mid)==x
            
    for _ in range(c):
        x=b.sum(P)
        if x==-INF:
            print('No')
            exit()
        x-=10**7
        if P-x<0:
            print('No')
            exit()
        index=nibutan(P,0,x+10**7)
        P+=x
        b.add(index,-(x+10**7))
    P-=M
    YesNo(P==0)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
data = []
le,ri = 0,0
for i in range(n):
    s = input()
    left,right = 0,0 #left (
    for j in s:
        if j == "(":
            left += 1
        else:
            if left > 0:
                left -= 1
            else:
                right += 1
    le += left
    ri += right
    data.append([left,right])

if le != ri: #閉じない
    print("No")
    exit()
if le == ri == 0: #全部それぞれで完結
    print("Yes")
    exit()

check1,check2,check3 = False,False,True
data.sort(key=lambda z:z[1])
now = 0
left,right = -1,-1
for i,x,y in enumerate(data):
    if x > 0 and y == 0:
        check1 = True
        left = i
    if x == 0 and y > 0:
        check2 = True
        right = i

now = data[left][0]
data.sort(key=lambda z:z[1])
for i,x,y in enumerate(data):
    if i == left or i == right:continue
    now -= y
    if now < 0:
        check3 = False
        break
    now += x

print("Yes" if check1 and check2 and check3 else "No")

Submission status: Runtime Error

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():
    class Bit:
        def __init__(self, n):
            self.size = n
            self.tree = [0] * (n + 1)
    
        def sum(self, i):
            s = -(10 ** 18)  # -INF
            while i > 0:
                s = max(s, self.tree[i])
                i -= i & -i
            return s
    
        def add(self, i, x):
            while i <= self.size:
                self.tree[i] = max(x, self.tree[i])
                i += i & -i
    
    N=int(input())
    S=[input() for i in range(N)]
    P=0
    M=0
    c=0
    b=Bit(10**6)
    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:
            P+=p
        elif p==0 and m>0:
            M+=m
        elif p>0 and m>0:
            b.add(m,p-m+10**7)
            c+=1

    def nibutan(ok,ng,x):
        while abs(ok-ng) > 1:
            mid = (ok + ng) // 2
            if solve(mid,x):
                ok = mid
            else:
                ng = mid
        return ok
    
    def solve(mid,x):
        return b.sum(mid)==x
            
    for _ in range(c):
        x=b.sum(P)
        if x==0:
            print('No')
            exit()
        x-=10**7
        P+=x
        if P<0:
            print('No')
            exit()
        index=nibutan(0,P)
        b.add(index,-(x+10**7))
    P-=M
    YesNo(P==0)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))




n = int(input())
minsum = [None] * n # (min, sum)
for i in range(n):
    tmp = list(map(int, " ".join(input()).replace("(", "1").replace(")", "-1").split()))
    c = 0
    m = 0
    for item in tmp:
        c += item
        m = min(c, m)
    minsum[i] = (m, sum(tmp))
minsum.sort()
if sum(item[1] for item in minsum)!=0:
    print("No")
else:
    c = 0
    i = n-1
    while True:
        m, s = minsum[i]
        if m<0:
            break
        c += s
        i -= 1
        minsum.pop()
    minsum.sort(key=lambda x: x[1])
#     print(minsum, c)
    i = len(minsum)-1
    while minsum:
        m, s = minsum[i]
        if c+m>=0:
            minsum.pop(i)
            c += s
            i = len(minsum) - 1
        else:
            i -= 1
            if i<0:
                print("No")
                break
    else:
        print("Yes")

Submission status: Runtime Error

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,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(key == lambda x:x[2])
for i in brackets_minus:
    if i[0] + cur < 0:
        print("No")
        exit()
    cur += i[1]
print("Yes")

Submission status: Runtime Error

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:
    x = 10 / 0
    print("No")
    exit()
  cnt += x

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

Submission status: Runtime Error

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:
  x = 10 / 0
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
from scipy.sparse import csr_matrix, csgraph
N = int(input())
lefts, rights = [], []
count = 0
M = 0
unappearences = [1] * (10 ** 6 // N + 1)
for i in range(N):
    left, right = 0, 0
    for c in input():
        if c == "(":
            left += 1
        if c == ")":
            if left:
                left -= 1
            else:
                right += 1
    if any((left, right)):
        count += 1
        lefts.append(left)
        rights.append(right)
        unappearences[left] = 0
        unappearences[right] = 0
        M = max((M, left, right))
graph = csr_matrix(([1] * count, (lefts, rights)), shape=(M + 1, M + 1))
if (csgraph.connected_components(graph, return_labels=False) == 1 + sum(unappearences[:(M + 1)])):
    parity = [0, 0]
    for i in range(M + 1):
        parity[graph[i].sum() & 1] += 1
    print("Yes" if (parity[0] in [0, 2] and not parity[1] & 1) else "No")
else:
    print("No")

Submission status: Runtime Error

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(key = lambda x:(x[0],-x[1]))
Y = 0
for a,b in X:
    if a > Y:
        print(1/0)
        quit()
    Y -= a
    Y += b

if Y:
    print(1/0)
else:
    print("Yes")

Submission status: Runtime Error

Solution code:

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))




n = int(input())
minsum = [None] * n # (min, sum)
for i in range(n):
    tmp = list(map(int, " ".join(input()).replace("(", "1").replace(")", "-1").split()))
    c = 0
    m = 0
    for item in tmp:
        c += item
        m = min(c, m)
    minsum[i] = (m, sum(tmp))
minsum.sort()

if sum(item[1] for item in minsum)!=0:
    print("No")
else:
    c = 0
    i = n-1
    while True:
        m, s = minsum[i]
        if m<0:
            break
        c += s
        i -= 1
        minsum.pop()
    minsum.sort(key=lambda x: x[1])
#     print(minsum, c)
    i = len(minsum)-1
    while minsum:
        m, s = minsum[i]
        if c+m>=0:
            minsum.pop(i)
            c += s
            i = len(minsum) - 1
        else:
            i -= 1
            if i<0:
                print("No")
                break
    else:
        print("Yes")

Submission status: Runtime Error

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:
    if h>1:1/0
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import math
sys.setrecursionlimit(4100000)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
input=lambda :sys.stdin.readline().rstrip()
N=int(input())
S=[input() for i in range(N)]
lr=[]
for n in range(N):
    l=0
    r=0
    for i in range(len(S[n])):
        if S[n][i]=="(":
            l+=1
        else:
            if l>0:
                l-=1
            else:
                r+=1
    #print(l,r)
    if l or r:
        lr.append([l,r])
#lr.sort(key=lambda x:x[0]*x[1],reverse=True)
idleR=10**7
#print(lr)
L,R=lr[0]
stack=[[L,R]]
for n in range(1,len(lr)):
    #print(stack)
    L,R=lr[n]
    visited=set()
    nstack=[]
    while stack:
        l,r=stack.pop()
        for xl,xr in [[l+L-R,r],[l,r+R-L]]:
            if xl>=0 and xr>=0:
                X=xl+idleR*xr
                if not X in visited:
                    visited.add(X)
                    nstack.append([xl,xr])


    stack=nstack
#print(stack)
if not stack or [0,0] in stack:
    print("Yes")
else:
    print("No")

Submission status: Runtime Error

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:
    if a==b:1/0
    print('No')

Submission status: Runtime Error

Solution code:
def main():
    n = int(input())
    s = [list(input()) for _ in range(n)]
    L_cnt = []
    R_cnt = []
    LR_cnt = []
    min_l,min_r = 10**6,10**6
    for i in range(n):
        t = s[i]
        flag = 0
        l = 0
        r = 0
        for j in range(len(t)):
            if not flag and t[j] == ')':
                r += 1
            elif t[j] == '(':
                flag = 1
                l += 1
            else:
                l -= 1
                if l == 0:
                    flag = 0
        if r == 0 and l == 0:
            continue
        if r == 0:
            L_cnt.append(l)
        elif l == 0:
            R_cnt.append(r)
        else:
            LR_cnt.append([l,r])
            min_l = min(min_l,l)
            min_r = min(min_r,r)
    L,R = sum(L_cnt),sum(R_cnt)
    if not LR_cnt:
        if L == R:
            print('Yes')
            return
        else:
            print('No')
            return
    if not (L_cnt and R_cnt):
        print('No')
        return
    box1 = []
    box2 = []
    for i in range(len(LR_cnt)):
        if L >= LR_cnt[i][1] and LR_cnt[i][1] <= LR_cnt[i][0]:
            L += LR_cnt[i][0] - LR_cnt[i][1]
        elif LR_cnt[i][1] <= LR_cnt[i][0]:
            box1.append(LR_cnt[i])
        else:
            box2.append(LR_cnt[i])
    for i in range(len(box1)):
        L -= box1[i][1]
        if L < 0:
            print('No')
            return
        L += box1[i][0]
    for i in range(len(box2)):
        L -= box2[i][1]
        if L < 0:
            print('No')
            return
        L += box1[i][0]
    if L == R:
        print('Yes')
    else:
        print('No')
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

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:
    assert 0
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

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

x = 10 / 0
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: Runtime Error

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import math
sys.setrecursionlimit(4100000)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
input=lambda :sys.stdin.readline().rstrip()
N=int(input())
S=[input() for i in range(N)]
lr=[]
for n in range(N):
    l=0
    r=0
    for i in range(len(S[n])):
        if S[n][i]=="(":
            l+=1
        else:
            if l>0:
                l-=1
            else:
                r+=1
    #print(l,r)
    if l or r:
        lr.append([l,r])
#lr.sort(key=lambda x:x[0]*x[1],reverse=True)
idleR=10**7
#print(lr)
L,R=lr[0]
stack=[[L,R]]
for n in range(1,len(lr)):
    #print(stack)
    L,R=lr[n]
    visited=set()
    nstack=[]
    while stack:
        l,r=stack.pop()
        for xl,xr in [[l+L-R,r],[l,r+R-L]]:
            if xl>=0 and xr>=0:
                X=xl+idleR*xr
                if not X in visited:
                    visited.add(X)
                    nstack.append([xl,xr])


    stack=nstack
#print(stack)
if [0,0] in stack:
    print("Yes")
else:
    print("No")

Submission status: Runtime Error

Solution code:

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))


n = int(input())
minsum = [None] * n # (min, sum)
for i in range(n):
    tmp = list(map(int, " ".join(input()).replace("(", "1").replace(")", "-1").split()))
    c = 0
    m = 0
    for item in tmp:
        c += item
        m = min(c, m)
    minsum[i] = (m, sum(tmp))
minsum.sort()

if sum(item[1] for item in minsum)!=0:
    print("No")
else:
    c = 0
    i = n-1
    while True:
        m, s = minsum[i]
        if m<0:
            break
        c += s
        i -= 1
        minsum.pop()
    minsum.sort(key=lambda x: x[1])
#     print(minsum, c)
    i = len(minsum)-1
    update = False
    while minsum:
        m, s = minsum[i]
        if c+m>=0:
            minsum.pop(i)
            update = True
            c += s
        i -= 1
        if i<0:
            if not update:
                print("No")
                break
            i = len(minsum) - 1
    else:
        print("Yes")

Submission status: Runtime Error

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:
    assert 0
    print('No')

Submission status: Runtime Error

Solution code:
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
n=int(input())
l=[]
for i in range(n):
	s=input()
	stack=[]
	for i in range(len(s)):
		if s[i]=='(':
			stack.append('(')
		else:
			if len(stack)>0 and stack[-1]=='(':
				stack.pop()
			else:
				stack.append(')')
	if len(stack)>0:
		l.append(''.join(stack))
l.sort()
if len(l)==1:
	print('No')
else:
	stack=list(l[0])
	for s in l[1:]:
		for i in range(len(s)):
			if s[i]=='(':
				stack.append('(')
			else:
				if len(stack)>0 and stack[-1]=='(':
					stack.pop()
				else:
					stack.append(')')
	if len(stack)==0:
		print('Yes')
	else:
		print('No')

Submission status: Runtime Error

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(map(int,input().split())))

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: Runtime Error

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)

b_str = b_list[0]
for b in b_list[1:]:
    if 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: Runtime Error

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


def func(x):
    ret = []
    for i in range(len(x)):
        if len(ret) == 0:
            ret.append(x[i])
        else:
            if ret[-1] == '(' and x[i] == ')':
                ret.pop()
            else:
                ret.append(x[i])
    l = r = 0
    for i in range(len(ret)):
        if ret[i] == '(':
            l += 1
        else:
            r += 1
    return (r, l)  # ) (


t = []
for i in range(n):
    r, l = func(s[i])
    # print((r, l), '<-', s[i])
    if r + l == 0:
        continue
    t.append((r, l))
t.sort()
# print(*t, sep='\n')

is_possible = True
r, l = t[0]
if r != 0:
    is_possible = False
else:
    for i in range(1, len(t)):
        r_i, l_i = t[i]
        if r_i <= l:
            l -= r_i
            l += l_i
        else:
            is_possible = False
    if l != 0:
        is_possible = False

ans = 'Yes' if is_possible else 'No'
print(ans)