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

-----Sample Output-----
Yes

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

Difficulty: interview

Starter code:

Solutions:
#写経
#https://atcoder.jp/contests/abc167/submissions/13072107
import sys
readline = sys.stdin.readline

def resolve():
    N = int(readline())
    S = [readline().strip() for i in range(N)]
    L,R = [],[]
    D = []
    for s in S:
        l, r = 0, 0
        for c in s:
            if c == ')':
                if l > 0:
                    l -= 1
                else:
                    r += 1
            else:
                l += 1
        if l == 0 and r == 0:
            pass
        elif l == 0:
            R.append(r)
        elif r == 0:
            L.append(l)
        else:
            D.append((l, r))
    L = sum(L)
    R = sum(R)

    inc = []
    dec = []
    for l,r in D:
        if l > r:
            inc.append((l, r))
        else:
            dec.append((l, r))
    
    inc.sort(key=lambda x:x[1])
    dec.sort(key=lambda x:-x[1])
    
    D = inc + dec
    
    for i, (l,r) in enumerate(D):
        L -= r
        if L < 0:
            print('No')
            return
        L += l
    
    if L == R:
        print('Yes')
    else:
        print('No')
resolve()

from itertools import *
n,*s=open(0).read().split()
u=[[min(accumulate(t,lambda a,b: a+(1 if b=="(" else -1),initial=0)),2*t.count("(")-len(t)] for t in s]
m=0
for c,d in chain(sorted([x for x in u if x[1]>=0])[::-1],sorted([x for x in u if x[1]<0],key=lambda z:z[0]-z[1])):
    if m+c<0:print("No");break
    m+=d
else:print("No" if m else "Yes")

# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
    N = int(input())
    current = 0
    ways = []
    dic = {'(': 1, ')': -1}
    SS = read().split()

    for S in SS:
        path = [0]
        for s in S:
            path.append(path[-1]+ dic[s])
        ways.append((path[-1], min(path)))

    ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:(x[1], x[0]), reverse=True)
    ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[1] - x[0], -x[0]), reverse=True)[::-1]

    for i in range(len(ways_pos)):
        go, max_depth = ways_pos[i]
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

    for i in range(len(ways_neg)):
        go, max_depth = ways_neg[i]
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

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

def __starting_point():
    run()
__starting_point()

import sys
input = sys.stdin.readline

# up_list = []
# down_list = []


def count_scan(s):
    max_min = 0
    compare = 0
    for c in s:
        if c == '(':
            compare += 1
        elif c == ')':
            compare -= 1
            max_min = min(max_min, compare)
    return min(max_min, compare), compare


def key(lst):
    m, c = lst
    if c > 0:
        return 1, m
    else:
        return -1, c - m


def main():
    n = int(input())
    lst = [input() for _ in range(n)]

    # up_list.sort(key=lambda x: x[1], reverse=True)
    # down_list.sort(key=lambda x: x[1], reverse=False)
    txt = 'No'
    ans = 0
    # print(lst)
    # print(sorted([count_scan(lst) for i in lst],
                #  reverse=True,
                #  key=key))
    for max_min, c in sorted([count_scan(s) for s in lst],
                             reverse=True,
                             key=key):
        # print(f"{max_min = }, {c = }, {ans = }")
        if max_min + ans < 0:
            break
        ans += c
    else:
        if ans == 0:
            txt = 'Yes'

    print(txt)


def __starting_point():
    main()
__starting_point()

n=int(input())
po,ne=[],[]
now=0
for i in range(n):
    p=0
    mp=0
    for j in input():
        p+=(1,-1)[j==")"]
        mp=min(p,mp)
    if mp:
        if p>=0:
            po.append((mp,p))
        else:ne.append((mp-p,-p))
    else:now+=p
po.sort(reverse=1)
ne.sort(reverse=1)
for m,p in po:
    if m+now<0:print("No");return
    else:now+=p
nnow=0
for m,p in ne:
    if m+nnow<0:print("No");return
    else:nnow+=p
print("Yes" if now==nnow else "No") 


def f():
    N = int(input())
    UP = []
    DOWN = []

    for _ in range(N):
        S = input()
        c = 0
        minC = 0

        for s in S:
            if s == '(':
                c += 1
            else:
                c -= 1
                minC = min(minC, c)

        if c >= 0:
            UP.append((minC, c))
        else:
            DOWN.append((c - minC, c))


    c = 0
    for up in sorted(UP, reverse=True):
        if c + up[0] < 0:
            return False

        c += up[1]

    for down in sorted(DOWN, reverse=True):
        if c + down[1] - down[0] < 0:
            return False

        c += down[1]

    if c != 0:
        return False

    return True


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


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

xs1total = 0 # ((
xs2 = [] # )((
xs3 = [] # ))(
xs4total = 0 # ))

for s in S:
    n = 0
    m = 0
    for c in s:
        if c == "(":
            n += 1
        elif c == ")":
            n -= 1
            m = min(m, n)
    k = n - m
    if m == 0 and k == 0:
        continue
    elif m == 0:
        xs1total += k
    elif k == 0:
        xs4total += -m
    else:
        if -m < k:
            xs2.append((-m, k))
        else:
            xs3.append((-m, k))

xs2.sort()
xs3.sort(key=lambda x:-(x[1] - x[0]))

def check(xs1total, xs2, xs3, xs4total):
    t = xs1total
    for x in xs2:
        if t < x[0]:
            return False
        t = t - x[0] + x[1]
    for x in xs3:
        if t < x[0]:
            return False
        t = t - x[0] + x[1]
    return t == xs4total

#print(xs1total, xs2, xs3, xs4total)

if check(xs1total, xs2, xs3, xs4total):
    print("Yes")
else:
    print("No")


import sys

input = sys.stdin.readline

def check(s):
    h = 0
    for p in s:
        b = h + p[0]
        if b < 0: return False
        h += p[1]
    return True

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

total = 0
ps, ms = [], []
for s in S:
    h, b = 0, 0
    for c in s:
        if c == '(':
            h += 1
        else:
            h -= 1
        b = min(b, h)
    if h > 0:
        ps.append([b, h])
    else:
        ms.append([b-h, -h])
    total += h

ps.sort(reverse=True)
ms.sort(reverse=True)
if check(ps) and check(ms) and total == 0:
    print('Yes')
else:
    print('No')

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

xs1total = 0 # ((
xs2 = [] # )((
xs3 = [] # ))(
xs4total = 0 # ))

for s in S:
    n = 0
    m = 0
    for c in s:
        if c == "(":
            n += 1
        elif c == ")":
            n -= 1
            m = min(m, n)
    k = n - m
    if m == 0 and k == 0:
        continue
    elif m == 0:
        xs1total += k
    elif k == 0:
        xs4total += -m
    else:
        if -m < k:
            xs2.append((-m, k))
        else:
            xs3.append((-m, k))

xs2.sort()
xs3.sort(key=lambda x:-x[1])

def check(xs1total, xs2, xs3, xs4total):
    t = xs1total
    for x in xs2:
        if t < x[0]:
            return False
        t = t - x[0] + x[1]
    for x in xs3:
        if t < x[0]:
            return False
        t = t - x[0] + x[1]
    return t == xs4total

#print(xs1total, xs2, xs3, xs4total)

if check(xs1total, xs2, xs3, xs4total):
    print("Yes")
else:
    print("No")


#abc167_e

n = int(input())

pos = []
neg = []

for _ in range(n):
    s = input()
    low_pos = 0
    increase= 0
    for v in s:
        if v=="(":
            increase += 1
        else:
            increase -= 1
            low_pos = min(low_pos, increase)
    
    if increase >= 0:
        pos.append((low_pos, increase))
    else:
        #reverse left from right
        low_pos, increase =  low_pos - increase, -increase        
        neg.append((low_pos, increase))
    
pos.sort()
pos.reverse() #lowが高い順にする.
neg.sort()
neg.reverse() #lowが高い順にする.

now_pos = 0
for low_pos, increase in pos:
    if now_pos + low_pos < 0:
        print("No")  #impossible
        return
    else:
        now_pos += increase

right_pos = 0       
for low_pos, increase in neg:
    if right_pos + low_pos < 0:
        print("No")  #impossible
        return
    else:
        right_pos += increase

if right_pos != now_pos:
    print("No")
    return
else:
    print("Yes")

import cython
 
def main():
    import sys
    readline = sys.stdin.readline
    
    N: cython.longlong
    N = int(readline())
    S = [readline().strip() for i in range(N)]
    
    D = []
    L, R = [], []
    for s in S:
        l: cython.longlong = 0
        r: cython.longlong = 0
        for c in s:
            if c == ')':
                if l > 0: l -= 1
                else: r += 1
            else: l += 1
        if l == 0 and r == 0:pass
        elif l == 0: R.append(r)
        elif r == 0: L.append(l)
        else: D.append((l, r))
    
    L: cython.longlong
    R: cython.longlong
    L = sum(L)
    R = sum(R)
    
    inc = []
    dec = []
    for l, r in D:
        if l > r:
            inc.append((l, r))
        else:
            dec.append((l, r))
    
    inc.sort(key=lambda x:x[1])
    dec.sort(key=lambda x:-x[1])
    
    D = inc + dec
    
    l: cython.longlong
    r: cython.longlong
    for _, (l,r) in enumerate(D):
        L -= r
        if L < 0:
            print('No')
            return
        L += l
    
    if L == R:
        print('Yes')
    else:
        print('No')
 
def __starting_point():
    main()
__starting_point()

n = int(input())
scop = [] #高低差,min値
scom = []
ssum = 0

for i in range(n):
    s = input()
    sa = 0
    ms = 0
    for i in range(len(s)):
        if s[i] == "(":
            sa += 1
        else:
            sa -= 1
        if ms > sa:
            ms = sa
    if sa > 0:
        scop.append([ms,sa])
    elif not sa == ms:
        scom.append([ms,sa])
    ssum += sa

if not ssum == 0:
    print("No")
    return

scop.sort(reverse = True)
scom.sort()

now = 0
for i in scop:
    if now + i[0] < 0:
        print("No")
        return
    now += i[1]
for i in scom:
    if now + i[0] < 0:
        print("No")
        return
    now += i[1]

print("Yes")


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

first_list = []
last_list = []
first = ""
last = ""
for i in range(n):
    s = slist[i]

    a_count = 0
    b_count = 0
    min_s = ""
    for c in s:
        if c == ")":
            b_count-=1
        else:
            b_count+=1
        if b_count < 0:
            b_count = 0
            a_count+= 1
    min_s = ")"* a_count + "("*b_count

    ai = a_count
    bi = b_count

    if ai == 0:
        first += min_s
    elif bi == 0:
        last += min_s
    elif bi-ai >= 0:
        first_list.append([min_s,ai])
    else:
        last_list.append([min_s,bi])

