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

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

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

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

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

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

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

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

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

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

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

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

show_flg=False
show_flg=True
ans=0

mo=998244353

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

fl=True

if L!=R:
    fl=False
    
b.sort(key=lambda x:-x[0])

x=0

for i in b:
    sc,lv,l,r,m,M=i
    if x+m<0:
        fl=False
        
    x+=lv

#    show(i)

if x==0:
    fl=fl and True
    

print(Yn[not fl])

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)]
llst=[]
lr=[]
rlst=[]
for n in range(N):
    l=0
    r=0
    for i in range(len(S[n])):
        if S[n][i]=="(":
            l+=1
        else:
            if l>0:
                l-=1
            else:
                r+=1
    #print(l,r)
    if l and not r:
        llst.append(l)
    elif not l and r:
        rlst.append(r)
    elif l or r:
        lr.append([l,r])
llst=sum(llst)
rlst=sum(rlst)

if not llst and not rlst and not lr:
    print("Yes")
    exit()
stack=[]
idleR=10**7
if lr:
    L,R=lr[0]
    stack=[[L,R]]
    for n in range(1,len(lr)):
        #print(stack)
        L,R=lr[n]
        visited=set()
        nstack=[]
        while stack:
            l,r=stack.pop()
            for xl,xr in [[l+L-R,r],[l,r+R-L]]:
                if xl>=0 and xr>=0:
                    X=xl+idleR*xr
                    if not X in visited:
                        visited.add(X)
                        nstack.append([xl,xr])
if not stack:
    if llst-rlst==0:
        print("Yes")
    else:
        print("No")
    exit()

for l,r in stack:
    if l<=rlst:

        rlst-=l
        l=0
    else:
        continue
    if r<=llst:

        llst-=r
        r=0
    else:
        continue

    if llst-rlst==0:
        print("Yes")
    else:
        print("No")
print("No")

Submission status: Wrong Answer

Solution code:
class SegmentTree():
    def __init__(self, arr, func=min, ie=2**63):
        self.h = (len(arr) - 1).bit_length()
        self.n = 2**self.h
        self.ie = ie
        self.func = func
        self.tree = [ie for _ in range(2 * self.n)]
        for i in range(len(arr)):
            self.tree[self.n + i] = arr[i]
        for i in range(1, self.n)[::-1]:
            self.tree[i] = func(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, idx, x):
        idx += self.n
        self.tree[idx] = x
        while idx:
            idx >>= 1
            self.tree[idx] = self.func(self.tree[2 * idx], self.tree[2 * idx + 1])

    def query(self, lt, rt):
        lt += self.n
        rt += self.n
        vl = vr = self.ie
        while rt - lt > 0:
            if lt & 1:
                vl = self.func(vl, self.tree[lt])
                lt += 1
            if rt & 1:
                rt -= 1
                vr = self.func(self.tree[rt], vr)
            lt >>= 1
            rt >>= 1
        return self.func(vl, vr)

import sys
input = sys.stdin.readline

from bisect import bisect_left, bisect_right

INF = 10**18

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

D = []

for i in range(N):
    kakko = 0
    minkakko = 0
    for j in range(len(S[i])):
        if S[i][j] == '(':
            kakko += 1
        else:
            kakko -= 1
        minkakko = min(kakko, minkakko)
    D.append((minkakko, kakko))

D.sort()
E = []

for i in range(N):
    E.append(D[i][0])


F = []
for i in range(N):
    F.append((D[i][1], i))

s = 0

st = SegmentTree(F, max, (-INF, 0))

for i in range(N):
    x = bisect_left(E, -s)

    if x >= N:

        print('No')
        break
    v = st.query(x, N)
    if v[0] == -INF:
        print('No')

        break
    s += v[0]
    st.set(v[1], (-INF, v[1]))
    if s < 0:
        print('No')
        break
else:
    if s == 0:
        print('Yes')
    else:
        print('No')

Submission status: Wrong Answer

Solution code:
from itertools import permutations
n = int(input())
s = [input() for i in range(n)]
ls=list() #mn,end
for i in range(n):
    now = 0
    mn = 0
    for c in s[i]:
        if c == '(':
            now += 1
        else:
            now -= 1
            mn = min(mn,now)
    ls.append([now,mn])

ls.sort(reverse=True)
tmn = 0
tend =0
for end,mn in ls:
    tmn = mn + tend
    tend += end
    if tmn < 0 or tend < 0:
        print("No")
        break
else:
    if tend != 0:
        print("No")
    else:
        print('Yes')

Submission status: Wrong Answer

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)
from heapq import heappush, heappop

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

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def rangeI(it, l, r):
    for i, e in enumerate(it):
        if l <= i < r:
            yield e
        elif l >= r:
            break

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

