Problem:


Score : 600 points

Problem Statement

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

An empty string;

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

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

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

Constraints

1 \leq N \leq 10^6

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

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

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

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

Sample Input 1

2
)
(()

Sample Output 1

Yes

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

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No



Sample input:
2
)
(()


Sample output:
Yes

Submission status: Wrong Answer

Solution code:
import math
import fractions
#import sys
#input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

#a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################



n = int(input())

lr = []

for i in range(n):
    s = input()
    m = len(s)
    #exam left
    count = 0
    left = 0
    for j in range(m):
        if(s[j]=='('):
            count += 1
        else:
            if(count == 0):
                left+=1
            else:
                count -=1
    #exam right
    count = 0
    right = 0
    for j in range(m):
        if(s[m-j-1]==')'):
            count += 1
        else:
            if(count == 0):
                right+=1
            else:
                count -=1

    #print(left,right)
    lr.append([left,right])

existL = 0
existR = 0
sumL = 0
sumR = 0
for i in range(n):
    sumL += lr[i][0]
    sumR += lr[i][1]
    if(lr[i][0]==0 and lr[i][1]!=0):
        existL=1
    if(lr[i][1]==0 and lr[i][0]!=0):
        existR=1

#print(lr)
print("Yes")
exit()
if(existL*existR == 1 and sumL == sumR):
    print("Yes")
else:
    if(sumL==0 and sumR==0):
        print("Yes")
    else:
        print("No")

Submission status: Wrong Answer

Solution code:
n= int(input())
s = [""]*n
for i in range(n):
  s[i] = input()
s.sort()
brakcnt = 0
ans = "Yes"
for i in s:
  for j in range(len(i)):
    if i[j]=="(":
      brakcnt += 1
    else:
      brakcnt -= 1
    if brakcnt<0:
      ans = "No"
      break
if brakcnt!=0:
  ans = "No"
print(ans)

Submission status: Wrong Answer

Solution code:

"""

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

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

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


"""


N = int(input())

ans = 0

pl_d = [] 
mi_d = []

for lp in range(N):

    S = input()

    dep = 0
    mindep = 0

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

        mindep = min(dep,mindep)

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

pl_d.sort()
mi_d.sort()

print (pl_d,mi_d)

nowp = 0

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

    nd,np = pl_d[i]

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

    nowp += np

nowm = 0

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

    nd,np = mi_d[i]

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

    nowm += np


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

Submission status: Wrong Answer

Solution code:
N=int(input())
plus_data=[]
minus_data=[]
for i in range(N):
    s=list(input())
    dif=0
    maxi=0
    mini=0
    for j in range(len(s)):
        if s[j]=="(":
            dif+=1
        else:
            dif-=1
        maxi=max(maxi,dif)
        mini=min(mini,dif)
    if mini>=0:  
        plus_data.append((maxi,mini,dif))
    else:
        minus_data.append((maxi,mini,dif))
    
minus_data.sort(key=lambda x:(-x[1]))
flag=True
sums=0
for some in plus_data:
    sums+=some[2]
for some in minus_data:
    maxi,mini,dif=some
    if sums+mini<0:
        flag=False
        break
    else:
        sums+=dif
if flag:
    if sums==0:
        print("Yes")
    else:
        print("No")
else:
    print("No")

Submission status: Wrong Answer

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

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

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

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

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

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

if len(M) == 0:
  if cnt == 0:
    print("Yes")
  else:
    print("No")
  exit()
M.sort(key = lambda x:x[1], reverse = True)

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

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

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

Submission status: Wrong Answer

Solution code:
n = int(input())
left = []
right = []
for i in range(n):
    s = input()
    n0 = 0
    n1 = 0
    l = len(s)
    for j in range(l):
        if s[j] == "(":
            n0 += 1
        else:
            if n0 == 0:
                n1 += 1
            else:
                n0 -= 1
    if n0 > 0 or n1 > 0:
        if n0 >= n1:
            left.append([n1, n0])
        else:
            right.append([n0, n1])

left.sort()
right.sort()

def solve():
    nl0 = 0
    nl1 = 0
    for p in left:
        if p[0] > nl0:
            return False
        nl0 -= p[0]
        nl1 += p[1]
    nr0 = 0
    nr1 = 0
    for p in right:
        if p[0] > nr1:
            return False
        nr1 -= p[0]
        nr0 += p[1]
    if nl1 == nr0:
        return True
    else:
        return False

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
for i in range(N):
    S = input()
    a = [0,0]
    if S!="":
        l,r,k = 0,0,0
        for s in S:
            if s=="(":
                r+=1
            else:
                if r>0:
                    r-=1
                else:
                    l+=1
        a = [l,r]
    A.append(a)
A.sort(key=lambda x:(x[0],-x[1]))
ans = "Yes"
K = 0
for a in A:
    K -= a[0]
    if K<0:
        ans = "No"
        break
    K += a[1]
if K>0:ans = "No"
print(ans)

Submission status: Wrong Answer

Solution code:
def RunLengthEncoding(S):
    res = []
    N = len(S)
    i = 0
    while i < N:
        cnt = 1
        while i < N - 1 and S[i] == S[i + 1]:
            cnt += 1
            i += 1
        res.append([S[i], cnt])
        i += 1

    while True:
        res2 = omit(res)
        if res == res2:
            return res2
        res = res2


def omit(RLE):
    res = []
    i = 0
    while i < len(RLE):
        k, v = RLE[i]
        if k == ")":
            res.append([k, v])
            i += 1
            continue
        if i >= len(RLE) - 1:
            res.append([k, v])
            break

        kk, y = RLE[i + 1]
        if v > min(v, y):
            res.append([k, v - min(v, y)])
        if y > min(v, y):
            res.append([kk, y - min(v, y)])
        i += 2
    if res:
        res = merge(res)
    return res


def merge(RLE):
    res = []
    res.append(RLE[0])
    for i in range(1, len(RLE)):
        k, v = RLE[i]
        if res[-1][0] != k:
            res.append([k, v])
        else:
            res[-1][1] += v
    return res


if __name__ == "__main__":
    N = int(input())
    tmp = []
    for _ in range(N):
        RLE = RunLengthEncoding(input())
        if RLE:
            tmp.append(RLE)

    outR = 0
    inR = 0
    outL = 0
    inL = 0
    for b in tmp:
        if len(b) == 1:
            k, v = b[0]
            if k == "(":
                outR += v
            else:
                outL += v
        else:
            k, v = b[0]
            inL += v
            k, v = b[1]
            inR += v

    if outR < inL or inR > outL:
        print("No")
        exit()
    if outR + inR == outL + inL:
        print("Yes")
    else:
        print("No")

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [0] * n
inc = [[] for _ in range( 1100000)]
zeros = []
dec = [[] for _ in range( 1100000)]

for i in range(n):
    s[i] = input()
    start = 0
    minimum = 0
    now = 0
    for c in s[i]:
        if c == '(':now += 1
        else: now -= 1
        minimum = min(minimum, now)
    end = now
    
    if end == 0:
        zeros.append(i)
    elif start < end:
        inc[minimum].append(i)
    else:
        minimum = minimum - end
        dec[minimum].append(i)

inc.sort(reverse=True)
dec.sort()


now = 0
for m in range(0, -1000000, -1):
    for i in inc[m]:
        for c in s[i]:
            if c == '(':now += 1
            else: now -= 1
            if now < 0:
                print("No")
                exit()
        
for i in zeros:
    for c in s[i]:
        if c == '(':now += 1
        else: now -= 1
        if now < 0:
            print("No")
            exit()
for m in range(-1000000, 1):
    for  i in dec[m]:
        for c in s[i]:
            if c == '(':now += 1
            else: now -= 1
            if now < 0:
                print("No")
                exit()
                
if now != 0:
    print("No")
else:
    print("Yes")

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
N=int(input())
S=[input() for i in range(N)]
p=q=0
a=[]
b=[]
for n,i in enumerate(S):
    s=t=0
    for j in i:
        if j=="(":
            p+=1
        else:
            q+=1
    for j in i:
        if j=="(":
            s+=1
        else:
            if s:
                s-=1
    if s==0 and len(a)<2:
        a.append(n)
    s=0
    for j in i[::-1]:
        if j==")":
            s+=1
        else:
            if s:
                s-=1
    if s==0 and len(b)<2:
        b.append(n)
if p!=q:
    print("No")
elif len(a)==len(b)==1 and a==b and N!=1:
    print("No")
elif not (a and b):
    print("No")
else:
    print("Yes")

Submission status: Wrong Answer

Solution code:
import sqlite3

conn = sqlite3.connect(":memory:")
conn.executescript(
    "CREATE TABLE tab (max_d INTEGER, tot_d INTEGER); CREATE INDEX ind ON tab(max_d DESC, tot_d DESC);",
)

N = int(input())
for _ in range(N):
    S = input()
    max_d = 0
    tot_d = 0
    tot_o = 0
    tot_c = 0
    for c in S:
        if c == "(":
            tot_o += 1
        else:
            tot_c += 1
            max_d = max(max_d, tot_c - tot_o)
    conn.execute("INSERT INTO tab VALUES (?, ?)", (max_d, tot_o - tot_c))
d = 0
for _ in range(N):
    row = conn.execute(
        "SELECT rowid, tot_d FROM tab WHERE max_d <= ? ORDER BY max_d DESC, tot_d DESC LIMIT 1",
        (d,),
    ).fetchone()
    if row is None:
        d = -1
        break
    d += row[1]
    conn.execute("DELETE FROM tab WHERE rowid = ?", (row[0],))
if d == 0:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import Counter, defaultdict, deque

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

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

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

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

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

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

Submission status: Wrong Answer

Solution code:
import sys
from operator import itemgetter

def solve():
    input = sys.stdin.readline
    N = int(input())
    Left = []
    for _ in range(N):
        S = input().strip("\n")
        M = len(S)
        aL, aR = 0, 0
        #自身より左にある"("
        r = 0
        for i in range(M):
            if S[i] == ")":
                if r == 0: aL += 1
                else: r -= 1
            else: r += 1
        l = 0
        for i in range(M):
            if S[M-1-i] == "(":
                if l == 0: aR += 1
                else: l -= 1
            else: l += 1
        Left.append((aL, aR))
    Left.sort(key = itemgetter(1), reverse = True)
    Left.sort(key = itemgetter(0))
    
    #print(Left)
    rightOver = 0
    for aL, aR in Left:
        rightOver -= aL
        if rightOver < 0:
            print("No")
            break
        rightOver += aR
    else:
        if rightOver == 0: print("Yes")
        else: print("No")

    return  0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[input() for i in range(N)]
dl,dr,dm=0,0,0
f=0
for i,s in enumerate(S):
    l,r=0,0
    for c in s:
        if c=='(':
            l+=1
        else:
            if l>0:l-=1
            else: r+=1
    if l>0 and r>0:
        dm+=l-r
        f=1
    elif l>0:
        dl+=l
    elif r>0:
        dr-=r
print(['No','Yes'][dl+dr+dm==0 and (f==0 or dl>0)])

Submission status: Wrong Answer

Solution code:
n=int(input())
lipp = []
lipm = []
limm = []
allcnt = 0
for _ in range(n):
    s = input()
    cnt = 0
    mi = 0
    for x in s:
        if x == ')':
            cnt -= 1
            mi = min(mi,cnt)
        else:
            cnt += 1
    if mi == 0:
        lipp.append(cnt)
    elif cnt >= 0:
        lipm.append([mi,cnt])
    else:
        limm.append([mi,cnt])
    allcnt += cnt
if allcnt != 0:
    print('No')
    exit()

now = sum(lipp)
lipm.sort(reverse = True)
limm.sort()

for mi, cnt in lipm:
    if mi + now < 0:
        print('No')
        exit()
    now += cnt


for mi, cnt in limm:
    if now+mi < 0:
        print('No')
        exit()
    now += cnt
print("Yes")

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    S = [input() for _ in range(N)]
    L = []
    for i in range(N):
        t = 0
        mint = 0
        for s in S[i]:
            if s == "(":
                t += 1
            else:
                t -= 1
            mint = min(mint, t)
        L.append((t, mint))
    L.sort(key=lambda x: x[1], reverse=True)
    t = 0
    for l, m in L:
        if t + m < 0:
            return False
        t += l
        if t < 0:
            return False
    if t == 0:
        return True
    return False


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

Submission status: Wrong Answer

Solution code:
def main():

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

    if tot_v !=  0: return 'No'
    #
    # print(pos)
    # print(neg)

    u = 0
    for _, v in pos:
        u += v
    neg.sort(reverse = True, key = lambda x: x[0])
    for min_v, v in neg:
        if u + min_v < 0:
            return "No"
        else:
            u += v
        if u < 0:
            return "No"
    return "Yes"






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

Submission status: Wrong Answer

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)
    lr.append([l,r])
