Problem:


Score : 600 points

Problem Statement

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

An empty string;

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

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

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

Constraints

1 \leq N \leq 10^6

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

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

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

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

Sample Input 1

2
)
(()

Sample Output 1

Yes

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

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No



Sample input:
2
)
(()


Sample output:
Yes

Submission status: Runtime Error

Solution code:

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



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

Submission status: Runtime Error

Solution code:
N=int(input())
l=[]
flags=0
flagg0=0
flag1s=0
flag1g=0
count=0
for i in range(N):
  a=input()
  A=[]
  for i in a:
    A.append(str(i))
    if i=="(":
      count+=1
    else:
      count-=1
  if flags==0:
    if A[0]="(":
      flags=1
  elif flags==1:
    if A[len(A)]==")":
      flagg=1
  if flag1s==0:
    if A[0]="(":
      flag1s=1
  elif flag1s==1:
    if A[len(A)]==")":
      flag1g=1
if ((flags==1 and flagg==1) or (flag1s==1 and flag1g==1)) and count==0:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
class SegTree:
    def __init__(self, init_val, ide_ele, segfunc):
        self.n = len(init_val)
        self.num =2**(self.n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg = [[self.ide_ele, i] for i in range (2*self.num)]
        self.segfunc = segfunc
        
        #set_val
        for i in range(self.n):
            self.seg[i+self.num-1] = init_val[i]    
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i] = segfunc(self.seg[2*i+1], self.seg[2*i+2]) 
    
    def update(self, k, x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
    
    def query(self, p, q):
        if q<=p:
            return self.ide_ele,0
        p += self.num-1
        q += self.num-2
        res = [self.ide_ele, self.ide_ele] 
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res, self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res, self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res, self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
        return res

def Int():
    return int(input())
def Ints():
    return map(int,input().split())
def IntList():
    return list(Ints())
def IntMat(N):
    return [IntList() for i in range(N)]

import sys
sys.setrecursionlimit(4100000)
rl = sys.stdin.readline

N = Int()
Sum = 0

Min = []
Now = []
Now2 = []
c = 0
for i in range(N):
    s = rl()
    now = 0
    minimum = 0
    for j in s:
        if j=='(':
            now += 1
        elif j == ')':
            now -= 1
        minimum = min(minimum,now)
    Sum += now
    
    if minimum<0:
        Min.append(minimum)
        Now.append([now, c])
        c += 1
    else:
        Now2.append(now)
    #A.append([minimum,now])

#print(Min)
#print(Now)
#print(Now2)
#print(A)
# zipで二つの配列を統合
c = zip(Min, Now)
# 統合していた配列をもとに戻す
Min, Now = zip(*sorted(c))
    
if Sum!=0:
    print('No')
    sys.exit()

INF = 10**15
ide_ele = -INF
Seg = SegTree(Now,ide_ele,max)

import bisect

count = 0
now = 0

for j in Now2:
    now += j

#print(Min)
#print(Now)

LL = len(Now)

for _ in range(LL):
    i = bisect.bisect_left(Min,-now)
    #print(i,N)
    j,k = Seg.query(i, LL)
    
    #print(j)
    now += j
    Seg.update(k,[-INF,k])
    
    if now<0:
        print('No')
        sys.exit()

print('Yes')

Submission status: Runtime Error

Solution code:
def kakko():
  cnt1 = 0
  cnt2 = 0
  for ch in s:
    if ch == "(":
      cnt1 += 1
    else:
      cnt1 -= 1
      cnt2 = min(cnt1, cnt2)
  return - (cnt1 * (10 ** 7) + cnt2)

n = int(input())

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

s.sort(key=kakko)
ss = "".join(s)

cnt0 = 0
flag = True
for ch in range(ss):
  if ch == "(":
    cnt0 += 1
  else:
    cnt0 -= 1
    if cnt0 < 0:
      flag = False

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

Submission status: Runtime Error

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

Solution code:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(10**9)
from collections import deque
import heapq
from itertools import combinations
import bisect

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

p=0
q=0
for i in range(n):
    for j in l[i]:
        if j=='(':
            p+=1
        else:
            q+=1
if p!=q:
    print('No')
    exit()
pl=[]
ql=[]
ml=[]
for i in range(n):
    a=l[i]
    p=0
    q=0
    for j in a:
        if j=='(':
            p+=1
        else:
            q+=1
    if p>q:
        pl.append(a)
    elif p<q:
        ql.append(a)
    else:
        ml.append(a)
# if pl:
#     pl.sort()
# if ql:
#     ql.sort()
# if ml:
#     ml.sort()
# if pl:
#     if pl[0][0]==')':
#         print('No')
#         exit()
# else:
#     if ml[0][0]==')':
#         print('No')
#         exit()

# if ql:
#     if ql[-1][-1]=='(':
#         print('No')
#         exit()
# else:
#     if ml[-1][-1]=='(':
#         print('No')
#         exit()


if pl:
    pp=[]
    for i in pl:
        d=0
        t=0
        for j in i:
            if j=='(':
                d+=1
            else:
                d-=1
            t=max(t,-d)
        pp.append([t,d])
    pp.sort(key=lambda x: x[0]*(10**6)-x[1])
    dd=0
    for a,b in pp:
        if dd<a:
            print('No')
            exit()
        dd+=b-a
if ml:
    pp=[]
    for i in ml:
        d=0
        t=0
        for j in i:
            if j=='(':
                d+=1
            else:
                d-=1
            t=max(t,-d)
        pp.append([t,d])
    pp.sort(key=lambda x: x[0]*(10**6)-x[1])
    #d=0
    for a,b in pp:
        if dd<a:
            print('No')
            exit()
        dd+=b-a

if ql:
    pp=[]
    for i in ql:
        d=0
        t=0
        for j in range(len(i)):
            if i[len(i)-1-j]==')':
                d+=1
            else:
                d-=1
            t=max(t,-d)
        pp.append([t,d])
    pp.sort(key=lambda x: x[0]*(10**6)-x[1])
    dd=0
    for a,b in pp:
        if dd<a:
            print('No')
            exit()
        dd+=b-a

if ml:
    pp=[]
    for i in ml:
        d=0
        t=0
        for j in range(len(i)):
            if i[len(i)-1-j]==')':
                d+=1
            else:
                d-=1
            t=max(t,-d)
        pp.append([t,d])
    pp.sort(key=lambda x: x[0]*(10**6)-x[1])
    for a,b in pp:
        if dd<a:
            print('No')
            exit()
        dd+=b-a


print('Yes')

Submission status: Runtime Error

Solution code:
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
def pri(x): print('\n'.join(map(str, x)))

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

a = []
for li in L:
    l = li.count('(')
    r = li.count(')')
    if l != r:
        a.append((l, r))
al = sorted(a, key=lambda x: x[0])
ar = sorted(a, key=lambda x: x[1])
ar.sort(reversed=True)

if al == ar:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
class SegTree:
    def __init__(self, init_val, ide_ele, segfunc):
        self.n = len(init_val)
        self.num =2**(self.n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg = [[self.ide_ele, i] for i in range (2*self.num)]
        self.segfunc = segfunc
        
        #set_val
        for i in range(self.n):
            self.seg[i+self.num-1] = init_val[i]    
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i] = segfunc(self.seg[2*i+1], self.seg[2*i+2]) 
    
    def update(self, k, x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
    
    def query(self, p, q):
        if q<=p:
            return self.ide_ele,0
        p += self.num-1
        q += self.num-2
        res = [self.ide_ele, self.ide_ele] 
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res, self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res, self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res, self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
        return res

def Int():
    return int(input())
def Ints():
    return map(int,input().split())
def IntList():
    return list(Ints())
def IntMat(N):
    return [IntList() for i in range(N)]

import sys
sys.setrecursionlimit(4100000)
rl = sys.stdin.readline

N = Int()
Sum = 0

Min = []
Now = []
Now2 = []

for i in range(N):
    s = rl()
    now = 0
    minimum = 0
    for j in s:
        if j=='(':
            now += 1
        elif j == ')':
            now -= 1
        minimum = min(minimum,now)
    Sum += now
    
    if minimum<0:
        Min.append(minimum)
        Now.append([now, i])
    else:
        Now2.append(now)
    #A.append([minimum,now])

#print(A)
# zipで二つの配列を統合
c = zip(Min, Now)
# 統合していた配列をもとに戻す
Min, Now = zip(*sorted(c))
    
if Sum!=0:
    print('No')
    sys.exit()

INF = 10**15
ide_ele = -INF
Seg = SegTree(Now,ide_ele,max)

import bisect

count = 0
now = 0

for j in Now2:
    now += j

#print(Min)
#print(Now)

LL = len(Now)

for _ in range(LL):
    i = bisect.bisect_left(Min,-now)
    #print(i,N)
    j,k = Seg.query(i, LL)
    
    #print(j)
    now += j
    Seg.update(k,[-INF,k])
    
    if now<0:
        print('No')
        sys.exit()

print('Yes')

Submission status: Runtime Error

Solution code:
def kakko():
  cnt1 = 0
  cnt2 = 0
  for ch in s:
    if ch = "(":
      cnt1 += 1
    else:
      cnt1 -= 1
      cnt2 = min(cnt1, cnt2)
  return cnt1 * (10 ** 7) + cnt2

n = int(input())

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

s.sorted(key=kakko)
ss = "".join(s)

cnt0 = 0
flag = True
for ch in range(ss):
  if ch = "(":
    cnt0 += 1
  else:
    cnt0 -= 1
    if cnt0 < 0:
      flag = False

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

Submission status: Runtime Error

Solution code:
import sys
n = int(stdin.readline().rstrip())
s = [stdin.readline().rstrip() for _ in range(n)]
print(s)

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

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

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

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

        dl.append([dd, dd_min])

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

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

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

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

            idx = bisect_left(d_min, -carry)

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

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

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

        if f and carry == 0:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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.items():
        m = t + v
        t = t + tot[k]
        if m<0:
            ok=False
            print('No')
            break
    if ok:
        print('Yes')

Submission status: Runtime Error

Solution code:
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
def pri(x): print('\n'.join(map(str, x)))

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

a = []
for li in L:
    l = li.count('(')
    r = li.count(')')
    if l != r:
        a.append((l, r))
al = a.sort(key=lambda x: x[0])
ar = a.sort(key=lambda x: x[1])
ar.sort(reversed=True)

if al == ar:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
# 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
def run():
    N = int(input())
    ret = 0
    for _ in range(N):
        S = sysread()
        for s in S:
            ret += dic[s]
    if ret == 0:
        print('Yes')
    else:
        print('No')
if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
n = int(input())
x = []
for i in range(n):
    s = input()
    while "()" in s:
        s = s.replace("()", "")
    if '(' in s:
        x.append(len(s))
    elif ')' in s:
        x.append(-len(s))
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]:
        print("No")
        exit()
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np



n = int(input())
s = []
s_num = np.zeros(n)
s_num_min = np.zeros(n)
for i in range(n):
    kakko_in = input()
    s.append(kakko_in)
    for s_in in kakko_in:
        if s_in == '(':
            s_num[i] += 1
        else:
            s_num[i] -= 1
        if s_num[i] < s_num_min[i]:
            s_num_min[i] = s_num[i]

if np.sum(s_num) != 0:
    print(np.sum(s_num), "No")
else:
    now_sum = 0
    now_min_sum = 0
    s_num_index = s_num.argsort()[::-1]
    s_num_min_index = s_num_min.argsort()[::-1]
    # print(s_num_index)
    # print(s_num_min_index)
    yet = [1 for _ in range(n)]


    def nap(i1, i2, yet, now_sum, now_min_sum):
        bool1 = 0
        bool2 = 0
        if i1 < n:
            i01 = s_num_index[i1]
            if yet[i01] and now_min_sum+s_num_min[i1] >= 0:
                yet[i01] = 0
                bool1 = nap(i1+1, i2, yet, now_sum+s_num[i01], now_min_sum+s_num_min[i01])
                yet[i01] = 1
        if i2 < n:
            i02 = s_num_min_index[i2]
            if yet[i02] and now_sum+s_num[i2] >= 0:
                yet[i02] = 0
                bool2 = nap(i1, i2+1, yet, now_sum+s_num[i02], now_min_sum+s_num_min[i02])
                yet[i02] = 1
        if sum(yet) == 0:
            return 1
        if bool1 == 1 or bool2 == 1:
            return 1
        else:
            return 0


    if nap(0, 0, yet, 0, 0):
        print("Yes")
    else:
        print("No")

Submission status: Runtime Error

Solution code:
def no():
    print("No")
    exit()

def yes():
    print("Yes")
    exit()

n = int(input())
def change(string):
    return [1 if c == "(" else -1 for c in string]
s = [change(input()) for i in range(n)]
t = []
k = 0
for si in s:
    minimum = 0
    cur = 0
    for c in si:
        cur += c
        if minimum > cur:
            minimum = cur
    if minimum == 0:
        k += cur
    else:
        t.append((minimum, cur))

t.sort(key = lambda x: (-x[0]))
nxt = []
for ti in t:
    x,y = ti
    if y>=0 and k+x>=0:
        k += y
    else:
        nxt.append(ti)

if any(y >= 0 for x,y in nxt):
    no()

if -sum(y for x,y in nxt) != k:
    no()

print(nxt[10000000000])
nxt.sort(key=lambda x: (x[0], -x[1]))
for x,y in nxt:
    if k+x < 0:
        no()
    k += y

if k == 0:
    yes()
else:
    no()

Submission status: Runtime Error

Solution code:
N = int(input())
LR = [[0]*2 for i in range(N)]
for i in range(N):
    S = input()
    M = len(S)
    L = 0
    R = 0
    R0 = 0
    t = 0
    if S[0]==")":
        while t<M:
            if S[t]==")":
                R0+=1
                t+=1
            else:
                t+=1
                break
    while t<M:
        if S[t]=="(":
            t+=1
            L+=1
        else:
            t+=1
            R+=1
    if L>R:
        LR[i][0]=L-R
        LR[i][1]=R0
    if L<R:
        LR[i][0]=0
        LR[i][1]=R0+R-L
    if L==R:
        LR[i][0]=0
        LR[i][1]=R0

LP = 0
RP = 0
S = []
for i in range(N):
    L = LR[i][0]
    R = LR[i][1]
    if (L==0)and(R==0):
        continue
    elif L==0:
        RP += R
    elif R==0:
        LP += L
    else:
        S.append([LS,RS])

if (LP==RP)and(len(S)==0):
    print("Yes")

else:
    L = LP
    for i in range(len(S)):
        L += -1*S[i][1]
        L += S[i][0]
    if L == RP:
        print("Yes")
    else:
        print("No")

Submission status: Runtime Error

Solution code:
class SegTree:
    def __init__(self, init_val, ide_ele, segfunc):
        self.n = len(init_val)
        self.num =2**(self.n-1).bit_length()
        self.ide_ele = ide_ele
        self.seg = [[self.ide_ele, i] for i in range (2*self.num)]
        self.segfunc = segfunc
        
        #set_val
        for i in range(self.n):
            self.seg[i+self.num-1] = init_val[i]    
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i] = segfunc(self.seg[2*i+1], self.seg[2*i+2]) 
    
    def update(self, k, x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
    
    def query(self, p, q):
        if q<=p:
            return self.ide_ele,0
        p += self.num-1
        q += self.num-2
        res = [self.ide_ele, self.ide_ele] 
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res, self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res, self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res, self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
        return res

def Int():
    return int(input())
def Ints():
    return map(int,input().split())
def IntList():
    return list(Ints())
def IntMat(N):
    return [IntList() for i in range(N)]

import sys
sys.setrecursionlimit(4100000)
rl = sys.stdin.readline

N = Int()
Sum = 0

Min = []
Now = []
Now2 = []

for i in range(N):
    s = rl()
    now = 0
    minimum = 0
    for j in s:
        if j=='(':
            now += 1
        elif j == ')':
            now -= 1
        minimum = min(minimum,now)
    Sum += now
    
    if minimum<0:
        Min.append(minimum)
        Now.append([now, i])
    else:
        Now2.append(now)
    #A.append([minimum,now])

#print(A)
# zipで二つの配列を統合
c = zip(Min, Now)
# 統合していた配列をもとに戻す
Min, Now = zip(*sorted(c))
    
if Sum!=0:
    print('No')
    sys.exit()

INF = 10**15
ide_ele = -INF
Seg = SegTree(Now,ide_ele,max)

import bisect

count = 0
now = 0

for j in Now2:
    now += j

#print(Min)
#print(Now)

LL = len(Now)

for _ in range(LL):
    i = bisect.bisect_left(Min,-now)
    #print(i,N)
    j,k = Seg.query(i, N)
    
    #print(j)
    now += j
    Seg.update(k,[-INF,k])
    
    if now<0:
        print('No')
        sys.exit()

print('Yes')

Submission status: Runtime Error

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N = I()
    landr = []
    lonly = 0
    ronly = 0
    for i in range(N):
        t = S()
        left = 0
        right = 0
        for c in t:
            if c == '(':
                left += 1
            else:
                if left > 0:
                    left -= 1
                    continue
                else:
                    right += 1
        if left == 0 and right > 0:
            ronly += right
        if left > 0 and right == 0:
            lonly += left
        if left > 0 and right > 0:
            landr.append((left, right))
        if left == 0 and right == 0:
            continue
    if landr == []:
        if lonly == ronly:
            print("Yes")
        else:
            print("No")
        return
    f = landr[0]
    fl, fr = f[0], f[1]
    if len(landr) == 1:
        print("No")
        return
    for elem in range(1, len(landr)):
        left, right = elem
        newl, newr = 0, 0
        if fr > left:
            fr -= left
            newl = fl
            newr = fr + right
        else:
            left -= fr
            newl = fl + left
            newr = right
        fl = newl
        fr = newr
        if fl == lonly and fr == ronly:
            print("Yes")
        else:
            print("No")

main()

Submission status: Runtime Error

Solution code:
import itertools

n = int(input())

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

comb_s = list(itertools.combinations(s, len(s)))

def checker(x):
    jud = 1
    ans = ''.join(x)

    if not s:
        return jud

    print(ans)
    r = x.count('(')
    l = x.count(')')
    if r != l:
        jud =0
        return jud

    if x[0] != '(' or x[-1] != ')':
        jud =0

    return jud

def main():
    for i in range(len(comb_s)):
        print(comb_s[i])
        juds = checker(''.join(for j in comb_s[i]))
        if juds == 1:
            print('Yes')
            return

    print('No')
    return
main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
# MOD = 10**9+7
# MOD = 998244353


def count(idx, s):
    left = right = 0
    for i in range(len(s)):
        if s[i] == "(":
            left += 1
        else:
            if left > 0:
                left -= 1
            else:
                right += 1

    return left, right, idx


n = int(input())
S = [input() for i in range(n)]
A = [count(i, s) for i, s in enumerate(S)]
A.sort(key=lambda x: (x[1], x[1]-x[0]))

left_rem = 0
for left, right in A:
    left_rem -= right
    if left_rem < 0:
        print("No")
        exit()
    left_rem += left

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

Submission status: Runtime Error

Solution code:
N=int(input())
l = '('
r = ')'
S = {l:0,r:0}
for _ in range(N):
  s = {l:0,r:0}
  for v in input():
    if v == r:
      if s[l]>0:s[l]-=1
      else: s[r]+=1
    else:
      if s[l]+=1
  if min(S[l],s[r]) < min(S[r],s[l]):
    if S[r] < s[l]:
      S[r]=s[r]
      S[l]+=(s[l]-S[r])
    else:
      S[l] = s[l]
      S[r]+= (s[r]-S[l])
  else:
    if S[l] < s[r]:
      S[l] = s[l]
      S[r] += (s[r]-S[l])
    else:
      S[r] = s[r]
      S[l] += (s[l]-S[r])
if S[r]==0 and S[l] == 0:
  print('Yes')
else:
  print('No')

Submission status: Runtime Error

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import math
sys.setrecursionlimit(4100000)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
input=lambda :sys.stdin.readline().rstrip()
N=int(input())
S=[input() for i in range(N)]
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=[]
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==0 and r-rlst==0:
        print("Yex")
        exit()
print("No")

Submission status: Runtime Error

Solution code:
from functools import reduce
from itertools import permutations

def f(s):
    while True:
        t = s.replace('()', '')
        if t == s:
            return s
        s = t

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

l = 0
r = 0
for s in S:
    t = s.count('(')
    l += t
    r += len(s) - t
if l != r:
    print('No')
    exit()

S = [s for s in map(f, S) if s != ""]

if len(S) == 0:
    print('Yes')
    exit()

lS = [s for s in S if s[0] == "("]
rS = [s for s in S if s[0] == ")"]

ld = {}
for s in lS:
    ld.setdefault(s, 0)
    ld[s] += 1

rd = {}
for s in rS:
    rd.setdefault(s, 0)
    rd[s] += 1

for k1 in ld:
    for k2 in rd.keys():
        if f(k1 + k2) != '':
            continue
        t = max(ld[k1], rd[k2])
        ld[k1] -= t
        rd[k2] -= t

if len(ld) == 0 and len(rd) == 0:
    print('Yes')
    exit()

SS = []
for k in ld:
    for i in range(ld[k]):
        SS.append(k)
for k in rd:
    for i in range(rd[k]):
        SS.append(k)

for ss in permutations(SS, len(SS)):
    t = reduce(lambda x, y: x + y, ss)
    if f(t) == '':
        print('Yes')
        exit()
print('No')

Submission status: Runtime Error

Solution code:
n=int(input())
A=[]
B=[]
c=0
for i in range(n):
  S=input()
  a=0
  b=0
  for j in range(len(S)):
    if S[j]=="(":
      a=a+1
    else:
      a=a-1
      if a<b:
        b=a
  if b==0:
    c=c+a
  elif a>0:
    B.append([b,-1*a])
  else:
    A.append([-1*b,a])
A.sort()
B.sort()
f=0
for i in range(len(B)):
  if c+B[i][0]<0:
    f=1
  c=c-A[i][1]
for i in range(len(A)):
  if c-A[i][0]<0:
    f=1
  c=c+A[i][1]
if c!=0:
  f=1
if f==0:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
n=int(input())
A=[]
B=[]
c=0
for i in range(n):
  S=input()
  a=0
  b=0
  for j in range(len(S)):
    if S[j]=="(":
      a=a+1
    else:
      a=a-1
      if a<b:
        b=a
  if b==0:
    c=c+a
  elif a>0:
    B.append[(b,-1*a)]
  else:
    A.append([-1*b,a])
A.sort()
B.sort()
f=0
for i in range(len(B)):
  if c+B[i][0]<0:
    f=1
  c=c-A[i][1]
for i in range(len(A)):
  if c-A[i][0]<0:
    f=1
  c=c+A[i][1]
if c!=0:
  f=1
if f==0:
  print("Yes")
else:
  print("No")