first_list= sorted(first_list, key=lambda s: s[1])
last_list= sorted(last_list, key=lambda s: s[1], reverse=True)

ans = first
for i in range(len(first_list)):
    ans += first_list[i][0]
for i in range(len(last_list)):
    ans += last_list[i][0]
ans += last

a_count = 0
b_count = 0
min_s = ""
for c in ans:
    if c == ")":
        b_count-=1
    else:
        b_count+=1
    if b_count < 0:
        b_count = 0
        a_count+= 1

if a_count == 0 and b_count == 0:
    print("Yes")
else:
    print("No")

import sys
def input(): return sys.stdin.readline().rstrip()

n = int(input())
ls, rs = [], []
total = 0
for i in range(n):
    s = input()
    h, b = 0, 0
    for c in s:
        if c=='(':  h += 1
        else:       h -= 1
        b = min(b, h)
    if h > 0:   ls.append((b, h))       # 増減+ はb:最下点, h:増減を取る
    else:       rs.append((b-h, -h))    # 増減- は、上下左右逆さに考え、b:右から見た最下点、h:増減のマイナスを取る
    total += h
ls.sort(reverse=True)
rs.sort(reverse=True)   # 増減-は右から見るので、大きい順にsort

def chk(s):
    h = 0
    for sb, sh in s:
        b = h + sb
        if b < 0: return False
        h += sh
    return True

if (chk(ls) and chk(rs) and total==0):
    print("Yes")
else:
    print("No")

N, *S = open(0)

L = [s.count("(") for s in S]
R = [s.count(")") for s in S]

X = sorted(((s[:-1], r) for s, l, r in zip(S, L, R) if l - r >= 0), key=lambda x: x[1])
Y = sorted(((s[:-1], l) for s, l, r in zip(S, L, R) if l - r < 0), key=lambda x: -x[1])

cnt = 0
for s, _ in X + Y:
    for si in s:
        cnt += 1 if si == "(" else -1
        if cnt < 0:
            print("No")
            return

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

import sys
input=lambda: sys.stdin.readline().rstrip()

N = int(input())

S_p = []
S_n = []

for i in range(N):
  end = 0
  mim = 0
  for c in input():
    if c == "(":
      end += 1
    else :
      end -= 1
    mim = min(mim,end)
  
  if end >= 0:
    S_p.append([mim, end])
  else:
    S_n.append([end-mim, end])
  
S_p.sort(reverse=True)
S_n.sort(reverse=True)
#print(S_p)
#print(S_n)

check = 0
flag = True
for i in range(len(S_p)):
  if check + S_p[i][0] >= 0:
    check += S_p[i][1]
  else:
    flag = False
    break
  #print(check)
  
for i in range(len(S_n)):
  if check + S_n[i][1] - S_n[i][0] >= 0:
    check += S_n[i][1]
  else:
    flag = False
    break
  #print(check)
  
if check == 0 and flag:
  flag = True
else:
  flag = False

print("Yes" if flag else "No")

def main():
    from sys import stdin
    input = stdin.readline
    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.strip('\n'):
            if i == "(":
                now += 1
            else:
                now -= 1
            m = min(m, now)
        temp = [-m, (s.count("(")-s.count(")"))-m]
        if temp[0] < temp[1]:
            s2.append(temp)
        else:
            s3.append(temp)
    s2.sort(key=lambda x: (x[0]))
    s3.sort(key=lambda x: (-x[1]))
    cnt = 0
    for i, j in s2:
        cnt -= i
        if cnt < 0:
            print("No")
            return
        cnt += j
    for i, j in s3:
        cnt -= i
        if cnt < 0:
            print("No")
            return
        cnt += j
    if cnt != 0:
        print("No")
        return
    print("Yes")


main()


import sys


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


def solve():
    N = int(input())
    inc_chunks = []
    dec_chunks = []
    for _ in range(N):
        depth = 0
        level = 0
        for c in input():
            if c == '(':
                level += 1
            else:
                level -= 1
                depth = min(depth, level)
        if depth >= 0 and level == 0:
            continue
        elif level > 0:
            inc_chunks.append((depth, level))
        else:
            dec_chunks.append((depth - level, -level))

    inc_chunks.sort(reverse=True)
    dec_chunks.sort(reverse=True)
    inc_level = 0
    for depth, level in inc_chunks:
        if inc_level + depth < 0:
            return 'No'
        inc_level += level
    dec_level = 0
    for depth, level in dec_chunks:
        if dec_level + depth < 0:
            return 'No' 
        dec_level += level
    if inc_level != dec_level:
        return 'No'
    return 'Yes'


print((solve()))


import sys
input = sys.stdin.readline
n = int(input())
chk = []
res = []
for i in range(n):
  s = input().strip()
  m = 0
  e = 0
  for i in s:
    if i == ')':
      e -= 1
      m = min(m,e)
    else:
      e += 1
  if e >= 0:
    chk.append((m,e))
  else:
    res.append((-1*e+m,-1*e))
  
from operator import itemgetter
res.sort(key=itemgetter(0),reverse=True)
chk.sort(key=itemgetter(0),reverse=True)
ans = 'Yes'
st = 0
for i,j in chk:
  if i+st < 0:
    ans = 'No'
    break
  st += j
  
sr = 0
for i,j in res:
  if i+sr < 0:
    ans = 'No'
    break
  sr += j
  
if st != sr:
  ans = 'No'

print(ans)

N = int(input())
G2,G4 = [],[]
cnt2 = 0
cnt3 = 0
for _ in range(N):
    S = input()
    MIN = 0
    cnt = 0
    for s in list(S):
        if s == '(':
            cnt += 1
        else:
            cnt -= 1
        MIN = min(MIN,cnt)
    if MIN == 0 and cnt >= 0:
        cnt2 += cnt
    if MIN < 0 and cnt >= 0:
        G2.append([MIN,cnt])
    if MIN == cnt and cnt < 0:
        cnt3 += cnt
    if MIN < cnt and cnt < 0:
        G4.append([MIN,cnt])


G2.sort(reverse=True)
for L in G2:
    if cnt2 + L[0] < 0:
        print('No')
        return
    else:
        cnt2 += L[1]
for L in G4:
    if cnt2 + L[0] < 0:
        print('No')
        return
    else:
        cnt2 += L[1]

cnt2 += cnt3

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


def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    n = int(input())
    lx = []
    rx = []
    for i in range(n):
        a = 0
        cnt = 0
        for j in input():
            if j == '(':
                cnt += 1
            else:
                cnt -= 1
            a = min(a, cnt)
        
        if cnt >= 0:
            lx.append((a, cnt))
        else:
            rx.append((a, cnt))
    lx.sort(key= lambda x: -x[0]) # -aの昇順
    rx.sort(key= lambda x: x[0]-x[1]) # -bの昇順(bの降順)
    total = 0
    check = True
    for x,cnt in (lx+rx):
        if total + x < 0:
            check = False
            break
        total += cnt
    if total == 0 and check:
        print('Yes')
    else:
        print("No")
    




def __starting_point():
    main()
__starting_point()

import sys
# input = sys.stdin.readline


def parse(s):
    bottom = 0
    delta = 0
    for c in s:
        delta += (1 if c == "(" else -1)
        bottom = min(bottom, delta)
    return bottom, delta


def compute(pars):
    pars.sort(reverse=True)
    h = 0
    for bottom, delta in pars:
        if h + bottom < 0:
            print("No")
            return
        h += delta
    return h


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

    incs = []
    decs = []
    for _ in range(N):
        bottom, delta = parse(input())
        if delta > 0:
            incs.append((bottom, delta))
        else:
            decs.append((bottom-delta, -delta))

    inc_tot = compute(incs)
    dec_tot = compute(decs)
    if inc_tot == dec_tot:
        print("Yes")
    else:
        print("No")


def __starting_point():
    main()

__starting_point()

from itertools import *
n,*s=open(0).read().split()
u=[[min(accumulate(chain([0],t),lambda a,b: a+(1 if b=="(" else -1))),2*t.count("(")-len(t)] for t in s]
m=0
for c,d in chain(sorted([x for x in u if x[1]>=0])[::-1],sorted([x for x in u if x[1]<0],key=lambda z:z[0]-z[1])):
    if m+c<0:print("No");break
    m+=d
else:print("No" if m else "Yes")

import sys
input = sys.stdin.readline

n = int(input())
cnt = 0
decrement = 0
profit = []
loss = []

for _ in range(n):
    s = input().rstrip()
    min_p = 0
    end_p = 0
    point = 0
    for c in s:
        if c == '(':
            point += 1
        elif c == ')':
            point -= 1
            if point < min_p:
                min_p = point
    else:
        end_p = point
    if 0 <= min_p:
        cnt += end_p
    else:
        if min_p == end_p:
            decrement += end_p
        else:
            if 0 <= end_p:
                profit.append((min_p, end_p))
            else:
                loss.append((min_p, end_p))



profit.sort()
while profit:
    min_p, end_p = profit.pop()
    if cnt+min_p < 0:
        print('No')
        return
    cnt += end_p


loss.sort(reverse=True)
while loss:
    min_p, end_p = loss.pop()
    if cnt+min_p < 0:
        print('No')
        return
    cnt += end_p

print(('Yes' if cnt+decrement == 0 else 'No'))


def check(vec):
    if len(vec) == 0:
        return True
    h = 0
    for v in sorted(vec, reverse=True):
        if h + v[0] < 0:
            return False
        h += v[1]
    return True


def parse(brackets):
    m = 0
    f = 0
    for c in brackets:
        if c == "(":
            f += 1
        else:
            f -= 1
        if m > f:
            m = f
    return m, f


def main():
    N = int(input())
    ls = []
    rs = []
    tot = 0
    for _ in range(N):
        m, f = parse(input().strip())
        tot += f
        if f >= 0:
            ls.append([m, f])
        else:
            rs.append([m-f, -f])
    return tot == 0 and check(ls) and check(rs)


def __starting_point():
    print(("Yes" if main() else "No"))

__starting_point()

import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: list(map(int, input().split()))
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    # 10**6
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     # 10**6
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp

#

class UnionFindEx:
    def __init__(self, size):
        #正なら根の番号、負ならグループサイズ
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   #負なら根
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    #サイズ更新
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'