#lr.sort(key=lambda x:x[0]*x[1],reverse=True)
idleR=10**7
L,R=lr[0]
stack=[[L,R]]
for n in range(1,N):
    #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],[l+L-R,r-l],[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: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
import sys
N = int(input())
brackets = []
def change(S):
    SUM = 0
    left = 0
    for i in S:
        if i == ')':
            if SUM <= 0:
                left += 1
            SUM -= 1
        else:
            SUM += 1
    return (left, -1 * (SUM + left))

for _ in range(N):
    brackets.append(change(input()))

brackets.sort()

cnt = 0
for b in brackets:
    cnt -= b[0]
    if cnt < 0:
        print('No')
        sys.exit()
    cnt -= b[1]
if cnt == 0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import os

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N = int(sys.stdin.buffer.readline())
S = [sys.stdin.buffer.readline().decode().rstrip() for _ in range(N)]


def solve():
    diffs = []
    max_downs = []
    for s in S:
        diff = 0
        mi = 0
        for c in s:
            diff += 1 if c == '(' else -1
            mi = min(diff, mi)
        diffs.append(diff)
        max_downs.append(-mi)

    if sum(diffs) != 0:
        return False

    positives = []
    zeros = []
    negatives = []
    for i, d in enumerate(diffs):
        if d > 0:
            positives.append((max_downs[i], d, i))
        elif d < 0:
            negatives.append((-max_downs[i], d, i))
        else:
            zeros.append((max_downs[i], d, i))

    positives.sort()
    zeros.sort()
    negatives.sort()
    pos = 0
    for down, diff, i in positives:
        if down > pos:
            return False
        pos += diff
    for down, diff, i in zeros:
        if down > pos:
            return False
        pos += diff
    for down, diff, i in negatives:
        if down > pos:
            return False
        pos += diff

    assert pos == 0
    return True


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