INF = 999999999999999999999999
MOD = 10**9+7

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

left = 0
right = 0

l_ok = [False] * n
r_ok = [False] * n
lmr = [0] * n
min_lmr = [INF] * n

for i,s in enumerate(S):
    l = 0
    r = 0
    lok = True
    for j,c in enumerate(s):
        if c == "(":
            l += 1
        else:
            r += 1
            if r > l:
                lok = False
            min_lmr[i] = min(min_lmr[i], l-r)
    lmr[i] = l - r
    l = 0
    r = 0
    rok = True
    for j in range(len(s)-1, -1, -1):
        if s[j] == "(":
            l += 1
            if l > r:
                rok = False
                break
        else:
            r += 1

    left += s.count("(")
    right += s.count(")")

    l_ok[i] = lok
    r_ok[i] = rok

# log(l_ok)
# log(r_ok)

if left != right:
    print("No")
    exit()

strs = []

# LeftOKを並べる
for i in range(n):
    if l_ok[i]:
        strs.append(S[i])

# LeftもRightもだめなやつをminL-Rが多い順に並べる
ngs = []
for i in range(n):
    if not l_ok[i] and not r_ok[i]:
        # ngs.append((-1 * min_lmr[i], -1 * lmr[i], i))
        ngs.append((lmr[i]<0, -1 * min_lmr[i], -1 * lmr[i], i))

ngs.sort()

for ng in ngs:
    strs.append(S[ng[2]])

# RightOKを並べる
for i in range(n):
    if r_ok[i] and not l_ok[i]:
        strs.append(S[i])

# log(ngs)
# log(min_lmr)
# log("".join(strs))

l = 0
r = 0
for s in strs:
    for j,c in enumerate(s):
        if c == "(":
            l += 1
        else:
            r += 1
            if r > l:
                print("No")
                exit()
print("Yes")

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    a = [input() for i in range(n)]
    s = []
    for i in range(n):
        p = 0
        m = 0
        for j in a[i]:
            if j == "(":
                p += 1
            else:
                p -= 1
            if p < m:
                m = p
        s.append((m,p))
    s.sort(key=lambda x:(-x[0],-x[1]))
    q = []
    k = 0
    for m,p in s:
        if m+k >= 0:
            heappush(q,-p)
        if not q:
            print("No")
            return
        k -= heappop(q)
    if k > 0:
        print("No")
    else:
        print("Yes")
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
n = int(input())
S = []
L = []
R = []
for _ in range(n):
  s = input()
  state = [0,0]
  for c in s:
    if c == ')' and state[1]==0:
      state[0] += 1
    elif c ==')':
      state[1] -= 1
    elif c == '(':
      state[1] += 1
  if state[0]==state[1] == 0:
    continue
  if state[0] > state[1]:
    L.append(state)
  else:
    R.append(state)

x,y = 0,0
for l,r in R+L:
  y -= l
  if y <0:
    x -= y
  y = r
if x==y==0:
  print('Yes')
else:
  print('No')

Submission status: Wrong Answer

Solution code:
#かっこ列とは…( = +1 ) = -1「途中でマイナスにならない」
N = int(input())
AllMinPlus = []
AllMinMinus = []
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)
    if minkakko >= 0:
        AllMinPlus.append((cur,minkakko))
    else:
        AllMinMinus.append((cur,minkakko))
AllMinPlus.sort(key = lambda x:x[1],reverse=True)
AllMinMinus.sort(key = lambda x:x[1])
AllMin = AllMinPlus + AllMinMinus
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:
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)]
llst=[]
lr=[]
rlst=[]
for n in range(N):
    l=0
    r=0
    for i in range(len(S[n])):
        if S[n][i]=="(":
            l+=1
        else:
            if l>0:
                l-=1
            else:
                r+=1
    #print(l,r)
    if l and not r:
        llst.append(l)
    elif not l and r:
        rlst.append(r)
    elif l or r:
        lr.append([l,r])
llst=sum(llst)
rlst=sum(rlst)

if not llst and not rlst and not lr:
    print("Yes")
    exit()
stack=[]
idleR=10**7
if lr:
    L,R=lr[0]
    stack=[[L,R]]
    for n in range(1,len(lr)):
        #print(stack)
        L,R=lr[n]
        visited=set()
        nstack=[]
        while stack:
            l,r=stack.pop()
            for xl,xr in [[l+L-R,r],[l,r+R-L]]:
                if xl>=0 and xr>=0:
                    X=xl+idleR*xr
                    if not X in visited:
                        visited.add(X)
                        nstack.append([xl,xr])
if not stack:
    if llst-rlst==0:
        print("Yes")
    else:
        print("No")
    exit()

