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:
def result(m, b):
    sum1 = m
    resmin = m
    for i in range(len(b)):
        resmin += b[i][0]
        if resmin < 0:
            return -1
    for i in range(len(b)):
        sum1 += b[i][1]
    if sum1 != 0:
        return -1
    return 0
n = int(input())
resmin = 10 ** 7
a = [''] * n
set_pos = []
set_neg = []
for i in range(n):
    a[i] = input().strip('\n')
for i in range(n):
    loc_min = 10 ** 7
    total = 0
    tmp = 0
    for j in range(len(a[i])):
        if a[i][j] == '(':
            tmp += 1
        else:
            tmp -= 1
        if tmp < loc_min:
            loc_min = tmp
        total = tmp
    if loc_min >= 0:
        set_pos.append((loc_min, total))
    else:
        set_neg.append((loc_min, total))
total_pos = 0
for elem in set_pos:
    total_pos += elem[1]
b = sorted(list(set_neg), key = lambda l: l[0], reverse = True)
res = result(total_pos, b)
print('No' if res == -1 else 'Yes')

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
import collections
def gb(s):
	stack = collections.deque()
	for l in s:
		if l == '(':
			stack.append(l)
		elif l == ')':
			if stack and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
	
	for i in range(len(stack)):
		if stack[i] == '(':
			return (len(stack) - i, i)
			break

	return (0, len(stack))
	
r  = [gb(raw_input()) for _ in range(n)]
def f(r):
	r.sort(key = lambda x:(x[1],-(x[0]- x[1]),-x[0]))
	bal = 0
	for a,b in r:
		bal -= b
		if bal < 0: return False
		bal += a
		if bal < 0: return False
	return bal == 0
print 'Yes' if f(r) else 'No'

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
import collections
def gb(s):
	stack = []
	for l in s:
		if l == '(':
			stack.append(l)
		elif l == ')':
			if stack and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
	
	for i in range(len(stack)):
		if stack[i] == '(':
			return (len(stack) - i, i)
			break

	return (0, len(stack))
	
r  = [gb(raw_input()) for _ in range(n)]
def f(r):
	r.sort(key = lambda x:(-(x[0]- x[1]),x[1],x[0]))
	bal = 0

	for a,b in r:
		bal -= b
		if bal < 0: return False
		bal += a
		if bal < 0: return False
	return bal == 0
print 'Yes' if f(r) else 'No'

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
import collections
def gb(s):
	stack = []
	for l in s:
		if l == '(':
			stack.append(l)
		elif l == ')':
			if stack and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
	
	for i in range(len(stack)):
		if stack[i] == '(':
			return (len(stack) - i, i)
			break

	return (0, len(stack))
	
r  = [gb(raw_input()) for _ in range(n)]
def f(r):
	r.sort(key = lambda x:(-(x[0]- x[1]),x[1],x[0]))
	bal = 0

	print r
	for a,b in r:
		bal -= b
		if bal < 0: return False
		bal += a
		if bal < 0: return False
	return bal == 0
print 'Yes' if f(r) else 'No'

Submission status: Wrong Answer

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

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


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


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

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

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

Submission status: Wrong Answer

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

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


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


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

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

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

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
def gb(s):
	bal = 0
	m = 0
	for l in s: 
		bal += 1 if l == '(' else -1
		m = min(m, bal)
	return (bal,m)
r  = [gb(raw_input()) for _ in range(n)]

def f(r):
	r.sort(key = lambda x:(-x[1],-x[0]))
	s = 0
	for aa,bb in r:
		if s + aa < 0 or s + bb < 0: return False
		s += aa
	return s == 0
print 'Yes' if f(r) else 'No'

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

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


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


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


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

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

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
def gb(s):
	bal = 0
	m = 0
	for l in s: 
		bal += 1 if l == '(' else -1
		m = min(m, bal)
	return (bal,m)
r  = [gb(raw_input())for _ in range(n)]
def f(r):
	r.sort(key = lambda x:(-x[1],-x[0]))
	s = 0
	for aa,bb in r:
		if s + aa < 0: return False
		if s + bb < 0: return False
		s += aa
	return True

	