Submission status: Wrong Answer

Solution code:
n=int(input())
ch=True
fd=0
inv=0
bk=0
sm=0
for t in range (n):
    s=input()
    l=len(s)
    i=0
    curr=0
    m=l+1
    for i in range (l):
        if s[i]=='(':
            curr+=1
        else:
            curr-=1
        m=min(m,curr)
    if m<curr and m<0:
        ch=False
        inv+=1
    elif curr>0:
        fd+=1
    elif curr<0:
        bk+=1
    sm+=curr
    #print(m,curr,ch)
if ch and sm==0:
    print("Yes")
elif sm==0 and inv>0 and fd>0:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():  
    N = int(input())
    flag1 = False
    flag2 = False
    left = 0
    right = 0
    for _ in range(N):
        s = input()
        stack = ['-']
        for t in s:
            if t == '(':
                stack.append(t)
            else:
                if stack[-1] == '(':
                    stack.pop()
                else:
                    stack.append(')')
        if len(stack) == 1:
            continue
        elif stack[1] == '(':
            flag1 = True
            left += len(stack) - 1
        elif len(stack) >= 3  and stack[1] == ')' and stack[-1] == '(':
            for i in range(len(stack)):
                if stack[i] == '(':
                    s = i
                    break
            left += len(stack) - s
            right += s - 1
        else:
            flag2 = True
            right += len(stack) - 1
    if flag1 and flag2 and right == left:
        print('Yes')
    else:
        print('No') 
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

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