def main():
    N=ii()
    up = []
    down = []
    for _ in range(N):
        S = input()
        h = 0
        b = 0
        for s in S:
            if s=='(':
                h += 1
            else:
                h -= 1
                b = min(b, h)
        #
        if h>=0:
            up.append((h, b))
        else:
            down.append((h, b))
    #
    up.sort(key=lambda t: t[1], reverse=True)
    down.sort(key=lambda t: t[0]-t[1], reverse=True)
    H = 0
    for h, b in up:
        if H+b>=0:
            H += h
        else:
            print(No)
            return
    for h, b in down:
        if H+b>=0:
            H += h
        else:
            print(No)
            return
    #
    if H == 0:
        print(Yes)
    else:
        print(No)





main()




from functools import reduce
n, *s = open(0).read().split()
u = []
for t in s:
    close_cnt = 0
    tmp = 0
    for c in t:
        tmp += (1 if c == '(' else -1)
        close_cnt = min(close_cnt, tmp)
    u.append((close_cnt, tmp - close_cnt))
M = 10**6 + 1
acc = 0
for a, b in sorted([x for x in u if sum(x) >= 0], key=lambda z: -z[0]):
    if acc + a < 0:
        print("No")
        return
    else:
        acc += a + b
for a, b in sorted([x for x in u if sum(x) < 0], key=lambda z: -z[1]):
    if acc + a < 0:
        print("No")
        return
    else:
        acc += a + b
print(("No" if acc else "Yes"))

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

pos = []
neg = []
for s in S:
    sm = 0
    mn = 0
    for c in s:
        if c=='(':
            sm += 1
        else:
            sm -= 1
            mn = min(mn, sm)
    if sm >= 0:
        pos.append((mn,sm))
    else:
        neg.append((mn-sm, -sm))

pos.sort(key=lambda x:-x[0])
neg.sort(key=lambda x:-x[0])

hp = 0
for m,s in pos:
    if hp + m < 0:
        print('No')
        return
    hp += s

hn = 0
for m,s in neg:
    if hn + m < 0:
        print('No')
        return
    hn += s

print('Yes' if hp==hn else 'No')

# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
    N = int(input())
    current = 0
    ways = []
    dic = {'(': 1, ')': -1}
    SS = read().split()

    for S in SS:
        path = [0]
        for s in S:
            path.append(path[-1]+ dic[s])
        ways.append((path[-1], min(path)))

    ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:x[1], reverse=True)
    ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[0] - x[1]), reverse=True)

    idx = list(range(len(ways_pos)))



    for go, max_depth in ways_pos:
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None


    tmp =[]
    for go, max_depth in ways_neg:
        if current + max_depth >= 0:
            current += go
        else:
            tmp.append((go, max_depth))

    for go, max_depth in tmp:
        if current + max_depth >= 0:
            current += go
        else:
            print('No')
            return None


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

def __starting_point():
    run()
__starting_point()

import sys
input = sys.stdin.readline

n=int(input())
s=[input().strip("\n") for _ in range(n)]
p=[];m=[]
for si in s:
    cnt=0;a=0;b=0
    for i in range(len(si)):
        if si[i]==")":
            cnt+=1
        else:
            cnt-=1
        a=max(a,cnt)
    cnt=0
    for i in range(len(si)-1,-1,-1):
        if si[i]=="(":
            cnt+=1
        else:
            cnt-=1
        b=max(b,cnt)
    if b-a>=0:
        p.append((a,si))
    else:
        m.append((-b,si))
p.sort();m.sort()
ss=""

for _,si in p:
    ss+=si
for _,si in m:
    ss+=si
cnt=0
for i in range(len(ss)):
    if ss[i]=="(":
        cnt+=1
    else:
        cnt-=1
    if cnt<0:
        print("No")
        return
if cnt:
    print("No")
else:
    print("Yes")



# F

N = int(input())

list_plus = []
list_minus = []
for i in range(N):
    S = input()
    state = 0
    min_state = 0
    for s in S:
        if s == '(':
            state += 1
        else:
            state -= 1
        min_state = min(min_state, state)
    
    if state > 0:
        list_plus.append((min_state, state))
    else:
        list_minus.append((min_state - state, -state))

def compute(arr):
    total_state = 0
    for min_state, state in arr[::-1]:
        if total_state + min_state < 0:
            print('No')
            return
        total_state += state
    return total_state

list_plus.sort()
total_state_plus = compute(list_plus)
list_minus.sort()
total_state_minus = compute(list_minus)

print('Yes' if total_state_plus == total_state_minus else 'No')

# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
    N = int(input())
    current = 0
    ways = []
    dic = {'(': 1, ')': -1}
    SS = read().split()

    for S in SS:
        path = [0]
        for s in S:
            path.append(path[-1]+ dic[s])
        ways.append((path[-1], min(path)))

    ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:(x[1], x[0]), reverse=True)
    ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[1] - x[0], -x[0]), reverse=True)[::-1]

    for go, max_depth in ways_pos:
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

    for go, max_depth in ways_neg:
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

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

def __starting_point():
    run()
__starting_point()

import sys
input = sys.stdin.readline

def main():
  n = int(input())
  
  a = []
  b = []
  for i in range(n):
    s = input()
    c1, c2 = 0, 0
    for i in range(len(s)):
      if s[i] == "(":
        c2 += 1
      if s[i] == ")":
        if c2:
          c2 -= 1
        else:
          c1 += 1
    if c1 >= c2:
      b.append((c2, c1))
    else:
      a.append((c1, c2))
  a.sort()
  b.sort(reverse=True)
  ans = False
  sub = 0
  for value in a:
    k1, k2 = value[0], value[1]
    if sub < k1:
      ans = True
      break
    sub += k2-k1
  for value in b:
    k2, k1 = value[0], value[1]
    if ans or sub < k1:
      ans = True
      break
    sub += k2-k1
  print("No" if ans or sub else "Yes")

def __starting_point():
  main()
__starting_point()

import sys
n=int(input())
jsum=0
gjlist=[]
ejlist=[]
esum=0

def jouka(t):
	nonlocal jsum
	nonlocal gjlist
	nonlocal ejlist
	nonlocal esum
	
	tmpj=0
	tmpe=0
	
	for i in range(len(t)):
		if t[i] == "(":
			tmpj += 1
		else:
			if tmpj == 0:
				tmpe +=1
			else:
				tmpj -=1
		
	if tmpe == 0:
		jsum += tmpj
	elif tmpj == 0:
		esum += tmpe
	elif tmpj > tmpe:
		gjlist.append([tmpe,tmpj])
	else:
		ejlist.append([tmpe,tmpj])

for j in range(n):
	jouka(input())

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

streak=jsum
for gj in gjlist:
	if gj[0] > streak:
		print("No")
		return
	else:
		streak += gj[1]-gj[0]

for ej in ejlist:
	if ej[0] > streak:
		print("No")
		return
	else:
		streak += ej[1]-ej[0]

if streak == esum:
	print("Yes")
else:
	print("No")





import sys
readline = sys.stdin.readline

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

def count_cb_ob(s):
    st = []
    for i, si in enumerate(s):
        if si == '(' or len(st) == 0 or st[-1] != '(':
            st.append(si)
        else:
            st.pop()
    return st.count(')'), st.count('(')

cb_obs = map(count_cb_ob, S)
f, b, s = [], [], []
for down, up in cb_obs:
    (f if down < up else (s if down == up else b)).append((down, up))

f = sorted(f)
b = sorted(b, key=lambda x:x[1], reverse=True)

count = 0
ans = 'Yes'
for down, up in (*f, *s, *b):
    count -= down
    if count < 0:
        ans = 'No'
    count += up

if count != 0:
    ans = 'No'

print(ans)

from operator import itemgetter
N = int(input())

def checkNonnegative(brankets):
    curup = 0
    for (minup , up) in sorted(brankets , key= itemgetter(0) , reverse = True):
        if curup + minup < 0:
            return False
        curup += up
    return True

def canArrangeBranket(brankets):
    totup = 0
    left_brankets = []
    right_brankets = []
    for branket in brankets:
        up = 0
        minup = 0
        for c in list(branket):
            if c == '(':
                up += 1
            else:
                up -= 1
                minup = min(minup , up)
        totup += up
        if up >= 0:
            left_brankets.append((minup , up))
        else:
            right_brankets.append((minup - up , - up))
    if totup != 0:
        return False
    return checkNonnegative(left_brankets) and checkNonnegative(right_brankets)

branketList = []
for i in range(N):
    l = input()
    branketList.append(l)

if canArrangeBranket(branketList):
    print("Yes")
else:
    print("No")


def check(ar):
    h = 0
    for bottom, up in ar:
        if h + bottom < 0:
            return False
        h += up
    return True


def __starting_point():
    N = int(input())
    pos = []
    neg = []
    equal = 0
    for _ in range(N):
        cnt = 0
        bottom = 0
        for s in input():
            if s == "(":
                cnt += 1
            else:
                cnt -= 1
            bottom = min(bottom, cnt)
        equal += cnt
        if cnt >= 0:
            pos.append((bottom, cnt))
        else:
            cnt = -cnt
            bottom += cnt
            neg.append((bottom, cnt))

    pos.sort(reverse=True)
    neg.sort(reverse=True)
    if check(pos) and check(neg) and equal == 0:
        print("Yes")
    else:
        print("No")
__starting_point()

def count_scan(s):
    max_min = 0
    compare = 0
    for c in s:
        if c == '(':
            compare += 1
        elif c == ')':
            compare -= 1
            max_min = min(max_min, compare)
    return min(max_min, compare), compare
 
 
def key(lst):
    m, c = lst
    if c > 0:
        return 1, m
    else:
        return -1, c - m
 
 
def main():
    n = int(input())
    lst = [input() for _ in range(n)]
 
    txt = 'No'
    ans = 0
    for max_min, c in sorted([count_scan(s) for s in lst],
                             reverse=True,
                             key=key):
        if max_min + ans < 0:
            break
        ans += c
    else:
        if ans == 0:
            txt = 'Yes'
 
    print(txt)
  
def __starting_point():
    main()


__starting_point()

n = int(input())
ls, rs = [], []

def check(sl):
    h = 0
    for t in sl:
        b = h + t[0]
        if b < 0:
            return False
        h += t[1]
    return True

total = 0
for i in range(n):
    b, h = 0, 0
    S = input()
    for s in S:
        if s == '(':
            h += 1
        else:
            h -= 1
        b = min(b, h)
    if h > 0:
        ls.append((b, h))
    else:
        rs.append((b - h, -h))
    total += h