if sum([e[0] for e in r]) == 0:
	print 'Yes' if f(r) else 'No'
else:
	print 'No'
#is there a gready way to build a sum such that 
#
#fpor all psum prefix >=0 
#and 
#print r

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
def gb(s):
	bal = 0
	m = 0
	for l in s: 
		bal += 1 if l == '(' else -1
		m = min(m, bal)
	return (bal,0)
r  = [gb(raw_input())for _ in range(n)]

def f(r):

	r.sort(key = lambda x:(-x[1],-x[0]))
	s = 0
	
	for aa,bb in r:

		if s + aa < 0:
			return False
		if s + bb < 0:
			return False
		s += aa
		
	return True

	
if sum([e[0] for e in r]) == 0:
	print 'Yes' if f(r) else 'No'
else:
	print 'No'
#is there a gready way to build a sum such that 
#
#fpor all psum prefix >=0 
#and 
#print r

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
def gb(s):
	bal = 0
	for l in s: bal += 1 if l == '(' else -1
	return bal
r  = [gb(raw_input())for _ in range(n)]

if sum(r) == 0:
	print 'Yes'
else:
	print 'No'
#is there a gready way to build a sum such that 
#
#fpor all psum prefix >=0 
#and 
#print r

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# (と)の数は同じ、最下点に注目
N = ir()
S = [[1 if x == '(' else -1 for x in list(sr())] for _ in range(N)]
pos = []
neg = []
for s in S:
    temp = 0
    mi = 0
    for x in s:
        temp += x
        if temp < mi:
            mi = temp
    if temp >= 0:
        pos.append((mi, temp))
    else:
        neg.append((mi+temp, -temp))

pos.sort(reverse=True)
neg.sort(reverse=True)
cur_p = 0; cur_n = 0
bl = True
for m, p in pos:
    if cur_p + m < 0:
        bl = False
    cur_p += p

for m, n in neg:
    if cur_p + m < 0:
        bl = False
    cur_n += n

if cur_p != cur_n:
    bl = False

print('Yes' if bl else 'No')

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# (と)の数は同じ、最下点に注目
N = ir()
S = [[1 if x == '(' else -1 for x in list(sr())] for _ in range(N)]
pos = []
neg = []
for s in S:
    temp = 0
    mi = 0
    for x in s:
        temp += x
        if temp < mi:
            mi = temp
    if temp >= 0:
        pos.append((mi, temp))
    else:
        neg.append((mi-temp, -temp))

pos.sort(reverse=True)
neg.sort(reverse=True)
cur_p = 0; cur_n = 0
bl = True
for m, p in pos:
    if cur_p + m < 0:
        bl = False
    cur_p += p

for m, n in neg:
    if cur_p + m < 0:
        bl = False
    cur_n += n

if cur_p != cur_n:
    bl = False

print('Yes' if bl else 'No')

Submission status: Wrong Answer

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

lst.sort()
txt = 'No'

c = 0
for i in lst:
    for j in i:
        c += 1 if j == '(' else -1
        if c < 0:
            break

if c == 0:
    txt = 'Yes'

print(txt)

Submission status: Wrong Answer

Solution code:

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

lst.sort()
d = {'(': 0, ')': 0}
txt = 'No'

for i in lst:
    # print(f"{i = }")
    for j in i:
        # print(f"{j = }")
        d[j] += 1
        if(d['('] < d[')']):
            break

print(txt)

Submission status: Wrong Answer

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

lst.sort()
d = {'(': 0, ')': 0}
txt = 'Yes'

for i in lst:
    # print(f"{i = }")
    for j in i:
        # print(f"{j = }")
        d[j] += 1
        if(d['('] < d[')']):
            break


if(d['('] == d[')']):
    txt = 'No'

print(txt)

Submission status: Wrong Answer

Solution code:
import sys

N = int(sys.stdin.readline().strip())

S = []
for _ in range(N):
    s_i = sys.stdin.readline().strip()
    S.append(s_i)