for l,r in stack:
    if l<=llst:

        llst-=l
        l=0
    else:
        continue
    if r<=rlst:

        rlst-=r
        r=0
    else:
        continue

    if llst-rlst==0:
        print("Yes")
    else:
        print("No")
print("No")

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    tp = 0 
    tm = []
    left = 0
    right = 0
    for i in range(N):
        S = input()
        w = 0
        wl = 0
        l = 0
        r = 0
        for j in S:
            if j == '(':
                l += 1
                wl += 1
            else:
                r += 1
                w -= 1
                w += wl
                wl = 0
        left += l
        right += r
        if w >= 0:
            tp += (l - r)
        else:
            tm.append((l - r, -w))
    if left != right:
        return False
    tm.sort(key=lambda x: x[1] - x[0])
    while tm:
        tmp = []
        for i in tm:
            if i[1] <= tp:
                tp += i[0]
                if tp < 0:
                    return False
            else:
                tmp.append(i)
        if len(tmp) == len(tm):
            return False
        tm = tmp
    return True
if main():
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    tp = 0 
    tm = []
    left = 0
    right = 0
    for i in range(N):
        S = input()
        w = 0
        wl = 0
        l = 0
        r = 0
        for j in S:
            if j == '(':
                l += 1
                wl += 1
            else:
                r += 1
                w -= 1
                w += wl
                wl = 0
        left += l
        right += r
        if w >= 0:
            tp += (l - r)
        else:
            tm.append((l - r, -w))
    if left != right:
        return False
    tm.sort(key=lambda x: x[0] - x[1])
    while tm:
        tmp = []
        for i in tm:
            if i[1] <= tp:
                tp += i[0]
                if tp < 0:
                    return False
            else:
                tmp.append(i)
        if len(tmp) == len(tm):
            return False
        tm = tmp
    return True
if main():
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys


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


def calc(S):
    tmp = 0
    MIN = 0
    for s in S:
        if s == "(":
            tmp += 1
        else:
            tmp -= 1
        MIN = min(tmp, MIN)

    return -MIN, tmp


cnts = []
for s in ss:
    dpeth, up = calc(s)
    if up >= 0:
        cnts.append((1, -dpeth, up, s))
    else:
        cnts.append((-1, -dpeth, up, s))

cnts.sort(reverse=True)
# print(cnts)

tmp = 0
for f, d, u, _ in cnts:
    if tmp + d < 0:
        print("No")
        sys.exit()

    tmp += u

    if tmp < 0:
        print("No")
        sys.exit()


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

Submission status: Wrong Answer

Solution code:
import string

def removekakko(n,s):
    for i in range(n):
        while("()" in s[i][0]):
            s[i][0] = s[i][0].replace("()","")

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

removekakko(n,s)

for i in s:
    if(")(" in i):
        i.append(0)
    elif(")" in i):
        i.append(i.count(")"))
    else:
        i.append(-(i.count("(")))

s.sort(key=lambda x:x[0])

s2 = [[""]]
for i in s:
    s2[0][0] += i[0]

removekakko(1,s2)

if(s2[0][0] == ""):
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

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

INF = 2**62-1


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


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


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


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


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


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

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


def mt(f):
    import time

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

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

    return wrap


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

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

    sl = sum(l)
    sr = sum(r)

    bsl = sum([x[0] for x in b])
    bsr = sum([x[1] for x in b])

    if l and r and bsl + sl == bsr + sr:
        return 'Yes'

    return 'No'


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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
S = []
L = []
R = []
for _ in range(n):
  s = input()
  state = [0,0]
  for c in s:
    if c == ')' and state[1]==0:
      state[0] += 1
    elif c ==')':
      state[1] -= 1
    elif c == '(':
      state[1] += 1
  if state[0]==state[1] == 0:
    continue
  if state[0] > state[1]:
    L.append(state)
  else:
    R.append(state)

x,y = 0,0
for l,r in R+L:
  y -= l
  if y <0:
    x -= y
  y = r
if x==y==0:
  print('Yes')
else:
  print('No')

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt_list = [0,0]*n
l_zero = []
r_zero = []

for i in range(n):
    ss = input()
    l = len(ss)
    right = 0
    left=0
    for j in range(l):
        if ss[j]=='(': left+=1
        elif left>0: left-=1
        else: right+=1
    cnt_list = [left,right]
    if left==0: l_zero.append(i)
    if right==0: r_zero.append(i)

if l_zero ==[] or r_zero==[]:
    print('No')
    exit()
if len(l_zero)==1 and len(l_zero)==1 and l_zero[0]==r_zero[0]:
    print('No')
    exit()

if sum(cnt_list)==0:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import sys
import bisect