ls.sort(key=lambda x: x[0], reverse=True)
rs.sort(key=lambda x: x[0], reverse=True)
print('Yes' if check(ls) and check(rs) and total == 0 else 'No')

import sys
# input = sys.stdin.readline
input = lambda: sys.stdin.readline().rstrip()

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


def bracket(x):
    # f: final sum of brackets '(':+1, ')': -1
    # m: min value of f
    f = m = 0
    for i in range(len(x)):
        if x[i] == '(':
            f += 1
        else:
            f -= 1
        m = min(m, f)
    # m <= 0
    return f, m


l1 = []
l2 = []
for i in range(n):
    fi, mi = bracket(s[i])
    if fi >= 0:
        l1.append((fi, mi))
    else:
        l2.append((fi, mi))

l1.sort(key=lambda x: -x[1])
l2.sort(key=lambda x: -(x[0] - x[1]))
l = l1 + l2
v = 0
for fi, mi in l:
    if v + mi >= 0:
        v += fi
    else:
        v = -1
        break

ans = 'Yes' if v == 0 else 'No'
print(ans)


import sys
# input = sys.stdin.readline
input = lambda: sys.stdin.readline().rstrip()

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


def bracket(x):
    # f: final sum of brackets '(':+1, ')': -1
    # m: min value of f
    f = m = 0
    for i in range(len(x)):
        if x[i] == '(':
            f += 1
        else:
            f -= 1
        m = min(m, f)
    # m <= 0
    return f, m


def func(l):
    # l = [(f, m)]
    l.sort(key=lambda x: -x[1])
    v = 0
    for fi, mi in l:
        if v + mi >= 0:
            v += fi
        else:
            return -1
    return v


l1 = []
l2 = []
for i in range(n):
    fi, mi = bracket(s[i])
    if fi >= 0:
        l1.append((fi, mi))
    else:
        l2.append((-fi, mi - fi))

v1 = func(l1)
v2 = func(l2)
if v1 == -1 or v2 == -1:
    ans = 'No'
else:
    ans = 'Yes' if v1 == v2 else 'No'

print(ans)


def main():
    N = int(input())
    up_lines = []
    down_lines = []
    for i in range(N):
        s = input()
        height = 0
        bottom = 0
        for c in s:
            if c == "(":
                height += 1
            else:
                height -= 1
                bottom = min(bottom, height)
        if height > 0:
            up_lines.append((bottom, height))
        else:
            down_lines.append((bottom-height, -height))
    up_lines.sort(reverse=True, key=lambda line: line[0])
    down_lines.sort(reverse=True, key=lambda line: line[0])
    left = 0
    for bottom, height in up_lines:
        if left + bottom < 0:
            print("No")
            return
        left += height
    right = 0
    for bottom, height in down_lines:
        if right + bottom < 0:
            print("No")
            return
        right += height
    if left == right:
        print("Yes")
    else:
        print("No")


def __starting_point():
    main()

__starting_point()

import bisect

n=int(input())
opens=0
closes=0
ls=[]
rs=[]
for _ in range(n):
  s=input()
  cnt1=0
  cnt2=0
  for i in range(len(s)):
    if s[i]=='(':
      cnt1+=1
    else:
      if cnt1==0:
        cnt2+=1
      else:
        cnt1-=1
  if cnt2==0:
    opens+=cnt1
  elif cnt1==0:
    closes+=cnt2
  else:
    ls.append(cnt2)
    rs.append(cnt1)
ls=sorted(ls)
rs=sorted(rs)
lefts=sum(ls)
rights=sum(rs)
if opens-closes!=lefts-rights:
  print('No')
else:
  flag=False
  if len(ls)==0:
    flag=True
  for a in ls:
    if opens<a or closes<a+(rights-lefts):
      continue
    pos=bisect.bisect_right(rs,a+(rights-lefts))
    if pos!=0:
      flag=True
      break
  for d in rs:
    if opens<d+(lefts-rights) or closes<d:
      continue
    pos=bisect.bisect_right(ls,d+(lefts-rights))
    if pos!=0:
      flag=True
      break
  if flag==True:
    print('Yes')
  else:
    print('No')

# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
    N = int(input())
    current = 0
    ways = []
    dic = {'(': 1, ')': -1}
    SS = read().split()

    for S in SS:
        path = [0]
        for s in S:
            path.append(path[-1]+ dic[s])
        ways.append((path[-1], min(path)))

    ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:x[0], reverse=True)
    ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[0] - x[1]), reverse=True)

    tmp = []
    for go, max_depth in ways_pos:
        if current + max_depth >= 0:
            current += go
        else:
            tmp.append((go, max_depth))

    for go, max_depth in tmp:
        if current + max_depth >= 0:
            current += go
        else:
            print('No')
            return None

    tmp =[]
    for go, max_depth in ways_neg:
        if current + max_depth >= 0:
            current += go
        else:
            tmp.append((go, max_depth))

    for go, max_depth in tmp:
        if current + max_depth >= 0:
            current += go
        else:
            print('No')
            return None


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

def __starting_point():
    run()
__starting_point()

# 折れ線グラフで考えると
# ( : +1
# ) : -1
# 0で終わる
# 0未満にならない → 各文字列で最下点と和を利用
# 和がマイナスの部分と分けて、マイナス部分は反転して考える

import sys
input = sys.stdin.readline

n = int(input())
s = [input().strip() for _ in range(n)]
plus = []
minus = []
for i in s:
    min_v = 0
    sum_v = 0
    for j in i:
        sum_v += 1 if j == '(' else -1
        min_v = min(min_v, sum_v)
    if sum_v > 0:
        plus.append((min_v, sum_v))
    else:
        minus.append((min_v-sum_v, -sum_v))

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

sum_plus = 0
for min_v, sum_v in plus:
    if sum_plus + min_v < 0:
        print("No")
        return
    sum_plus += sum_v

sum_minus = 0
for min_v, sum_v in minus:
    if sum_minus + min_v < 0:
        print("No")
        return
    sum_minus += sum_v

if sum_plus == sum_minus:
    print("Yes")
else:
    print("No")





import sys
from operator import itemgetter
N = int(input())
S = sys.stdin.read().split()
HT_high = []
HT_low = []
for s in S:
    t = 0
    h = 0
    for c in s:
        if c == "(":
            h += 1
        else:
            h -= 1
            if h < t:
                t = h
    if h >= 0:
        HT_high.append((h, t))
    else:
        HT_low.append((h, t))
HT_high.sort(key=itemgetter(1), reverse=True)
HT_low.sort(key=lambda x: x[0]-x[1], reverse=True)
h0 = 0
for h, t in HT_high + HT_low:
    if h0 + t < 0:
        print("No")
        return
    h0 += h
if h0 != 0:
    print("No")
else:
    print("Yes")


N = int(input())
As = []
Bs = []

for _ in range(N):
  c = 0
  m = 0
  for s in input():
    if s == '(':
      c += 1
    elif s == ')':
      c -= 1
    m = min(m, c)
  if c >= 0:
    As.append((-m, c - m))
  else:
    Bs.append((-m, c - m))

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

f = True
c = 0
for (l, r) in As:
  if c < l:
    f = False
    break
  c += r - l
if f:
  for (l, r) in Bs:
    if c < l:
      f = False
      break
    c += r - l

f = f and (c == 0)

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

N = int(input())

tleft = 0
tright = 0
a = []
b=  []
for _ in range(N):
  s = input()
  left = 0
  lmin = 0
  for c in s:
    if c == "(":
      left += 1
    else: # ")"
      left -= 1
      lmin = min(lmin,left)
  #
  if left >= 0:
    if lmin == 0:
      tleft += left
    else:
      a.append([left,lmin])
  else:
    if left <= lmin:
      tright += left
    else:
      b.append([left,lmin])
#
a.sort(key=lambda x:-x[1])
b.sort(key=lambda x:x[1])

for left, lmin in a:
  if tleft + lmin < 0:
    print("No")
    return
  else:
    tleft += left
#
for left, lmin in b:
  if tleft + lmin < 0:
    print("No")
    return
  else:
    tleft += left
#
if tleft + tright == 0:
  print("Yes")
else:
  print("No")
#


# coding: utf-8
import sys
from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
#import queue# queue,get(), queue.put()
def run():
    N = int(input())
    current = 0
    ways = []
    dic = {'(': 1, ')': -1}
    SS = read().split()

    for S in SS:
        path = [0]
        for s in S:
            path.append(path[-1]+ dic[s])
        ways.append((path[-1], min(path)))

    ways_pos = sorted([(a,b) for a,b in ways if a >= 0], key = lambda x:(x[1], x[0]), reverse=True)
    ways_neg = sorted([(a,b) for a,b in ways if a < 0], key = lambda x:(x[1] - x[0], -x[0]))

    for i in range(len(ways_pos)):
        go, max_depth = ways_pos[i]
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

    for i in range(len(ways_neg)):
        go, max_depth = ways_neg[i]
        if current + max_depth >= 0:
            current += go
        else:
            print("No")
            return None

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

def __starting_point():
    run()
__starting_point()

from functools import reduce
n, *s = open(0).read().split()
u = []
for t in s:
    close_cnt = 0
    tmp = 0
    for c in t:
        tmp += (1 if c == '(' else -1)
        close_cnt = min(close_cnt, tmp)
    u.append((close_cnt, tmp - close_cnt))
M = 10**6 + 1
acc = 0
for a, b in sorted(u, key=lambda z: (- M - z[0] if sum(z)>= 0 else M - z[1])):
    if acc + a < 0:
        print("No")
        return
    else:
        acc += a + b
print(("No" if acc else "Yes"))

import sys
input = sys.stdin.readline
 
n = int(input())
s = [input().strip() for _ in range(n)]
plus = []
minus = []
for i in s:
    min_v = 0
    sum_v = 0
    for j in i:
        sum_v += 1 if j == '(' else -1
        min_v = min(min_v, sum_v)
    if sum_v > 0:
        plus.append((min_v, sum_v))
    else:
        minus.append((min_v-sum_v, -sum_v))
 
plus.sort(key=lambda x:x[0], reverse=True)
minus.sort(key=lambda x:x[0], reverse=True)
 
sum_plus = 0
for min_v, sum_v in plus:
    if sum_plus + min_v < 0:
        print("No")
        return
    sum_plus += sum_v
 
sum_minus = 0
for min_v, sum_v in minus:
    if sum_minus + min_v < 0:
        print("No")
        return
    sum_minus += sum_v
 
if sum_plus == sum_minus:
    print("Yes")
else:
    print("No")

n = int(input())