# left bracket - right bracketを高さとした、最小の高さと最終的な高さの座標列
# ex)
# ")": (-1, -1)
# "(": (1, 1)
# "()": (1, 0)
# ")()(": (-1, 0)
# "))))(((((: (-4, 1)

plus_seqs = []
minus_seqs = []
for s_i in S:
    h = 0
    min_h = float("inf") 
    for bracket in s_i:
        if bracket == "(":
            h += 1
        else:
            h -= 1
        min_h = min(min_h, h)
            
    if h >= 0:
        plus_seqs.append((min_h, h))
    else:
        # minus_seqs.append((-1 * min_h, -1 * h))
        minus_seqs.append((min_h - h, -1 * h))

# print(plus_seqs)
# print(minus_seqs)

hight = 0
# for (min_h, h) in sorted(plus_seqs, reverse=True):
for (min_h, h) in sorted(plus_seqs):
    if hight + min_h < 0:
        print("No")
        sys.exit()
    hight += h

hight2 = 0
# for (min_h, h) in sorted(minus_seqs, reverse=True):
# for (min_h, h) in sorted(minus_seqs, key=lambda x: x[1] - x[0]):
for (min_h, h) in sorted(minus_seqs):
    if hight2 + min_h < 0:
        print("No")
        sys.exit()
    hight2 += h

# print(hight, hight2)
if hight == hight2:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys

N = int(sys.stdin.readline().strip())

S = []
for _ in range(N):
    s_i = sys.stdin.readline().strip()
    S.append(s_i)

# left bracket - right bracketを高さとした、最小の高さと最終的な高さの座標列
# ex)
# ")": (-1, -1)
# "(": (1, 1)
# "()": (1, 0)
# ")()(": (-1, 0)
# "))))(((((: (-4, 1)

plus_seqs = []
minus_seqs = []
for s_i in S:
    h = 0
    min_h = float("inf") 
    for bracket in s_i:
        if bracket == "(":
            h += 1
        else:
            h -= 1
        min_h = min(min_h, h)
            
    if h >= 0:
        plus_seqs.append((min_h, h))
    else:
        minus_seqs.append((-1 * min_h, -1 * h))

# print(plus_seqs)
# print(minus_seqs)

hight = 0
for (min_h, h) in sorted(plus_seqs, reverse=True):
    if hight + min_h < 0:
        print("No")
        sys.exit()
    hight += h

hight2 = 0
# for (min_h, h) in sorted(minus_seqs, reverse=True):
for (min_h, h) in sorted(minus_seqs, key=lambda x: x[1] - x[0]):
    if hight2 + min_h < 0:
        print("No")
        sys.exit()
    hight2 += h

# print(hight, hight2)
if hight == hight2:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys

N = int(sys.stdin.readline().strip())

S = []
for _ in range(N):
    s_i = sys.stdin.readline().strip()
    S.append(s_i)

# left bracket - right bracketを高さとした、最小の高さと最終的な高さの座標列
# ex)
# ")": (-1, -1)
# "(": (1, 1)
# "()": (1, 0)
# ")()(": (-1, 0)
# "))))(((((: (-4, 1)

plus_seqs = []
minus_seqs = []
for s_i in S:
    h = 0
    min_h = float("inf") 
    for bracket in s_i:
        if bracket == "(":
            h += 1
        else:
            h -= 1
        min_h = min(min_h, h)
            
    if h >= 0:
        plus_seqs.append((min_h, h))
    else:
        minus_seqs.append((-1 * min_h, -1 * h))

# print(plus_seqs)
# print(minus_seqs)

hight = 0
for (min_h, h) in sorted(plus_seqs, reverse=True):
    if hight + min_h < 0:
        print("No")
        sys.exit()
    hight += h

hight2 = 0
for (min_h, h) in sorted(minus_seqs, reverse=True):
    if hight2 + min_h < 0:
        print("No")
        sys.exit()
    hight2 += h

# print(hight, hight2)
if hight == hight2:
    print("Yes")