inf = 10**15
mod = 998244353
n = int(input())
s = [input() for i in range(n)]
count = []
ans = 0
tayori = 0
for i,arr in enumerate(s):
    lc = 0
    rc = 0
    for c in arr:
        if c == '(':
            rc+=1
        else:
            if rc >= 1:
                rc-=1
            else:
                lc+=1
    if lc != 0 or rc != 0:
        if lc == 0 and rc != 0:
            ans+=rc
        elif lc != 0 and rc == 0:
            tayori+=lc
        else:
            count.append([lc,rc])
count.sort(key = lambda x:x[0])
if ans == 0:
    print('No')
    sys.exit()
else:
    for tmp in count:
        l,r = tmp
        if ans > 0:
            if ans - l < 0:
                print('No')
                sys.exit()
            else:
                ans+=(r-l)
        else:
            print('No')
            sys.exit()
if ans == tayori:
    print('Yes')
else:
    print('No')

Submission status: Wrong Answer

Solution code:

import math
import sys

def input_num():
	ls = input().strip().split(" ")
	return [int(e) for e in ls]

n, = input_num()
s_ls = []
for _ in range(n):
	s_ls.append(input().strip())

r_ls = []
for s in s_ls:
	n = 0
	n_ls = [n]
	for ss in s:
		if ss == "(":
			n += 1
		else:
			n -= 1
		n_ls.append(n)
	b = min(n_ls)
	t = n_ls[-1]
	r_ls.append((t,b))

def su(s0,s1):
	return s0[0]+s1[0], max(s0[0]+s1[1], s1[0]+s0[1])

s0 = r_ls[0]
for r in r_ls[1:]:
	s0 = su(s0,r)

print("Yes" if s0[0]==0 and s0[1] >= 0 else "No")

Submission status: Wrong Answer

Solution code:
n=int(input())
mn=dict()
tot=dict()
t=0
for i in range(n):
    s=input()
    tot[i]=0
    mn[i]=0
    for j in s:
        if j=='(':tot[i] = tot[i]+1
        else: tot[i] = tot[i]-1
        mn[i] = min(mn[i],tot[i])
    t=t+tot[i]
mn=sorted(mn.items(), key = lambda kv:(kv[1], kv[0]),reverse=True)
if t!=0:
    print('No')
else:
    ok=True
    m = 0
    for k,v in mn:
        m = t + v
        t = t + tot[k]
        if m<0:
            ok=False
            print('No')
            break
    if ok:
        print('Yes')

Submission status: Wrong Answer

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

for i, x in enumerate(S):
    res = []
    q = 0
    for y in x:
        if y == ')':
            if q > 0:
                q -= 1
            else:
                res.append(y)
        else:
            q += 1
    res += ['(']*q
    S[i] = list(res)
s = [0]*N
m = [len(S[i]) for i in range(N)]
for i, x in enumerate(S):
    tmp = 0
    for j in range(len(x)):
        if x[j] == '(':
            tmp += 1
        else:
            tmp -= 1
            m[i] = min(tmp, m[i])
    s[i] = tmp

if sum(s) == 0:
    ss = [(S[i], m[i], s[i]) for i in range(N)]
    ss.sort(key=lambda x: (x[1], x[2]), reverse=True)
    tmp = 0
    for x, _, _ in ss:
        for z in x:
            if z == '(':
                tmp += 1
            else:
                tmp -= 1
                if tmp < 0:
                    print("No")
                    exit(0)
    print("Yes")

else:
    print("No")

Submission status: Wrong Answer

Solution code:

import math
import sys

def input_num():
	ls = input().strip().split(" ")
	return [int(e) for e in ls]

n, = input_num()
s_ls = []
for _ in range(n):
	s_ls.append(input().strip())

r_ls = []
for s in s_ls:
	n = 0
	n_ls = [n]
	for ss in s:
		if ss == "(":
			n += 1
		else:
			n -= 1
		n_ls.append(n)
	b = min(n_ls)
	t = n_ls[-1]
	r_ls.append((t,b))

def su(s0,s1):
	return s0[0]+s1[0], min(s0[0]+s1[1], s1[0]+s0[1])

s0 = r_ls[0]
for r in r_ls[1:]:
	s0 = su(s0,r)

print("Yes" if s0[0]==0 and s0[1] >= 0 else "No")

Submission status: Wrong Answer

Solution code:
n = int(input())
x = []
for i in range(n):
    s = input()
    while "()" in s:
        s = s.replace("()", "")
    if '(' in s:
        x.append(s.count('('))
    elif ')' in s:
        x.append(-s.count(')'))
x = sorted(x)
if len(x) % 2 != 0:
    print("No")
    exit()
for i in range(int(len(x)/2)):
    if x[i] != -x[len(x)-i-1]:
        print("No")
        exit()
print("Yes")