def _kakko(s):
    l, lr = 0, 0
    for c in s:
        if c == ')':
            if lr == 0:
                l = l + 1
            else:
                lr = lr - 1
        else:
            lr = lr + 1
    return (l, lr)


s = [_kakko(input()) for _ in range(n)]

sl = [ss for ss in s if ss[1] >= ss[0]]
sr = [ss for ss in s if ss[1] < ss[0]]

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

r = 0
for ss in sl:
    if ss[0] > r:
        print('No')
        return
    r = r + ss[1] - ss[0]

for ss in sr:
    if ss[0] > r:
        print('No')
        return
    r = r + ss[1] - ss[0]

if r != 0:
    print('No')
    return

print('Yes')


# +1/-1の折れ線で表したとき
# 「0で終わる」かつ「途中で0未満にならない」を満たせば良い

# あとは貪欲を上手い事使う


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

    n = int(input())
    a = []
    b = []
    for _ in range(n):
        s = input().rstrip()
        # 最終的に上がる量/最下点
        up, down = 0, 0
        for i in s:
            if i == ')':
                up -= 1
                if down > up:
                    down = up
            else:
                up += 1
        if up >= 0:
            a.append((down, up))
        else:
            b.append((down-up, -up))

    a.sort(key=lambda a: a[0],reverse=True)
    b.sort(key=lambda a: a[0],reverse=True)

    left, right = 0, 0

    for d, u in a:
        if left+d < 0:
            print('No')
            break
        else:
            left += u
    else:
        for d, u in b:
            if right+d < 0:
                print('No')
                break
            else:
                right += u
        else:
            if left == right:
                print('Yes')
            else:
                print('No')
    
def __starting_point():
    main()
__starting_point()

def main():
    import sys
    from collections import deque
    sys.setrecursionlimit(10**6)
    input = sys.stdin.readline
    N = int(input())
    pq = deque([])
    mq = deque([])
    for n in range(N):
        s = input().strip()
        mini = 0
        dst = 0
        for ss in [1 if ss == '(' else -1 for ss in s]:
            dst += ss
            mini = min(dst, mini)
        
        if dst >= 0:
            pq.append((mini, dst))
        elif dst < 0:
            mq.append((mini - dst, mini, dst))
    pq = sorted(pq, reverse=True)
    mq = sorted(mq)
    p = 0
    for mini, dst in pq:
        if p + mini < 0:
            print('No')
            return
        p += dst
    for minimini, mini, dst in mq:
        if p + mini < 0:
            print('No')
            return
        p += dst
    if p != 0:
        print('No')
    else:
        print('Yes')

def __starting_point():
    main()
__starting_point()

#from collections import defaultdict, deque
#import itertools
#import numpy as np
#import re
import bisect

def main():
    N = int(input())
    SS = []
    for _ in range(N):
        SS.append(input())
    S = []
    for s in SS:
        while '()' in s:
            s = s.replace('()', '')
        S.append(s)
    #print(S)
    S = [s for s in S if s != '']
    sum_op = 0
    sum_cl = 0
    S_both_op = []
    S_both_cl = []
    for s in S:
        if not ')' in s:
            sum_op += len(s)
        elif not '(' in s:
            sum_cl += len(s)
        else:
            pos = s.find('(')
            if pos <= len(s) - pos:
                S_both_op.append((pos, len(s)-pos))  #closeのほうが少ない、'))((('など -> (2,3)
            else:
                S_both_cl.append((pos, len(s)-pos))  #closeのほうが多い、')))(('など -> (3,2)

    # S_both_opは、耐えられる中でより伸ばす順にしたほうがいい？
    #S_both_op.sort(key=lambda x: (x[0], x[0]-x[1]))  #closeの数が小さい順にsortかつclose-openが小さい=伸ばす側にsort
    #S_both_cl.sort(key=lambda x: (x[0], x[0]-x[1]))  #これもcloseの数が小さい順にsortかつclose-openが小さい=あまり縮まない順にsort
    S_both_op.sort(key=lambda x: x[0])
    S_both_cl.sort(key=lambda x: -x[1])

    for p in S_both_op:
        sum_op -= p[0]
        if(sum_op < 0 ):
            print('No')
            return
        sum_op += p[1]

    for p in S_both_cl:
        sum_op -= p[0]
        if(sum_op < 0 ):
            print('No')
            return
        sum_op += p[1]
    
    if sum_op == sum_cl:
        print('Yes')
    else:
        print('No')

def __starting_point():
    main()
__starting_point()

import sys
input=lambda: sys.stdin.readline().strip()


n=int(input())
A=[]
#
PM=[[0,0] for i in range(n)]
for i in range(n):
    now=0
    mini=0
    for j in input():
        if j=="(": now+=1 
        else:
            now-=1 ; mini=min(mini,now)
    PM[i]=[mini,now]

if sum( [PM[i][1] for i in range(n)]  )!=0 : 
    print("No")
    return

MINI=0
NOW=0
PMf=[PM[i] for i in range(n) if PM[i][1]>=0]
PMf.sort()
for i in range(len(PMf)):
    MINI=min(MINI , NOW+PMf[-i-1][0] )
    NOW+=PMf[-i-1][1]
    if MINI<0 : print("No") ; return

PMs=[PM[i] for i in range(n) if PM[i][1]<0]
PMs=sorted(PMs , key=lambda x : x[1]-x[0])
for i in range(len(PMs)):
    MINI=min(MINI , NOW+PMs[-i-1][0] )
    NOW+=PMs[-i-1][1]
    if MINI<0 : print("No") ; return

print("Yes")


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

min_revr, min_revl = 10**20, 10**20
left, rev_l, rev_r, right = 0, 0, 0, 0
for S in S_list:
    stack = []
    l, r = 0, 0
    for s in S:
        if s == '(':
            if stack:
                if stack[-1] == ')':
                    stack.append('(')
                    l = 1
                else:
                    stack.append('(')
                    l += 1
            else:
                stack.append('(')
                l = 1
        else:   # s==')'
            if stack:
                if stack[-1] == '(':
                    stack.pop()
                    l -= 1
                else:
                    stack.append(')')
                    r += 1
            else:
                stack.append(')')
                r = 1
    if l == 0:
        right += r
    elif r == 0:
        left += l
    else:
        rev_r += r
        rev_l += l
        min_revr = min(min_revr, r)
        min_revl = min(min_revl, l)

if min_revr == 10**20:
    min_revr = 0
if min_revl == 10**20:
    min_revl = 0

if left+rev_l == rev_r+right and left >= min_revr and right >= min_revl:
    print('Yes')
else:
    print('No')


n=int(input())
s1=0
s2=0
s3=list()
s4=list()
s5=list()
for i in range(n):
    a=str(input())
    b=str()
    while a!=b:
        b=a
        a=a.replace(r'()','')
    if len(a)==0:
        continue
    if a[0]=="(" and a[-1]=="(":
        s1+=len(a)
    elif a[0]==")" and a[-1]==")":
        s2+=len(a)
    else:
        x=len(a.replace("(",""))
        y=len(a)-x
        if x<y:
            s3.append([x,y])
        elif x==y:
            s4.append(x)
        else:
            s5.append([x,y])
            
s3.sort(key=lambda x:x[0])
s5.sort(key=lambda x:x[1])

flag=0
limit=s1

if len(s3)!=0:
    for i in range(len(s3)):
        if limit>=s3[i][0]:
            limit=limit-s3[i][0]+s3[i][1]
        else:
            flag=1
            print("No")
            break

x=limit

if len(s4)!=0:
    if limit<max(s4):
        print("No")
        flag=1

limit=s2
if len(s5)!=0:    
    if flag==0:
        for i in range(len(s5)):
            if limit>=s5[i][1]:
                limit=limit-s5[i][1]+s5[i][0]
            else:
                flag=1
                print("No")
                break

if flag==0 and len(s4)!=0:
    if limit<max(s4):
        print("No")
        flag=1

if flag==0 and x==limit:
    print("Yes")
elif flag==0:
    print("No")
        
        
       


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

# process
T = []
for s in S:
    while '()' in s:
        s = s.replace('()', '')
    T.append(s)

l1 = []
l2 = []
for t in T:
    op = t.find('(')
    if op < 0:
        op = len(t)
    cl = len(t) - op
    
    if cl+op != 0:
        if cl <= op:
            l1.append((cl, op))
        else:
            l2.append((op, cl))

l1.sort()
l2.sort(reverse=True)

result = False
x = 0
if len(l1)+len(l2) == 0:
    result = True
elif len(l1)>0 and len(l2)>0 and l1[0][0]+l2[-1][0] == 0:
    for cl, op in l1:
        x -= cl
        if x < 0:
            break
        x += op
    
    if x >= 0:
        for op, cl in l2:
            x -= cl
            if x < 0:
                break
            x += op
            
        if x == 0:
            result = True

# output
print(("Yes" if result else "No"))


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

ls1 = []
ls2 = []

for item in s:
    stk1 = []
    stk2 = []
    for ch in item:
        if ch == '(':
            stk2.append(ch)
        else:
            if len(stk2) > 0:
                stk2.pop()
            else:
                stk1.append(ch)
    l1 = len(stk1)
    l2 = len(stk2)
    if l2 >= l1:
        ls1.append((l1, l2))
    else:
        ls2.append((l1, l2))


ls1.sort()

cnt = 0

for item in ls1:
    cnt -= item[0]
    if cnt < 0:
        print('No')
        return
    else:
        cnt += item[1]

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

for item in ls2:
    cnt -= item[0]
    if cnt < 0:
        print('No')
        return
    else:
        cnt += item[1]

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


def main():
    n = int(input())
    l_0 = []
    r_0 = []
    ls_plus = []
    ls_minus = []
    sum_l = 0
    sum_r = 0
    for i in range(n):
        s = input()
        left, right = 0, 0
        for j in range(len(s)):
            if s[j] == '(':
                right += 1
            else:
                if right > 0:
                    right -= 1
                else:
                    left += 1
        if left == right == 0:
            continue

        if left == 0:
            l_0.append((left, right))
        elif right == 0:
            r_0.append((left, right))
        elif left < right:
            ls_plus.append((left, right))
        else:
            ls_minus.append((left, right))
        sum_l += left
        sum_r += right

    if len(ls_plus) == len(ls_minus) == len(l_0) == len(r_0) == 0:
        print("Yes")
        return

    if len(l_0) == 0 or len(r_0) == 0:
        print("No")
        return
    if sum_l != sum_r:
        print("No")
        return

    # r-lの大きい順
    ls_plus.sort(key=lambda x: x[1] - x[0], reverse=True)
    # lの小さい順
    ls_plus.sort(key=lambda x: x[0])

    # l-rの小さい順
    ls_minus.sort(key=lambda x: x[0] - x[1])
    # lの大さい順
    ls_minus.sort(key=lambda x: x[0], reverse=True)

    now_r = 0
    for ll in l_0:
        now_r += ll[1]

    # now_l = 0
    for i in range(len(ls_plus)):
        # l = ls[i][0]
        r = ls_plus[i][1]
        x = now_r - ls_plus[i][0]
        if x >= 0:
            # now_l = now_l
            now_r = x + r
        else:
            print("No")
            return

    for i in range(len(ls_minus)):
        # l = ls[i][0]
        r = ls_minus[i][1]
        x = now_r - ls_minus[i][0]
        if x >= 0:
            # now_l = now_l
            now_r = x + r
        else:
            print("No")
            return

    print("Yes")