else:
    print("No")

Submission status: Wrong Answer

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

lst.sort()
d = {'(': 0, ')': 0}
txt = 'No'

for i in lst:
    # print(f"{i = }")
    for j in i:
        # print(f"{j = }")
        d[j] += 1
        if(d['('] < d[')']):
            break


if(d['('] == d[')']):
    txt = 'Yes'

print(txt)

Submission status: Wrong Answer

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

lst.sort()
d = {'(': 0, ')': 0}
txt = 'No'

for i in lst:
    # print(f"{i = }")
    for j in i:
        # print(f"{j = }")
        d[j] += 1
        if(d['('] < d[')']):
            break


if(d['('] == d[')']):
    txt = 'Yes'

Submission status: Wrong Answer

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

lst.sort()
d = {'(': 0, ')': 0}
tst = 'No'

for i in lst:
    # print(f"{i = }")
    for j in i:
        # print(f"{j = }")
        d[j] += 1
        if(d['('] < d[')']):
            break
else:
    txt = 'Yes'

print(txt)

Submission status: Wrong Answer

Solution code:
n = int(input())
s=['' for _ in range(n)]
for i in range(n):
    s[i]=input()
#x=[[0,0] for _ in range(n)]
hp,hm=0,0
p=[]
m=[]
for i in range(n):
    t=s[i]
    lv=0
    mn=0
    for u in t:
        if u == '(':
            lv+=1
        elif u == ')':
            lv-=1
        mn=min(mn,lv)
    #x[i][0],x[i][1]=lv,mn
    if lv>=0:
        p.append([lv,mn])
        hp+=lv
    else:
        m.append([-lv,mn-lv])
        hm-=lv
if hp!=hm:
    print('No')
    exit()
p.sort(key=lambda x: x[1],reverse=1)
m.sort(key=lambda x: x[1],reverse=0)
h=0

for a,b in p:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
for a,b in m:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
print('Yes')

#print(lv,mn)

Submission status: Wrong Answer

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


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

t = [scan(s) for s in S]
c = 0
for m, a in sorted([(m, a) for m, a in t if a >= 0], reverse=True):
    if c + m < 0:
        print('No')
        exit()
    c += a
for m, a in sorted([(m, -a) for m, a in t if a < 0]):
    if c + m < 0:
        print('No')
        exit()
    c -= a

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

Submission status: Wrong Answer

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


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

t = [scan(s) for s in S]
c = 0
for m, a in sorted([(m, a) for m, a in t if a >= 0], reverse=True):
    if c + m < 0:
        print('No')
        exit()
    c += a
for m, a in sorted([(m, a) for m, a in t if a < 0]):
    if c + m < 0:
        print('No')
        exit()
    c += a

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s=['' for _ in range(n)]
for i in range(n):
    s[i]=input()
x=[[0,0] for _ in range(n)]
h=0
pm,mp=[],[]
pp=[0,0]
mm=[0,0]
for i in range(n):
    t=s[i]
    lv=0
    mn=0
    for u in t:
        if u == '(':
            lv+=1
        elif u == ')':
            lv-=1
        mn=min(mn,lv)
    x[i][0],x[i][1]=lv,mn
    if lv>=0:
        if mn>=0:
            pp[0]+=lv
            pp[1]+=mn
        else:
            pm.append([lv,mn])
    else:
        if mn>=0:
            mp.append([lv,mn])
        else:
            mm[0]+=lv
            mm[1]+=mn
    h+=lv
if h!=0:
    print('No')
    exit()
pm.sort(key=lambda x: x[1],reverse=1)
#mm.sort(key=lambda x: x[1])
mp.sort(key=lambda x: x[1])
#print(pp,pm,mp,mm)
mn,lv=pp

for a,b in pm:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
lv+=mm[0]
mn+=mm[1]
for a,b in mp:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
print('Yes')

#print(lv,mn)

Submission status: Wrong Answer

Solution code:
n = int(input())
s=['' for _ in range(n)]
for i in range(n):
    s[i]=input()