is_opened = False

acc = "".join(S)
n_open = 0
flag = True
for c in acc:
    if c == ")":
        n_open -= 1
    else:
        n_open += 1

    if n_open < 0:
        flag = False
        break
if n_open != 0:
    flag = False    

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

Submission status: Wrong Answer

Solution code:
import math
import fractions
#import sys
#input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

#a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################



n = int(input())

lr = []

for i in range(n):
    s = input()
    m = len(s)
    #exam left
    count = 0
    left = 0
    for j in range(m):
        if(s[j]=='('):
            count += 1
        else:
            if(count == 0):
                left+=1
            else:
                count -=1
    #exam right
    count = 0
    right = 0
    for j in range(m):
        if(s[m-j-1]==')'):
            count += 1
        else:
            if(count == 0):
                right+=1
            else:
                count -=1

    #print(left,right)
    lr.append([left,right])

existL = 0
existR = 0
sumL = 0
sumR = 0
for i in range(n):
    sumL += lr[i][0]
    sumR += lr[i][1]
    if(lr[i][0]==0 and lr[i][1]!=0):
        existL=1
    if(lr[i][1]==0 and lr[i][0]!=0):
        existR=1

#print(lr)
if(existL*existR == 1 and sumL == sumR):
    print("Yes")
else:
    if(sumL==0 and sumR==0):
        print("Yes")
    else:
        print("No")

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())

val = []
for n in range(N):
    s = input()
    L = len(s)
    
    temp = 0
    for l in range(L):
        if s[l] == ')':
            temp -=1
        elif s[l] == '(':
            temp +=1
            
    val.append(temp)

S = sum(val)
ans = 'Yes' if S == 0 else 'No'
print(ans)

Submission status: Wrong Answer

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(key=lambda x: (x[0], -x[1]))
# print(*t, sep='\n')

is_possible = True
if len(t) > 0:
    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
                break
        if l != 0:
            is_possible = False

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

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
# L = []
start = False
end = False
left_sum = 0
right_sum = 0
for i in S:
    l_join = 0
    r_join = 0
    for j in i:
        if j == '(':
            r_join += 1
        else:
            if r_join > 0:
                r_join -= 1
            else:
                l_join += 1
    if r_join == 0 and l_join == 0:
        continue
    left_sum += l_join
    right_sum += r_join
    # L.append((l_join, r_join))
    if r_join == 0:
        end = True
    if l_join == 0:
        start = True
if (left_sum == right_sum) and start and end:
    print('Yes')
else:
    print('No')