main()


# F - Bracket Sequencing

from itertools import chain

n = int(input())
ss = [input() for i in range(n)]

def parse(s):
    "バランスしていない閉じ括弧数, 開き括弧数"
    cl, op = 0, 0
    for c in s:
        if c == '(':
            op += 1
        elif op > 0:
            op -= 1
        else:
            cl += 1
    return (cl, op)

open  = []  # 開き括弧のみ
close = []  # 閉じ括弧のみ
inc   = []  # 開き括弧が多い
dec   = []  # 閉じ括弧が多い
for s in ss:
    cl, op = parse(s)
    if cl == 0:
        open.append((cl, op))
    elif cl < op:
        inc.append((cl, op))
    elif op == 0:
        close.append((cl, op))
    else:
        dec.append((cl, op))
peak = 0
inc.sort()
dec.sort(reverse=True)
for cl, op in chain(open, inc, dec, close):
    if peak < cl:
        print('No')
        return
    peak += op - cl
print(('Yes' if peak == 0 else 'No'))


'''
○ 基本方針
'(' を1上昇、')'を1下降とイメージすると、
この問題は「0未満にならず、最終的に0になるか」と言い換えられる。

1. ／ 型
2. V 型で上昇
3. V型で下降
4. ＼型
の順で使えばよい。

2は、V字の最下点が最も高いものから使うのが最適。（徐々に、大きく沈み込むものを使えるようになる）
3は、(|下降| - V字の最下点) が最も大きいものから使うのが最適。（沈み込みが大きいものは早めに消化する）

ここで、1は2、3は4と合わせて考えて良い。
'''

Yes = 'Yes'
No = 'No'

def main():
    # 入力
    N = int(input())
    up = []     # 上昇が0以上のもの
    down = []   # 上昇が0未満のもの
    for _ in range(N):
        S = input()
        h, b = 0, 0 # h:上昇数、b:最下点
        for s in S:
            if s=='(':
                h += 1
            else:
                h -= 1
                b = min(b, h)
        #
        if h>=0:
            up.append((h, b))
        else:
            down.append((h, b))
    # 演算
    up.sort(key=lambda t: t[1], reverse=True)           # 上昇は、最下点が高いものから使う
    down.sort(key=lambda t: t[0]-t[1], reverse=True)    # 下降は、沈み込み後の反転上昇が大きいものから使う
    H = 0   # 現在の高さ
    for h, b in up + down:
        if H+b>=0:  # 高さが0未満にならない条件
            H += h
        else:
            print(No)
            return
    # 出力
    if H == 0:
        print(Yes)
    else:
        print(No)


main()



from sys import stdin

def main():
    readline = stdin.readline
    n = int(readline())
    s = tuple(readline().strip() for _ in range(n))

    plus, minus = [], []
    for c in s:
        if 2 * c.count('(') - len(c) > 0:
            plus.append(c)
        else:
            minus.append(c)

    plus.sort(key = lambda x: x.count(')'))
    minus.sort(key = lambda x: x.count('('), reverse = True)
    plus.extend(minus)
    sum = 0
    for v in plus:
        for vv in v:
            sum = sum + (1 if vv == '(' else -1)
            if sum < 0 : return print('No')
    if sum != 0:
        return print('No')

    return print('Yes')

def __starting_point():
    main()

__starting_point()

# F - Bracket Sequencing

from itertools import chain

n = int(input())
ss = [input() for i in range(n)]

def parse(s):
    "バランスしていない閉じ括弧数, 開き括弧数"
    cl, op = 0, 0
    for c in s:
        if c == '(':
            op += 1
        elif op > 0:
            op -= 1
        else:
            cl += 1
    return (cl, op)

inc   = []  # 開き括弧が多い
dec   = []  # 閉じ括弧が多い
close = []  # 閉じ括弧のみ
for s in ss:
    cl, op = parse(s)
    if cl < op:
        inc.append((cl, op))
    elif op == 0:
        close.append((cl, op))
    else:
        dec.append((cl, op))
peak = 0
inc.sort()
dec.sort(reverse=True)
for cl, op in chain(inc, dec, close):
    if peak < cl:
        print('No')
        return
    peak += op - cl
print(('Yes' if peak == 0 else 'No'))


# -*- coding: utf-8 -*-

N = int(input().strip())
S_list = [input().strip() for _ in range(N)]
#-----

def count_brackets(brackets):
    cnt = 0
    min_cnt = 0
    
    for i in range(len(brackets)):
        if brackets[i] == "(":
            cnt += 1
        else:  # brackets[i] == ")"
            cnt -= 1
            min_cnt = min(min_cnt, cnt)
    
    return cnt, min_cnt


tmp_cnt_plus  = []
tmp_cnt_minus = []

for S in S_list:
    cnt, min_cnt = count_brackets(S)
    
    if cnt == min_cnt == 0:
        continue
    
    if cnt >= 0:
        tmp_cnt_plus.append( (cnt, min_cnt) )
    else:  # cnt < 0
        tmp_cnt_minus.append( (cnt, min_cnt) )


tmp_cnt_plus.sort(key=lambda x: -x[1])
tmp_cnt_minus.sort(key=lambda x: -(x[0]-x[1]) )


sum_bracket = 0
flag = True

for cnt, min_cnt in (tmp_cnt_plus + tmp_cnt_minus):
    if (sum_bracket + min_cnt) < 0:
        flag = False
        break
    
    sum_bracket += cnt


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


import sys


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


def solve():
    N = int(input())
    inc_chunks = []
    dec_chunks = []
    for _ in range(N):
        depth = 0
        level = 0
        for c in input():
            if c == '(':
                level += 1
            else:
                level -= 1
                depth = min(depth, level)
        if level > 0:
            inc_chunks.append((depth, level))
        else:
            dec_chunks.append((depth - level, -level))

    inc_chunks.sort(reverse=True)
    dec_chunks.sort(reverse=True)
    inc_level = 0
    for depth, level in inc_chunks:
        if inc_level + depth < 0:
            return 'No'
        inc_level += level
    dec_level = 0
    for depth, level in dec_chunks:
        if dec_level + depth < 0:
            return 'No' 
        dec_level += level
    if inc_level != dec_level:
        return 'No'
    return 'Yes'


print((solve()))


def main():
    n = int(input())
    l_0 = []
    r_0 = []
    ls_plus = []
    ls_minus = []
    sum_l = 0
    sum_r = 0
    for i in range(n):
        s = input()
        left, right = 0, 0
        for j in range(len(s)):
            if s[j] == '(':
                right += 1
            else:
                if right > 0:
                    right -= 1
                else:
                    left += 1
        if left == right == 0:
            continue

        if left == 0:
            l_0.append((left, right))
        elif right == 0:
            r_0.append((left, right))
        elif left < right:
            ls_plus.append((left, right))
        else:
            ls_minus.append((left, right))
        sum_l += left
        sum_r += right

    if len(ls_plus) == len(ls_minus) == len(l_0) == len(r_0) == 0:
        print("Yes")
        return

    if len(l_0) == 0 or len(r_0) == 0:
        print("No")
        return
    if sum_l != sum_r:
        print("No")
        return

    # r-lの大きい順
    ls_plus.sort(key=lambda x: x[1] - x[0], reverse=True)
    # lの小さい順
    ls_plus.sort(key=lambda x: x[0])

    # l-rの小さい順
    ls_minus.sort(key=lambda x: x[0] - x[1])
    # lの大さい順
    ls_minus.sort(key=lambda x: x[0], reverse=True)

    now_r = 0
    for ll in l_0:
        now_r += ll[1]

    for _ in ls_plus:
        r = _[1]
        x = now_r - _[0]
        if x >= 0:
            now_r = x + r
        else:
            print("No")
            return

    for _ in ls_minus:
        r = _[1]
        x = now_r - _[0]
        if x >= 0:
            now_r = x + r
        else:
            print("No")
            return

    print("Yes")


main()


from sys import stdin

def main():
    plus, minus = [], []
    readline = stdin.readline
    n = int(readline())
    for _ in range(n):
        s = readline().rstrip()
        if 2 * s.count('(') - len(s) > 0:
            plus.append(s)
        else:
            minus.append(s)
    plus.sort(key = lambda x: x.count(')'))
    minus.sort(key = lambda x: x.count('('), reverse = True)
    plus.extend(minus)

    sum = 0
    for v in ''.join(plus):
        sum = sum + (1 if v == '(' else -1)
        if sum < 0 : return print('No')
    if sum != 0:
        return print('No')

    return print('Yes')

def __starting_point():
    main()

__starting_point()

# 折れ線グラフで考えると
# ( : +1
# ) : -1
# 0で終わる
# 0未満にならない → 各文字列で最下点と和を利用
# 和がマイナスの部分と分けて、マイナス部分は反転して考える

n = int(input())
plus = []
minus = []
for i in range(n):
    min_v = 0
    sum_v = 0
    s = input()
    for j in s:
        sum_v += 1 if j == '(' else -1
        min_v = min(min_v, sum_v)
    if sum_v > 0:
        plus.append((min_v, sum_v))
    else:
        minus.append((min_v-sum_v, -sum_v))

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

sum_plus = 0
for min_v, sum_v in plus:
    if sum_plus + min_v < 0:
        print("No")
        return
    sum_plus += sum_v

sum_minus = 0
for min_v, sum_v in minus:
    if sum_minus + min_v < 0:
        print("No")
        return
    sum_minus += sum_v

if sum_plus == sum_minus:
    print("Yes")
else:
    print("No")





def kakko(S):
    cum = 0
    mi = 0
    for s in S:
        cum += 1 if s == '(' else -1
        mi = min(mi, cum)
    return (-mi, cum - mi)

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