x=[[0,0] for _ in range(n)]
h=0
pm,mp=[],[]
pp=[0,0]
mm=[0,0]
for i in range(n):
    t=s[i]
    lv=0
    mn=0
    for u in t:
        if u == '(':
            lv+=1
        elif u == ')':
            lv-=1
        mn=min(mn,lv)
    x[i][0],x[i][1]=lv,mn
    if lv>=0:
        if mn>=0:
            pp[0]+=lv
            pp[1]+=mn
        else:
            pm.append([lv,mn])
    else:
        if mn>=0:
            mp.append([lv,mn])
        else:
            mm[0]+=lv
            mm[1]+=mn
    h+=lv
if h!=0:
    print('No')
    exit()
pm.sort(key=lambda x: x[1])
#mm.sort(key=lambda x: x[1])
mp.sort(key=lambda x: x[1])
#print(pp,pm,mp,mm)
mn,lv=pp

for a,b in pm:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
lv+=mm[0]
mn+=mm[1]
for a,b in mp:
    lv+=a
    mn+=b
    if mn<0:
        print('No')
        exit()
    mn=lv
print('Yes')

#print(lv,mn)

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())
s=[list(input()) for i in range(n)]
L1=[]
L2=[]
ct1=0;ct2=0
for i in range(n):
  ct3=0
  l=[0]
  for j in range(len(s[i])):
    if s[i][j]=='(':
      ct1+=1
      ct3+=1
      l.append(ct3)
    else:
      ct2+=1
      ct3-=1
      l.append(ct3)
  if l[-1]>=0:
    L1.append((min(l),l[-1]))
  else:
    L2.append((l[-1]-min(l),-l[-1]))
if ct1!=ct2:
  print('No')
  sys.exit()

L1.sort()
L1.reverse()
ct4=0
for i in range(len(L1)):
  if ct4+L1[i][0]<0:
    print('No')
    sys.exit()
  ct4+=L1[i][1]

L2.sort()
L2.reverse()
ct5=0
for i in range(len(L2)):
  if ct5+L2[i][0]<0:
    print('No')
    sys.exit()
  ct5+=L2[i][1]

if ct4!=ct5:
  print('No')
  sys.exit()

print('Yes')

Submission status: Wrong Answer

Solution code:
n = int(input())
s=['' for _ in range(n)]
for i in range(n):
    s[i]=input()
x=[[0,0] for _ in range(n)]
h=0
pp,pm,mp,mm=[],[],[],[]
for i in range(n):
    t=s[i]
    lv=0
    mn=0
    for u in t:
        if u == '(':
            lv+=1
        elif u == ')':
            lv-=1
        mn=min(mn,lv)
    x[i][0],x[i][1]=lv,mn
    if lv>=0:
        if mn>=0:
            pp.append([lv,mn])
        else:
            pm.append([lv,mn])
    else:
        if mn>=0:
            mp.append([lv,mn])
        else:
            mm.append([lv,mn])
    h+=lv
if h!=0:
    print('No')
    exit()
pm.sort(key=lambda x: x[1])
mm.sort(key=lambda x: x[1])
mp.sort(key=lambda x: x[1])
#print(pp,pm,mp,mm)
mn=0
lv=0
list=[pp,pm,mm,mp]
for i in range(4):
    x=list[i]
    for a,b in x:
        lv+=a
        mn+=b
        if mn<0:
            print('No')
            exit()
        mn=lv
print('Yes')

#print(lv,mn)

Submission status: Wrong Answer

Solution code:
def main():
    from sys import stdin
    input = stdin.readline
    n = int(input())
    S = [input() for _ in [0]*n]
    s2 = []
    s3 = []
    for s in S:
        temp = [0, 0]
        m = 0
        now = 0
        for i in s:
            if i == "(":
                now += 1
            else:
                now -= 1
            m = min(m, now)
        temp = [-m, (s.count("(")-s.count(")"))-m]
        if temp[0] < temp[1]:
            s2.append(temp)
        else:
            s3.append(temp)
    s2.sort(key=lambda x: (x[0]))
    s3.sort(key=lambda x: (-x[1]))
    cnt = 0
    for i, j in s2:
        cnt -= i
        if cnt < 0:
            print("No")
            return
        cnt += j
    for i, j in s3:
        cnt -= i
        if cnt < 0:
            print("No")
            return
        cnt += j
    if cnt != 0:
        print("No")
        return
    print("Yes")


main()

Submission status: Wrong Answer

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

import functools
n=n0()
s=s2(n) 
def change(x,l_list,c_list,r_list):
    y=""
    while len(x)!=len(y):
        y=x
        x=x.replace("()","")
    left=x.find("(")
    right=x.rfind(")")
    if left==right==-1:
        pass
    elif right==-1:
        l_list.append(len(x))
    elif left==-1:
        r_list.append(-len(x))
    else:
        c_list.append((-right-1,left))

l_list=[]
c_list=[]
r_list=[]
for line in s:
    change(line,l_list,c_list,r_list)

if len(c_list)>0:
    c_sum=sum(functools.reduce(lambda x,y:x+y,c_list))
else:
    c_sum=0
r_sum=sum(r_list)
l_sum=sum(l_list)

if l_sum+r_sum+c_sum!=0:
    print("No")
else:
    tmp=l_sum
    c_list.sort(key=lambda x:-x[0])

    for line in c_list:
        r1,l1=line
        tmp+=r1
        if tmp<0:
            print("No")
            break
        else:
            tmp+=l1
    else:
        if tmp+r_sum==0:
            print("Yes")
        else:
            print("No")

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())
s=[list(input()) for i in range(n)]
L1=[]
L2=[]
ct1=0;ct2=0
for i in range(n):
  ct3=0
  l=[0]
  for j in range(len(s[i])):
    if s[i][j]=='(':
      ct1+=1
      ct3+=1
      l.append(ct3)
    else:
      ct2+=1
      ct3-=1
      l.append(ct3)
  if l[-1]>=0:
    L1.append((min(l),l[-1]))
  else:
    L2.append((l[-1]-min(l),-l[-1]))
if ct1!=ct2:
  print('No')
  sys.exit()

L1.sort()
L1.reverse()
ct4=0
for i in range(len(L1)):
  if ct4+L1[i][0]<0:
    print('No')
    sys.exit()
  ct4+=L1[i][1]

L2.sort()
L2.reverse()
ct5=0
for i in range(len(L2)):
  if ct5+L2[i][0]<0:
    print('No')
    sys.exit()
  ct5+=L2[i][1]

print('Yes')

Submission status: Wrong Answer

Solution code:
n = int(input())
s=['' for _ in range(n)]
for i in range(n):
    s[i]=input()
x=[[0,0] for _ in range(n)]
h=0
pp,pm,mp,mm=[],[],[],[]
for i in range(n):
    t=s[i]
    lv=0
    mn=0
    for u in t:
        if u == '(':
            lv+=1
        elif u == ')':
            lv-=1
        mn=min(mn,lv)
    x[i][0],x[i][1]=lv,mn
    if lv>=0:
        if mn>=0:
            pp.append([lv,mn])
        else:
            pm.append([lv,mn])
    else:
        if mn>=0:
            mp.append([lv,mn])
        else:
            mm.append([lv,mn])
    h+=lv
if h!=0:
    print('No')
    exit()
"""
x.sort(key = lambda x:x[0],reverse=1)
ind=0
for lv,mn in x:
    if lv<0:
        break
    ind+=1
p=x[:ind]
m=x[ind:]
p.sort(key = lambda x:x[1],reverse=1)
m.sort(key = lambda x:x[1],reverse=1)
ind = 0
for lv,mn in p:
    if mn<0:
        break
    ind+=1
pp=p[:ind]
pm=p[ind:]
ind = 0
for lv,mn in m:
    if mn<0:
        break
    ind+=1
mp=m[:ind]
mm=m[ind:]
#print(x)
"""
#print(pp,pm,mp,mm)
mn=0
lv=0
list=[pp,pm,mm,mp]
for i in range(4):
    x=list[i]
    for a,b in x:
        lv+=a
        mn+=b
        if mn<0:
            print('No')
            exit()
        mn=lv