plus = []
minus = []

for l, r in S:
    if l <= r:
        plus.append((l, r))
    else:
        minus.append((l, r))

plus.sort(key=lambda a: a[0])
minus.sort(key=lambda a: a[1], reverse=True)
M = 0
for l, r in (plus + minus):
    M -= l
    if M < 0:
        print('No')
        return
    M += r

print(('Yes' if M == 0 else 'No'))


n = int(input())
scop = [] #高低差,min値
scom = []
ssum = 0

for i in range(n):
    s = input()
    sa = 0
    ms = 0
    for i in s:
        if i == "(":
            sa += 1
        else:
            sa -= 1
        if ms > sa:
            ms = sa
    if sa > 0:
        scop.append([ms,sa])
    elif not sa == ms:
        scom.append([ms,sa])
    ssum += sa

if not ssum == 0:
    print("No")
    return

scop.sort(reverse = True)
scom.sort()

now = 0
for i in scop:
    if now + i[0] < 0:
        print("No")
        return
    now += i[1]
for i in scom:
    if now + i[0] < 0:
        print("No")
        return
    now += i[1]

print("Yes")


def check():
    N = int(input())
    plus,minus = [],[]
    for i in range(N):
        S = input()
        now = 0
        mini = 0
        for s in S:
            if s=='(':
                now += 1
            else:
                now -= 1
                mini = min(mini,now)
        if now>=0:
            plus.append([mini,now])
        else:
            minus.append([now-mini,now])
    plus.sort(reverse=True)
    minus.sort(reverse=True)
    now = 0
    for a,b in plus:
        if now + a <0:
            return 'No'
        now += b
    for a,b in minus:
        if now + b-a <0:
            return 'No'
        now += b
    if now > 0:
        return 'No' 
    return 'Yes'
print(check())

from cython import longlong
 
def main():
    n: longlong
    n=int(input())
    lp, lm = [], []
    for i in range(n):
        s=input()
        
        x: longlong
        y: longlong
        x,y=0,0
        
        for j in s:
            if j=="(":x+=1
            else:x-=1
            y=min(y,x)
        if x>0: lp.append((y,x))
        else: lm.append((y-x,-x))
    lp.sort()
    s: longlong
    s=0
 
    i: longlong
    j: longlong
    for i,j in lp[::-1]:
        if s+i<0:
            print("No")
            return
        s+=j
    lm.sort()
 
    t: longlong
    t=0
 
    i: longlong
    j: longlong
    for i,j in lm[::-1]:
        if t+i<0:
            print("No")
            return
        t+=j
    if s==t: print("Yes")
    else: print("No")
 
def __starting_point():
    main()
__starting_point()

def scan(s):
    m = 0
    a = 0
    for c in s:
        if c == '(':
            a += 1
        elif c == ')':
            a -= 1
        m = min(m, a)
    return m, a


def key(v):
    m, a = v
    if a >= 0:
        return 1, m, a
    else:
        return -1, a - m, a

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

c = 0
for m, a in sorted([scan(s) for s in S], reverse=True, key=key):
    if c + m < 0:
        c += m
        break
    c += a

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


# 入力
N = int(input())

S1 = [] # 増えるシーケンス用
S2 = [] # 減るシーケンス用

# 入力その２
for i in range(N):

    S = input()  # シーケンス
    mid, end = 0, 0    

    for s in S:
        if s == '(':
            end += 1
        else:
            end -= 1
            
        mid = min(mid, end)  # 途中経過で一番減るところを探す

    if end > 0:
        S1.append((mid, end))
    else:
        S2.append((mid-end, -end))

S1.sort(reverse=True)
# S2.sort(key = lambda x : (x[0], -x[1]))
S2.sort(reverse=True)


mid = end1 = 0  # スタート
out = False

for t in S1:
    a, b = t
    mid = end1 + a
    end1 = end1 + b
    if mid < 0:  # 途中で左カッコの数が右を上回る
        out = True
        break

mid = end2 = 0  # スタート
for t in S2:
    a, b = t
    mid = end2 + a
    end2 = end2 + b
    if mid < 0:  # 途中で左カッコの数が右を上回る
        out = True
        break
        
if (not end1 == end2) or out:  # 右、左 の数が合わない
    print('No')
else:
    print('Yes')

def main():
    n = int(input())
    Ss = [input() for _ in range(n)]
    U = [[0, 0] for _ in range(n)]
    for i in range(n):
        for c in Ss[i]:
            if c == "(":
                U[i][1] += 1
            else:
                if U[i][1] == 0:
                    U[i][0] += 1
                else:
                    U[i][1] -= 1
    L, R = 0, 0
    P = []
    for i in range(n):
        if U[i][0] == 0 and U[i][1] > 0:
            L += U[i][1]
        elif U[i][0] > 0 and U[i][1] == 0:
            R += U[i][0]
        elif U[i][0] > 0 and U[i][1] > 0:
            P.append([U[i][0], U[i][1]])
    P.sort(key=lambda x: (x[0]-x[1], x[0], -x[1]))
    if L == 0 and R == 0 and len(P) == 0:
        print("Yes")
    elif (L == 0 or R == 0) and len(P) > 0:
        print("No")
    else:
        f = True
        for i in range(len(P)):
            L -= P[i][0]
            if L < 0:
                f = False
                break
            L += P[i][1]
        if L == R and f:
            print("Yes")
        else:
            print("No")

def __starting_point():
    main()
__starting_point()

# F - Bracket Sequencing
import sys
readline = sys.stdin.readline

N = int(input())
L = []
R = []
for _ in range(N):
    S = readline().strip()
    sums = 0
    mins = 0
    for s in S:
        if s == '(':
            sums += 1
        else:
            sums -= 1
            mins = min(mins, sums)
    if sums >= 0:
        L.append((sums, mins))
    else:
        R.append((-sums, mins-sums))

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

ans = 'Yes'
l_now = 0
for d, min_d in L:
    if l_now + min_d < 0:
        ans = 'No'
        break
    else:
        l_now += d

r_now = 0
for d, min_d in R:
    if r_now + min_d < 0:
        ans = 'No'
        break
    else:
        r_now += d

if l_now != r_now:
    ans = 'No'

print(ans)

from sys import stdin

def main():
    plus, minus = [], []
    readline = stdin.readline
    n = int(readline())
    for _ in range(n):
        s = readline().rstrip()
        if 2 * s.count('(') - len(s) > 0:
            plus.append(s)
        else:
            minus.append(s)
    plus.sort(key = lambda x: x.count(')'))
    minus.sort(key = lambda x: x.count('('), reverse = True)

    sum = 0
    for v in ''.join(plus + minus):
        sum = sum + (1 if v == '(' else -1)
        if sum < 0 : return print('No')
    if sum != 0:
        return print('No')

    return print('Yes')

def __starting_point():
    main()

__starting_point()

def hoge(S):
    cum = 0
    mi = 0
    for s in S:
        cum += 1 if s == '(' else -1
        mi = min(mi, cum)
    return (-mi, cum - mi)

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

plus = []
minus = []

for l, r in S:
    if l <= r:
        plus.append((l, r))
    else:
        minus.append((l, r))

plus.sort(key=lambda a: a[0])
minus.sort(key=lambda a: a[1], reverse=True)
M = 0
for l, r in (plus + minus):
    M -= l
    if M < 0:
        print('No')
        return
    M += r

print(('Yes' if M == 0 else 'No'))


from itertools import chain
import sys

def main():
    N = int(input())
    # TLEs were caused mostly by slow input (1s+)
    # S = list(input() for _ in range(N))
    S = sys.stdin.read().split('\n')
    print((solve(S)))

def get_count(args):
    s, result = args # messy input to work with map.
    cum_sum = 0
    for c in s:
        if c == ')':
            cum_sum -= 1
        else:
            cum_sum += 1
        result[0] = max(result[0], -cum_sum)
    result[1] = result[0] + cum_sum
    return result

# Made-up name, don't remember what to call this. Radix-ish
def silly_sort(array, value_min, value_max, get_value):
    if len(array) == 0:
        return
    cache = [None for _ in range(value_max - value_min + 1)]
    for elem in array:
        # Assume elem[0] is the value
        value = get_value(elem) - value_min
        if cache[value] is None:
            cache[value] = []
        cache[value].append(elem)
    for values in cache:
        if values is None:
            continue
        for value in values:
            yield value

def solve(S):
    counts = [[0,0] for _ in range(len(S))]
    counts = list(map(get_count, list(zip(S,counts))))
    first_group = []
    second_group = []
    min_first_group = float('inf')
    max_first_group = 0
    min_second_group = float('inf')
    max_second_group = 0

    for c in counts:
        if c[0] - c[1] <= 0:
            first_group.append(c)
            max_first_group = max(max_first_group, c[0])
            min_first_group = min(min_first_group, c[0])
        else:
            second_group.append(c)
            max_second_group = max(max_second_group, c[1])
            min_second_group = min(min_first_group, c[1])
    first_group = silly_sort(first_group, min_first_group, max_first_group, lambda c: c[0])
    second_group = reversed(list(silly_sort(second_group, min_second_group, max_second_group, lambda c: c[1])))

    order = chain(first_group, second_group)

    cum_sum = 0
    for c in order:
        cum_sum -= c[0]
        if cum_sum < 0:
            return 'No'
        cum_sum += c[1]
    if cum_sum == 0:
        return 'Yes'
    return 'No'

def __starting_point():
    main()

__starting_point()

from itertools import *
n,*s=open(0).read().split()
u=[[min(accumulate(t,lambda a,b: a+(1 if b=="(" else -1),initial=0)),2*t.count("(")-len(t)] for t in s]
m=0
for c,d in chain(sorted([x for x in u if x[1]>=0])[::-1],sorted([x for x in u if x[1]<0],key=lambda z:z[0]-z[1])):
    if m+c<0:print("No");break
    m+=d
else:
    print("No" if m else "Yes")

import sys
readline = sys.stdin.readline


def solve():
    N = int(input())
    brackets_generator = (readline().strip() for _ in range(N))

    grads_positive = list()
    grads_negative = list()

    total = 0
    for brackets in brackets_generator:

        elevation, bottom = 0, 0

        for bk in brackets:

            elevation += 1 if bk == '(' else -1
            bottom = min(bottom, elevation)

        if elevation >= 0:
            grads_positive.append((bottom, elevation))
        elif elevation < 0:
            grads_negative.append((bottom - elevation, -elevation))

        total += elevation

    if total != 0:
        return False

    grads_positive.sort(reverse=True)
    grads_negative.sort(reverse=True)

    def is_good(grads):
        elevation, bottom = 0, 0
        for grad in grads:
            bottom = elevation + grad[0]
            if bottom < 0:
                return False
            elevation += grad[1]

        return True

    return is_good(grads_positive) and is_good(grads_negative)


def main():
    ok = solve()
    if ok:
        print('Yes')
    else:
        print('No')


def __starting_point():
    main()

__starting_point()

# 折れ線グラフで考えると
# ( : +1
# ) : -1
# 0で終わる
# 0未満にならない → 各文字列で最下点と和を利用
# 和がマイナスの部分と分けて、マイナス部分は反転して考える

n = int(input())
s = [input() for _ in range(n)]
plus = []
minus = []
for i in s:
    min_v = 0
    sum_v = 0
    for j in i:
        sum_v += 1 if j == '(' else -1
        min_v = min(min_v, sum_v)
    if sum_v > 0:
        plus.append((min_v, sum_v))
    else:
        minus.append((min_v-sum_v, -sum_v))

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

sum_plus = 0
for min_v, sum_v in plus:
    if sum_plus + min_v < 0:
        print("No")
        return
    sum_plus += sum_v

sum_minus = 0
for min_v, sum_v in minus:
    if sum_minus + min_v < 0:
        print("No")
        return
    sum_minus += sum_v

if sum_plus == sum_minus:
    print("Yes")
else:
    print("No")





# +1/-1の折れ線で表したとき
# 「0で終わる」かつ「途中で0未満にならない」を満たせば良い

# あとは貪欲を上手い事使う


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

    n = int(input())
    a = []
    b = []
    for _ in range(n):
        s = input().rstrip()
        # 最終的に上がる量/最下点
        up, down = 0, 0
        for i in s:
            if i == ')':
                up -= 1
                if down > up:
                    down = up
            else:
                up += 1
        if up >= 0:
            a.append((down, up))
        else:
            b.append((up-down, down, up))

    a.sort(reverse=True)
    b.sort(key=lambda a: a[0],reverse=True)

    c = 0

    for d, u in a:
        if c+d < 0:
            print('No')
            break
        else:
            c += u
    else:
        for _, d, u in b:
            if c+d < 0:
                print('No')
                break
            else:
                c += u
        else:
            if c == 0:
                print('Yes')
            else:
                print('No')
    
def __starting_point():
    main()

__starting_point()

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


def bracket(x):
    # f: final sum of brackets '(':+1, ')': -1
    # m: min value of f
    f = m = 0
    for i in range(len(x)):
        if x[i] == '(':
            f += 1
        else:
            f -= 1
        m = min(m, f)
    # m <= 0
    return f, m


def func(l):
    # l = [(f, m)]
    l.sort(key=lambda x: -x[1])
    v = 0
    for fi, mi in l:
        if v + mi >= 0:
            v += fi
        else:
            return -1
    return v


l1 = []
l2 = []
for i in range(n):
    fi, mi = bracket(s[i])
    if fi >= 0:
        l1.append((fi, mi))
    else:
        l2.append((-fi, mi - fi))

v1 = func(l1)
v2 = func(l2)
if v1 == -1 or v2 == -1:
    ans = 'No'
else:
    ans = 'Yes' if v1 == v2 else 'No'

print(ans)


def main():
    n = int(input())
    up = []
    down = []
    for _ in range(n):
        height = 0
        m = 0
        for si in input():
            if si == "(":
                height += 1
            else:
                height -= 1
                m = min(m, height)
        if height >= 0:
            up.append([m, height])
        else:
            down.append([m-height, -height])
    up.sort(reverse=True)
    down.sort(reverse=True)
    if sum([i for _, i in up]) - sum([i for _, i in down]) != 0:
        print("No")
        return
    h = 0
    for mi, hi in up:
        if h+mi < 0:
            print("No")
            return
        h += hi
    h = 0
    for mi, hi in down:
        if h+mi < 0:
            print("No")
            return
        h += hi
    print("Yes")
    return
            

def __starting_point():
    main()
__starting_point()

def CNT(A):
    tmp, Min = 0, 0
    for a in A:
        if a == '(': tmp += 1
        else: tmp -= 1
        Min = min(Min, tmp)
    return (-Min, tmp-Min)

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

pls = []
mis = []
for l, r in T:
    if l <= r: pls.append((l, r))
    else: mis.append((l, r))

pls.sort(key=lambda a: a[0])
mis.sort(key=lambda a: a[1], reverse=True)
totl= pls + mis

levl = 0
for l, r in totl:
    levl -= l
    if levl < 0:
        print('No')
        return
    levl += r

print('Yes' if levl==0 else 'No')

import sys
input = sys.stdin.readline
def main():
    N = int( input())
    S = [input().strip() for _ in range(N)]
    Up = []
    Down = []
    for s in S:
        now = 0
        m = 0
        for t in s:
            if t == "(":
                now += 1
            else:
                now -= 1
            if now < m:
                m = now
            # print(t, now)
        if now >= 0:
            Up.append((m,now))
        else:
            Down.append((m-now,-now))
    up = 0
    Up.sort(reverse=True)
    for m, inc in Up:
        if up+m < 0:
            print("No")
            return
        up += inc
    
    down = 0
    Down.sort(reverse=True)
    # print(Up, Down)
    for m, dec in Down:
        if down+m < 0:
            print("No")
            return
        down += dec
    if up != down:
        print("No")
        return
    print("Yes")
    
def __starting_point():
    main()

__starting_point()

N = int((input()))
C_p = []
C_m = []
for i in range(N):
    kakko = input()
    temp = 0
    temp_min = 0
    for s in kakko:
        if s == "(":
            temp += 1
        else:
            temp -= 1
            temp_min = min(temp, temp_min)
    if temp >= 0:
        C_p.append((temp_min, temp))
    else:
        C_m.append((temp_min - temp, temp_min, temp))
C_p.sort(reverse=True)

flag = 0
final = 0
for l, f in C_p:
    if final + l < 0:
        flag = 1
    final += f

C_m.sort()

for _, l, f in C_m:
    if final + l < 0:
        flag = 1
    final += f
    
if final != 0:
    flag = 1

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

import bisect

n=int(input())
opens=0
closes=0
ls=[]
rs=[]
for _ in range(n):
  s=input()
  cnt1=0
  cnt2=0
  for i in range(len(s)):
    if s[i]=='(':
      cnt1+=1
    else:
      if cnt1==0:
        cnt2+=1
      else:
        cnt1-=1
  if cnt2==0:
    opens+=cnt1
  elif cnt1==0:
    closes+=cnt2
  else:
    ls.append(cnt2)
    rs.append(cnt1)
ls=sorted(ls)
rs=sorted(rs)
lefts=sum(ls)
rights=sum(rs)
if opens-closes!=lefts-rights:
  print('No')
else:
  flag=False
  if len(ls)==0:
    flag=True
  for a in ls:
    if opens<a or closes<a+(rights-lefts):
      continue
    pos=bisect.bisect_right(rs,a+(rights-lefts))
    if pos!=0:
      flag=True
      break
  for b in rs:
    if opens<b+(lefts-rights) or closes<b:
      continue
    pos=bisect.bisect_right(ls,b+(lefts-rights))
    if pos!=0:
      flag=True
      break
  if flag==True:
    print('Yes')
  else:
    print('No')

# 入力
N = int(input())

S1 = [] # 増えるシーケンス用
S2 = [] # 減るシーケンス用

# 入力その２
for i in range(N):

    S = input()  # シーケンス
    mid, end = 0, 0    

    for s in S:
        if s == '(':
            end += 1
        else:
            end -= 1
            
        mid = min(mid, end)  # 途中経過で一番減るところを探す

    if end > 0:
        S1.append((mid, end))
    else:
        S2.append((mid-end, -end))

S1.sort(reverse=True)
# S2.sort(key = lambda x : (x[0], -x[1]))
S2.sort(reverse=True)


mid = end1 = 0  # スタート
out = False

for t in S1:
    a, b = t
    mid = end1 + a
    end1 = end1 + b
    if mid < 0 or end1 < 0:  # 途中で左カッコの数が右を上回る
        out = True
        break

mid = end2 = 0  # スタート
for t in S2:
    a, b = t
    mid = end2 + a
    end2 = end2 + b
    if mid < 0 or end2 < 0:  # 途中で左カッコの数が右を上回る
        out = True
        break
        
if (not end1 == end2) or out:  # 右、左 の数が合わない
    print('No')
else:
    print('Yes')


def resolve():
    def check(arr):
        height = 0
        for b, h in arr:
            if height+b < 0:
                return False
            height += h
        return True

    N = int(input())
    plus = []
    minus = []
    total = 0
    for _ in range(N):
        # 1つのパーツを処理
        S = input()
        cum = 0 # 累積和(最高地点)
        bottom = 0 # 最下地点
        for s in S:
            if s == "(":
                cum += 1
            else:
                cum -= 1
            bottom = min(bottom, cum)

        total += cum
        if cum > 0:
            plus.append((bottom, cum))
        else:
            minus.append((bottom-cum, -cum))

    plus.sort(reverse=True)
    minus.sort(reverse=True)

    if check(plus) and check(minus) and total == 0:
        print("Yes")
    else:
        print("No")

def __starting_point():
    resolve()

__starting_point()

def main():
  ## IMPORT MODULE
  #import sys

  #sys.setrecursionlimit(100000)
  #input=lambda :sys.stdin.readline().rstrip()

  #f_inf=float("inf")
  #MOD=10**9+7
  
  if 'get_ipython' in globals(): 
    ## SAMPLE INPUT
    n = 4
    S = ['((()))', '((((((', '))))))', '()()()']

  else:
    ## INPUT 
    n = int(input())
    #a, b = map(int, input().split())
    S = [input() for _ in range(n)]

  ## SUBMITION CODES HERE
  def CNT(A):
    tmp, Min = 0, 0
    for a in A:
        if a == '(': tmp += 1
        else: tmp -= 1
        Min = min(Min, tmp)
    return (-Min, tmp-Min)
  
  T = [CNT(s) for s in S]

  pls = []
  mis = []
  for l, r in T:
    if l <= r: pls.append((l, r))
    else: mis.append((l, r))

  pls.sort(key=lambda a: a[0])
  mis.sort(key=lambda a: a[1], reverse=True)
  total = pls + mis

  levl = 0
  for l, r in total:
    levl -= l
    if levl < 0:
        print('No')
        return
    levl += r

  print('Yes' if levl == 0 else 'No')
    
main()