print('Yes')

#print(lv,mn)

Submission status: Wrong Answer

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


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

q = sorted([scan(s) for s in S], reverse=True)

c = 0
while q:
    nq = []
    for m, a in q:
        if c + m < 0:
            nq.append((m, a))
            continue
        c += a
    if len(nq) == len(q):
        c = -1
        break
    q = nq

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

Submission status: Wrong Answer

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


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

t = sorted([scan(s) for s in S], reverse=True)

c = 0
for m, a in t:
    if a <= 0:
        continue
    if c + m < 0:
        c += m
        break
    c += a

for m, a in t:
    if a > 0:
        continue
    if c + m < 0:
        c += m
        break
    c += a


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

Submission status: Wrong Answer

Solution code:
def get_score(s):
  score = 0
  for char in s:
    if char =="(":
      score+=1
    elif char==")":
      score-=1
  return score

n  = int(input())
s_arr = []
for i in range(n):
  s = input()
  if not s:
    s = ""
  s_arr.append(s)
# print(s_arr)
s_score = [0]*n
for i in range(n):
  s_score[i] = get_score(s_arr[i])
# print(s_score)
ans = "Yes" if sum(s_score)==0 else "No"
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import queue
    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:
        minsum1 = [item for item in minsum if item[1]>=0]
        minsum2 = [(item[0]-item[1], -item[1]) for item in minsum if item[1]<0]
        c = 0
        for m,s in minsum1[::-1]:
            if c+m>=0:
                c += s
            else:
                print("No")
                return
        c = 0
        for m,s in minsum2[::-1]:
            if c+m>=0:
                c+=s
            else:
                print("No")
                return
        print("Yes")
main()

Submission status: Wrong Answer

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


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

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

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

Submission status: Wrong Answer

Solution code:
def main():
    import queue
    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:
        minsum1 = [item for item in minsum if item[1]>=0]
        minsum2 = [item for item in minsum if item[1]<0]
        c = 0
        for m,s in minsum1[::-1]:
            if c+m>=0:
                c += s
            else:
                print("No")
                return
        c = 0
        for m,s in minsum2[::-1]:
            if c+(m-s)>=0:
                c+=(-s)
            else:
                print("No")
                return
        print("Yes")
main()

Submission status: Wrong Answer

Solution code:
def main():
    import queue
    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:
        minsum1 = [item for item in minsum if item[1]>=0]
        minsum2 = [item for item in minsum if item[1]<0]
        c = 0
        for m,s in minsum1[::-1]:
            if c+m>=0:
                c += s
            else:
                print("No")
                return
        minsum2.sort(key=lambda x: x[1])
        for m,s in minsum2[::-1]:
            if c+m>=0:
                c+=s
            else:
                print("No")
                return
        print("Yes")
main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout
cnt=0
def check(a,b):
    global cnt
    for i in range(len(a)):
        cnt-=a[i][0]
        if cnt<0:
            return False
        cnt+=a[i][1]

    for i in range(len(b)):
        cnt-=b[i][0]
        if cnt<0:
            return False
        cnt+=b[i][1]
    if cnt==0:
        return True
    return False

a=[]
b=[]
for i in range(int(input())):
    s=stdin.readline()
    ans=[]
    for j in range(len(s)):
        if s[j]=='(':
            ans.append('(')
        else:
            if len(ans)==0:
                ans.append(')')
                continue
            if ans[-1]=='(':
                ans.pop(-1)
            else:
                ans.append(')')
    L=0
    for j in range(len(ans)):
        if ans[j]==')':
            L+=1
        else:
            break
    R=len(ans)-L
    if L<R:
        a.append((L,R))
    else:
        b.append((L,R))

    a.sort()
    b.sort(key=lambda x:x[1],reverse=True)
    #print(a,b)
if check(a,b):
    print('Yes')
else:
    print('No')