message stringlengths 2 15.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 45 107k | cluster float64 21 21 | __index_level_0__ int64 90 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,612 | 21 | 165,224 |
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
lparen = []
rparen = []
bparen = 0
for i in range(n):
p = input()
right = 0;
left = 0;
for j in range(len(p)):
if p[j] == '(':
right+=1
else:
if right == 0:
left+=1
else:
right-=1
if right == 0 and left == 0:
bparen+=1
elif right == 0:
lparen.append(left)
elif left == 0:
rparen.append(right)
num = int(bparen/2)
lparen.sort()
rparen.sort()
l = 0
r = 0
while(l < len(lparen) and r < len(rparen)):
if lparen[l] == rparen[r]:
num+=1
l+=1
r+=1
elif lparen[l] > rparen[r]:
r+=1
else:
l+=1
print(num)
``` | output | 1 | 82,612 | 21 | 165,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,613 | 21 | 165,226 |
Tags: greedy, implementation
Correct Solution:
```
def check(s):
a = 0
b = 0
for c in s:
if c == "(":
a += 1
else:
a -= 1
if a < 0:
b += 1
a = 0
return a, b
n = int(input())
d = {}
for i in range(0, n):
s = input()
a, b = check(s)
if a == 0 and b == 0:
d[0] = d.get(0, 0) + 1
elif a != 0 and b != 0:
pass
elif a != 0:
d[a] = d.get(a, 0) + 1
elif b != 0:
d[-b] = d.get(-b, 0) + 1
num = d.get(0, 0) // 2
for i in d:
if i < 0 and d.get(i) and d.get(-i):
num += min(d.get(i), d.get(-i))
print(num)
'''
2
()
)(()
'''
``` | output | 1 | 82,613 | 21 | 165,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,614 | 21 | 165,228 |
Tags: greedy, implementation
Correct Solution:
```
'''input
4
(
((
(((
(())
'''
from sys import stdin
def calculate_score(bracket):
score = dict()
for element in bracket:
count = 0
for c in element:
if c == '(':
count += 1
else:
count -= 1
score[element] = count
return score
def is_positive(string):
count = 0
for c in string:
if c == '(':
count += 1
else:
count -= 1
if count < 0:
return False
if count < 0:
return False
return True
def is_negative(string):
count = 0
for i in range(len(string) - 1, -1, -1):
if string[i] == '(':
count += 1
else:
count -= 1
if count > 0:
return False
return True
# main starts
n = int(stdin.readline().strip())
opening = dict()
closing = dict()
bracket = []
for _ in range(n):
bracket.append(stdin.readline().strip())
#bracket = list(set(bracket))
score = calculate_score(bracket)
zero = 0
for element in bracket:
if is_positive(element):
if score[element] == 0:
zero += 1
continue
else:
try:
opening[score[element]] += 1
except:
opening[score[element]] = 1
continue
elif is_negative(element):
try:
closing[score[element]] += 1
except:
closing[score[element]] = 1
continue
count = zero // 2
for key in opening:
if -key in closing:
count += min(opening[key], closing[-key])
print(count)
``` | output | 1 | 82,614 | 21 | 165,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,615 | 21 | 165,230 |
Tags: greedy, implementation
Correct Solution:
```
d={0:[0,0]}
for _ in[0]*int(input()):
m=c=0
for x in input():c+=2*(x<')')-1;m=min(m,c)
d.setdefault(abs(c),[0,0])[m<0]+=m in(0,c)
print(sum(map(min,d.values()))+d[0][0]//2)
``` | output | 1 | 82,615 | 21 | 165,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,616 | 21 | 165,232 |
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = []
for i in range(n):
a.append([(1 if x == '(' else -1) for x in input().strip()])
lsms = []
for p in a:
cs = 0
ms = 0
for e in p:
cs += e
ms = min(ms, cs)
lsms.append([cs, ms])
lsms.sort(key=lambda sms: sms[1], reverse=True)
lsms.sort(key=lambda sms: sms[0], reverse=True)
l = 0
r = n-1
ch = 0
while l < r:
if lsms[l][0] + lsms[r][0] == 0:
if lsms[l][1] < 0:
l += 1
continue
if lsms[r][1] + lsms[l][0] < 0:
r -= 1
continue
ch += 1
l += 1
r -= 1
elif lsms[l][0] + lsms[r][0] < 0:
r -= 1
continue
else:
l += 1
continue
print(ch)
``` | output | 1 | 82,616 | 21 | 165,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,617 | 21 | 165,234 |
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = [input() for i in range(n)]
kk = {}
for i in a:
if i[0] == ')' and i[-1] == '(':
continue
cnt = 0
flag1 = False
flag2 = False
isFirst = False
for j in i:
if j == '(':
cnt += 1
else:
cnt -= 1
if cnt > 0:
flag1 = True
if not flag2:
isFirst = True
if cnt < 0:
flag2 = True
flag = False
if cnt == 0:
if flag2:
continue
else:
flag = True
if cnt > 0:
if flag2:
continue
else:
flag = True
if cnt < 0:
cnt_zakr = 0
for j in i[::-1]:
if j == '(':
cnt_zakr -= 1
if cnt_zakr < 0:
break
else:
cnt_zakr += 1
else:
flag = True
if not flag:
continue
kk[cnt] = kk.get(cnt, 0) + 1
#print(kk)
ans = 0
for i in kk.keys():
if i >= 0:
continue
a = kk[i]
b = kk.get(-i, 0)
ans += min(a, b)
ans += kk.get(0, 0) // 2
print(ans)
``` | output | 1 | 82,617 | 21 | 165,235 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,618 | 21 | 165,236 |
Tags: greedy, implementation
Correct Solution:
```
def mi():
return map(int, input().split())
'''
def gcd (a,b):
if b==0:
return a
return gcd(b,a%b)
7
)())
)
((
((
(
)
)
'''
l = [0]*((10**5)*5+5)
r = [0]*((10**5)*5+5)
try:
n = int(input())
for _ in range(n):
a = input()
la = len(a)
s = 0
f = 0
for i in a:
if i=='(':
if s<0:
f=1
break
s+=1
else:
s-=1
if f==0 and s>=0:
r[s]+=1
s = 0
f = 0
a = a[::-1]
for i in a:
if i==')':
s+=1
else:
if s<=0:
f = 1
break
s-=1
if f==0 and s>0:
l[s]+=1
ans = r[0]//2
for i in range(1,500000+5):
ans += min(l[i],r[i])
print (ans)
except EOFError:
print (0)
``` | output | 1 | 82,618 | 21 | 165,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )". | instruction | 0 | 82,619 | 21 | 165,238 |
Tags: greedy, implementation
Correct Solution:
```
d={}
r=0
for _ in[0]*int(input()):
m=c=0
for x in input():c+=2*(x<')')-1;m=min(m,c)
if c==m==0:r+=1
elif m in(0,c):i=m<0;d.setdefault((c,-m)[i],[0,0])[i]+=1
print(sum(map(min,d.values()))+r//2)
``` | output | 1 | 82,619 | 21 | 165,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
if __name__ == '__main__':
n = int(input())
parens = [0 for x in range(n)]
for i in range(n):
parens[i] = input()
left_dict = {}
right_dict = {}
max_left = 0
max_right = 0
for i in range(n):
left = True
right = True
current = parens[i]
m = len(current)
left_count = 0
for j in range(m):
if current[j] == '(':
left_count += 1
else:
left_count -= 1
if left_count < 0:
left = False
break
if left:
left_dict[left_count] = left_dict.get(left_count, 0) + 1
max_left = max(max_left, left_count)
right_count = 0
for j in range(m):
j = m - 1 - j
if current[j] == ')':
right_count += 1
else:
right_count -= 1
if right_count < 0:
right = False
break
if right:
right_dict[right_count] = right_dict.get(right_count, 0) + 1
max_right = max(max_right, right_count)
sum = left_dict.get(0, 0)//2
MAX_VALUE = min(max_left, max_right) + 1
for i in range(1, MAX_VALUE):
sum += min(left_dict.get(i, 0), right_dict.get(i, 0))
print(sum)
``` | instruction | 0 | 82,620 | 21 | 165,240 |
Yes | output | 1 | 82,620 | 21 | 165,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
v = []
for _ in range(n):
bkt = input()
l, r, mmin = 0, 0, float('inf')
for item in bkt:
if item == '(':
l += 1
elif item == ')':
r += 1
mmin = min(mmin, l - r)
v.append([l-r, mmin])
v = sorted(v, key=lambda x:(x[0], x[1]))
ans = 0
l, r = 0, n-1
while l < r:
ll, llm = v[l]
rr, rrm = v[r]
if rr < 0 or ll > 0:
break
if ll + rr > 0:
r -= 1
elif ll + rr < 0:
l += 1
else:
if rrm < 0:
r -= 1
else:
if rr + llm >= 0:
ans += 1
l += 1
r -= 1
else:
l += 1
print(ans)
``` | instruction | 0 | 82,621 | 21 | 165,242 |
Yes | output | 1 | 82,621 | 21 | 165,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
cor = 0
x, y = dict(), dict()
for _ in range(int(input())):
s = input()
stack = 0
a, b = 0, 0
for c in s:
if c == '(':
stack += 1
elif c == ')':
if stack == 0:
a += 1
else:
stack -= 1
b = stack
if a == 0 and b == 0:
cor += 1
elif a == 0:
if b in y: y[b] += 1
else: y[b] = 1
elif b == 0:
if a in x: x[a] += 1
else: x[a] = 1
cor = cor//2
for k in x:
if k in y:
cor += min(x[k], y[k])
print(cor)
``` | instruction | 0 | 82,622 | 21 | 165,244 |
Yes | output | 1 | 82,622 | 21 | 165,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
n = int(input())
left = {}
right = {}
neutral_count = 0
for _ in range(n):
bracket = input()
s = []
for p in bracket:
if '(' == p:
s.append('(')
if ')' == p:
if len(s) > 0 and s[-1] == '(':
s.pop()
else:
s.append(')')
if len(s) == 0:
neutral_count += 1
elif all(e == '(' for e in s):
l = len(s)
if l in left:
left[l] += 1
else:
left[l] = 1
elif all(e == ')' for e in s):
r = len(s)
if r in right:
right[r] += 1
else:
right[r] = 1
ans = 0
ans += neutral_count//2
for l in left:
r = 0
if l in right:
r = right[l]
ans += min(left[l], r)
print(ans)
``` | instruction | 0 | 82,623 | 21 | 165,246 |
Yes | output | 1 | 82,623 | 21 | 165,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
import collections
n = int(input())
def count(s):
res = 0
wasNeg = False
for c in s:
if c == '(':
res += 1
else:
res -= 1
if res < 0:
wasNeg = True
res = 0
if wasNeg and res > 0:
return None
return res
ct = collections.Counter()
res = 0
for i in range(n):
s = input()
c = count(s)
if c is None:
continue
if ct[-c] > 0:
ct[-c] -= 1
res += 1
else:
ct[c] += 1
print(res)
``` | instruction | 0 | 82,624 | 21 | 165,248 |
No | output | 1 | 82,624 | 21 | 165,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
n=int(input())
tot=[]
for i in range(n):
a=input()
summa=0
g=1
for item in a:
if summa<0:
g=0
if item=='(':
summa+=1
else:
summa-=1
if summa>=0:
if g==1:
tot.append(summa)
elif summa<0:
f=summa
l=0
for m in a:
if f>1:
l=1
if m==')':
f+=1
else:
f-=1
if l==0:
if a[-1]!='(':
tot.append(summa)
dic={}
total=0
for item in tot:
if item==0:
dic[0]=0
else:
dic[abs(item)]=[0,0]
for item in tot:
if item>0:
dic[item][1]+=1
elif item==0:
dic[item]+=1
else:
dic[abs(item)][0]+=1
for item in dic:
if item!=0:
total+=min(dic[item])
else:
total+=(dic[item]//2)
print(total)
``` | instruction | 0 | 82,625 | 21 | 165,250 |
No | output | 1 | 82,625 | 21 | 165,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
n = int(input())
from collections import defaultdict
braces = []
braceHash = defaultdict(int)
count = 0
def checkComplete(braces):
count = 0
for brace in braces:
if brace == "(":
count += 1
else:
count -= 1
return count == 0
couple = True
for i in range(n):
x = input()
if checkComplete(x) is False:
braces.append(x)
braceHash[x] += 1
else:
if couple is True:
couple = False
else:
couple = True
count += 1
for i in range(len(braces)):
temp = []
for j in braces[i]:
if j == "(":
temp.append(")")
else:
temp.append("(")
temp = ''.join(temp)
if temp in braceHash and braceHash[temp] > 0:
count += 1
braceHash[temp] -= 1
print(count)
``` | instruction | 0 | 82,626 | 21 | 165,252 |
No | output | 1 | 82,626 | 21 | 165,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of bracket sequences.
Each of the following n lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5 β
10^5.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
Submitted Solution:
```
n = int(input())
left = [0 for i in range(100010)]
right = [0 for i in range(100010)]
none = 0
ans = 0
for i in range(n):
str = input()
k = ""
h = 0
for i in str:
if k == "":
if i == ')':
h+=1
else:
k = k + i
else:
k = k[:len(k)-1]
if h>0:
if k == "":
if left[h] > 0:
left[h] -= 1
ans += 1
else:
right[h] += 1
elif k == "":
if none > 0:
none = 0
ans += 1
else:
none = 1
elif k[0] == '(':
if right[len(k)] > 0:
right[len(k)] -= 1
ans += 1
else:
left[len(k)] += 1
elif k[0] == ')':
if left[len(k)] > 0:
left[len(k)] -= 1
ans += 1
else:
right[len(k)] += 1
#if k in dic:
#dic[k] = dic[k] + 1
#else:
#dic[k] = 1
print(ans)
``` | instruction | 0 | 82,627 | 21 | 165,254 |
No | output | 1 | 82,627 | 21 | 165,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,646 | 21 | 169,292 |
Tags: data structures, dsu, strings
Correct Solution:
```
import sys
sys.stderr = sys.stdout
from collections import deque
def brackets(n, m, p, B, S):
P = [i-1 for i in range(n+2)]
P[0] = None
Q = [i+1 for i in range(n+2)]
Q[n+1] = None
J = [None] * (n + 2)
D = deque()
for i, b in enumerate(B, 1):
if b == '(':
D.append(i)
elif b == ')':
j = D.pop()
J[i] = j
J[j] = i
i = p
for c in S:
if c == 'L':
i = P[i]
elif c == 'R':
i = Q[i]
else:
j = J[i]
if j < i:
i, j = j, i
Q[P[i]] = Q[j]
P[Q[j]] = P[i]
i = Q[j] if Q[j] <= n else P[i]
L = []
i = Q[0]
while i <= n:
L.append(B[i-1])
i = Q[i]
return L
def main():
n, m, p = readinti()
B = input()
S = input()
print(''.join(brackets(n, m, p, B, S)))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | output | 1 | 84,646 | 21 | 169,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,647 | 21 | 169,294 |
Tags: data structures, dsu, strings
Correct Solution:
```
def preproc(str, leng):
li = []
res = [-1]*leng
for i in range(leng):
if str[i] == '(':
li.append(i)
else:
start, end = li.pop(), i
res[start] = end
res[end] = start
return res
def delete(flags, cursor, pairs):
pos = pairs[cursor]
direction = 1 if pos > cursor else -1
while(pos+direction > 0 and pos+direction < len(flags) and flags[pos+direction] != -1):
pos = flags[pos+direction]
return pos
leng, op_num, cursor = map(int, input().strip().split())
cursor = cursor-1
str = input().strip()
ops = input().strip()
pairs = preproc(str, leng)
flags = [-1]*leng
#print(leng, op_num, cursor, str, ops, pairs)
for i in ops:
#print(i, cursor, flags)
if i == 'R' or i == 'L':
cursor = {
'R':(lambda cursor=cursor, flags=flags: cursor+1 if flags[cursor+1] == -1 else flags[cursor+1]+1),
'L':(lambda cursor=cursor, flags=flags: cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]-1)
}[i]()
else:
delete_to = delete(flags, cursor, pairs)
delete_from = delete(flags, pairs[cursor], pairs)
flags[delete_from] = delete_to
flags[delete_to] = delete_from
cursor = max(delete_to, delete_from)
if cursor+1 < leng and flags[cursor+1] == -1:
cursor = cursor+1
elif cursor+1 < leng and flags[cursor+1] != -1 and flags[cursor+1]+1 < leng:
cursor = flags[cursor+1]+1
elif min(delete_from, delete_to) -1 > 0 and flags[min(delete_from, delete_to)-1] == -1:
cursor = min(delete_from, delete_to)-1
else:
cursor = flags[min(delete_from, delete_to)-1]-1
idx = 0
res = ''
while idx < leng:
if flags[idx] != -1:
idx = flags[idx]+1
continue
res += str[idx]
idx = idx+1
print(res)
``` | output | 1 | 84,647 | 21 | 169,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,648 | 21 | 169,296 |
Tags: data structures, dsu, strings
Correct Solution:
```
class Node:
def __init__(self, index):
self.left = index - 1
self.right = index + 1
self.pair = -1
if __name__ == "__main__":
n, m, p = map(int, input().split())
brackets = input()
operations = input()
nodes = [Node(i) for i in range(n + 1)]
stack = []
for i in range(n):
if brackets[i] == "(":
stack.append(i + 1)
else:
pair_id = stack.pop()
nodes[pair_id].pair = i + 1
nodes[i + 1].pair = pair_id
for i in range(m):
if operations[i] == "L":
p = nodes[p].left
elif operations[i] == "R":
p = nodes[p].right
else:
pair_id = nodes[p].pair
left = 0
right = 0
if p < pair_id:
left = p
right = pair_id
else:
left = pair_id
right = p
left_node = nodes[left].left
right_node = nodes[right].right
nodes[left_node].right = right_node
if right_node != n + 1:
nodes[right_node].left = left_node
p = right_node
else:
p = left_node
p = nodes[0].right
result = []
while p != n + 1:
result.append(brackets[p - 1])
p = nodes[p].right
print("".join(result))
``` | output | 1 | 84,648 | 21 | 169,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,649 | 21 | 169,298 |
Tags: data structures, dsu, strings
Correct Solution:
```
n, m, p = [int(x) for x in input().split()]
A = input().rstrip()
B = input().rstrip()
pair = [0] * n
stack = []
for (i, c) in enumerate(A):
if c == '(':
stack.append(i)
else:
j = stack.pop()
pair[i] = j
pair[j] = i
start = 0
pointer = p - 1
left = list(range(-1, n-1))
right = list(range(1, n+1))
left[0] = None
right[-1] = None
for c in B:
if c == 'R':
pointer = right[pointer]
elif c == 'L':
pointer = left[pointer]
else:
if pair[pointer] < pointer:
if right[pointer] is not None:
left[right[pointer]] = left[pair[pointer]]
if left[pair[pointer]] is not None:
right[left[pair[pointer]]] = right[pointer]
else:
start = right[pointer]
if right[pointer] is None:
pointer = left[pair[pointer]]
else:
pointer = right[pointer]
else:
if right[pair[pointer]] is not None:
left[right[pair[pointer]]] = left[pointer]
if left[pointer] is not None:
right[left[pointer]] = right[pair[pointer]]
else:
start = right[pair[pointer]]
if right[pair[pointer]] is None:
pointer = left[pointer]
else:
pointer = right[pair[pointer]]
i = start
while right[i] is not None:
print(A[i], end = '')
i = right[i]
print(A[i])
``` | output | 1 | 84,649 | 21 | 169,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,650 | 21 | 169,300 |
Tags: data structures, dsu, strings
Correct Solution:
```
def main():
n, m, p = map(int, input().split())
xlat, l, s, ll, lr = [0] * n, [], input(), list(range(-1, n)), list(range(1, n + 2))
p -= 1
for i, c in enumerate(s):
if c == '(':
l.append(i)
else:
j = l.pop()
xlat[i] = j
xlat[j] = i
for c in input():
if c == 'D':
if s[p] == '(':
p = xlat[p]
q = ll[xlat[p]]
p = lr[p]
ll[p], lr[q] = q, p
if p == n:
p = ll[p]
else:
p = (lr if c == 'R' else ll)[p]
q = p
while p != -1:
l.append(s[p])
p = ll[p]
l.reverse()
del l[-1]
while q != n:
l.append(s[q])
q = lr[q]
print(''.join(l))
if __name__ == '__main__':
main()
``` | output | 1 | 84,650 | 21 | 169,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,651 | 21 | 169,302 |
Tags: data structures, dsu, strings
Correct Solution:
```
class Node:
def __init__(self, index):
self.left = index - 1
self.right = index + 1
self.pair = -1
if __name__ == "__main__":
n, m, p = map(int, input().split())
brackets = input()
operations = input()
nodes = [Node(i) for i in range(n + 1)]
stack = []
for i in range(n):
if brackets[i] == "(":
stack.append(i + 1)
else:
pair_id = stack.pop()
nodes[pair_id].pair = i + 1
nodes[i + 1].pair = pair_id
for i in range(m):
if operations[i] == "L":
p = nodes[p].left
elif operations[i] == "R":
p = nodes[p].right
else:
pair_id = nodes[p].pair
left = min(p, pair_id)
right = max(p, pair_id)
left_node = nodes[left].left
right_node = nodes[right].right
nodes[left_node].right = right_node
if right_node != n + 1:
nodes[right_node].left = left_node
p = right_node
else:
p = left_node
p = nodes[0].right
result = []
while p != n + 1:
result.append(brackets[p - 1])
p = nodes[p].right
print("".join(result))
``` | output | 1 | 84,651 | 21 | 169,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,652 | 21 | 169,304 |
Tags: data structures, dsu, strings
Correct Solution:
```
jump_r = {}
jump_l = {}
def bracket_to_value(bracket):
if bracket == '(':
return 1
if bracket == ')':
return -1
def move_r(c):
if c+1 in jump_r:
return jump_r[c+1]+1
else:
return c+1
def move_l(c):
if c-1 in jump_l:
return jump_l[c-1]-1
else:
return c-1
def remove_bracket(s, c, length):
val = bracket_to_value(s[c])
initial_c = c
dir = bracket_to_value(s[c])
#print(f'started at c ={c} and dir = {dir}')
if dir == 1:
c = move_r(c)
if dir == -1:
c = move_l(c)
val += bracket_to_value(s[c])
while val != 0:
#print(f'wwwc = {c} val = {val} s[c] = {s[c]}')
if dir == 1:
c = move_r(c)
if dir == -1:
c = move_l(c)
val += bracket_to_value(s[c])
final_c = c
left_end = min(initial_c, final_c)
right_end = max(initial_c, final_c)
real_r_end = right_end
real_l_end = left_end
#print(f'left_end = {left_end} roght_end = {right_end}')
jump_r[left_end] = right_end
jump_l[right_end] = left_end
if right_end + 1 in jump_r:
real_r_end = jump_r[right_end+1]
if left_end - 1 in jump_l:
real_l_end = jump_l[left_end-1]
jump_l[real_r_end] = real_l_end
jump_r[real_l_end] = real_r_end
if real_r_end < length - 1:
new_c = real_r_end+1
else:
new_c = real_l_end - 1
return new_c
def smart_print(s):
i = 0
while i < n:
if i not in jump_r:
print(s[i], end='')
i += 1
else:
i = jump_r[i]+1
def perform_order(order, s, c, length):
if order == 'R':
return move_r(c)
if order == 'L':
return move_l(c)
if order == 'D':
return remove_bracket(s, c, length)
n, m, p = [int(x) for x in input().split()]
p = p-1
se = input()
orders = input()
for ord in orders:
p = perform_order(ord, se, p, n)
#print(f'jump_r = {jump_r} jump_l = {jump_l} p = {p} s = {se}')
smart_print(se)
# print(f'se = {se} p = {p}')
#print(jump_r)
# 3->6
#
# 0 1 2 3 4 5 6 7 8 9 10 11
# ( ( ( ) ( ) ) ( ( ) ) )
``` | output | 1 | 84,652 | 21 | 169,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to (). | instruction | 0 | 84,653 | 21 | 169,306 |
Tags: data structures, dsu, strings
Correct Solution:
```
n, m, p = map(int, input().split()); x, v, s, l, r = [0]*n, [], input(), list(range(-1, n)), list(range(1, n+2))
p -= 1
for i, c in enumerate(s):
if c == '(': v.append(i)
else:
j = v.pop()
x[i] = j
x[j] = i
for c in input():
if c == 'D':
if s[p] == '(':
p = x[p]
q = l[x[p]]
p = r[p]
l[p], r[q] = q, p
if p == n:
p = l[p]
else:
p = (r if c == 'R' else l)[p]
q = p
while p != -1:
v.append(s[p])
p = l[p]
v.reverse()
del v[-1]
while q != n:
v.append(s[q])
q = r[q]
print(''.join(v))
``` | output | 1 | 84,653 | 21 | 169,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 1
cc = 0
for i in range(n):
if bracket[i] == "(":
blist[i] = c
cm = c
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
cc += 1
if cc == c: co = c
cm = co + c - cc - 1
continue
print(blist)
exit()
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
``` | instruction | 0 | 84,654 | 21 | 169,308 |
No | output | 1 | 84,654 | 21 | 169,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
def preproc(str, leng):
li = []
res = [-1]*leng
for i in range(leng):
if str[i] == '(':
li.append(i)
else:
start, end = li.pop(), i
res[start] = end
res[end] = start
return res
def delete(flags, cursor, pairs):
pos = pairs[cursor]
direction = 1 if pos > cursor else -1
while(pos+direction > 0 and pos+direction < len(flags) and flags[pos+direction] != -1):
pos = flags[pos+direction]
return pos
leng, op_num, cursor = map(int, input().strip().split())
cursor = cursor-1
str = input().strip()
ops = input().strip()
pairs = preproc(str, leng)
flags = [-1]*leng
#print(leng, op_num, cursor, str, ops, pairs)
for i in ops:
#print(i, cursor, flags)
if i == 'R' or i == 'L':
cursor = {
'R':(lambda cursor=cursor, flags=flags: cursor+1 if flags[cursor+1] == -1 else flags[cursor+1]+1),
'L':(lambda cursor=cursor, flags=flags: cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]-1)
}[i]()
else:
delete_to = delete(flags, cursor, pairs)
flags[cursor] = delete_to
flags[delete_to] = cursor
if max(cursor, delete_to)+1 < leng:
cursor = max(cursor, delete_to)+1
else:
cursor = cursor-1 if flags[cursor-1] == -1 else flags[cursor-1]
idx = 0
res = ''
while idx < leng:
if flags[idx] != -1:
idx = flags[idx]+1
continue
res += str[idx]
idx = idx+1
print(res)
``` | instruction | 0 | 84,655 | 21 | 169,310 |
No | output | 1 | 84,655 | 21 | 169,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 1
for i in range(n):
if bracket[i] == "(":
blist[i] = c
cm = c
co += 1
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
co -= 1
cm = c - co
continue
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
``` | instruction | 0 | 84,656 | 21 | 169,312 |
No | output | 1 | 84,656 | 21 | 169,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
* 1st bracket is paired with 8th,
* 2d bracket is paired with 3d,
* 3d bracket is paired with 2d,
* 4th bracket is paired with 7th,
* 5th bracket is paired with 6th,
* 6th bracket is paired with 5th,
* 7th bracket is paired with 4th,
* 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
* Β«LΒ» β move the cursor one position to the left,
* Β«RΒ» β move the cursor one position to the right,
* Β«DΒ» β delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
<image>
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
Input
The first line contains three positive integers n, m and p (2 β€ n β€ 500 000, 1 β€ m β€ 500 000, 1 β€ p β€ n) β the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.
It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.
Then follow a string of m characters "L", "R" and "D" β a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Output
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
Examples
Input
8 4 5
(())()()
RDLD
Output
()
Input
12 5 3
((()())(()))
RRDLD
Output
(()(()))
Input
8 8 8
(())()()
LLLLLLDD
Output
()()
Note
In the first sample the cursor is initially at position 5. Consider actions of the editor:
1. command "R" β the cursor moves to the position 6 on the right;
2. command "D" β the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;
3. command "L" β the cursor moves to the position 4 on the left;
4. command "D" β the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1.
Thus, the answer is equal to ().
Submitted Solution:
```
n, m, p = input().split(' ')
n = int(n)
m = int(m)
p = int(p) - 1
bracket = list(input())
operation = list(input())
blist = list(bracket)
c = 1
co = 0
cm = 0
for i in range(n):
if bracket[i] == "(":
blist[i] = c
co += 1
if co == 1:
cm = c
else:
cm = c
c += 1
continue
elif bracket[i] == ")":
blist[i] = -cm
co -= 1
cm = co
continue
for i in range(m):
if operation[i] == "R":
p += 1
continue
elif operation[i] == "L":
p -= 1
continue
elif operation[i] == "D":
if blist[p] > 0:
temp = blist.index(-blist[p])
del(blist[p:temp+1])
#p = temp
else:
temp = blist.index(-blist[p])
del(blist[p:temp:-1])
del(blist[temp])
p = temp
if p > len(blist) -1 :
p = len(blist) -1
res = ""
for i in range(len(blist)):
if blist[i] > 0:
res = res + "("
else:
res = res + ")"
print(res)
``` | instruction | 0 | 84,657 | 21 | 169,314 |
No | output | 1 | 84,657 | 21 | 169,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,704 | 21 | 173,408 |
Tags: implementation
Correct Solution:
```
n = int(input())
seq = list(input())
def get_comps(seq):
depth = 0
components = 0
lookingfor = 0
for i in range(n):
if seq[i] == "(":
depth += 1
else:
depth -= 1
if depth < lookingfor:
lookingfor = depth
components = 1
elif depth == lookingfor:
components += 1
return components
def other(x):
if x == "(":
return ")"
return "("
if n%2 == 1 or seq.count("(") != seq.count(")"):
print(0)
print(1,1)
else:
best1 = 1
best2 = 1
bestVal = get_comps(seq)
for i in range(n):
for j in range(i+1,n):
if seq[i] != seq[j]:
seq[i] = other(seq[i])
seq[j] = other(seq[j])
val = get_comps(seq)
if val > bestVal:
best1 = i
best2 = j
bestVal = val
seq[i] = other(seq[i])
seq[j] = other(seq[j])
print(bestVal)
print(best1+1,best2+1)
``` | output | 1 | 86,704 | 21 | 173,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,705 | 21 | 173,410 |
Tags: implementation
Correct Solution:
```
n = int(input())
S = list(input())
def count_all(s):
cnt=0
l_cnt=1
for c in s[1:]:
if c==')':
l_cnt-=1
else:
l_cnt+=1
if l_cnt==0:
cnt+=1
return cnt
if S==list('()'*(n//2)) or S==list(')'+'()'*(n//2-1)+'('):
print(n // 2)
print(1, 1)
else:
res=0
l,r =1,1
lc=rc=0
for c in S:
if c=="(":
lc+=1
else:
rc+=1
if lc==rc:
for i in range(n):
for j in range(i,n):
ss=S[:]
if ss[i]==ss[j]:
continue
ss[i],ss[j]=ss[j],ss[i]
t=0
t_min=n
m=0
for k in range(n):
if ss[k]==")":
t-=1
else:
t+=1
if t<t_min:
t_min,m=t,k
sss=ss[m+1:]+ss[:m+1]
temp = count_all(sss)
if temp>=res:
# print(sss)
res=temp
l,r=i+1,j+1
print(res)
print(l,r)
``` | output | 1 | 86,705 | 21 | 173,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,706 | 21 | 173,412 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = [1 if c == '(' else -1 for c in input()]
if s.count(1) != s.count(-1):
print(0)
print(1, 1)
exit()
ans = 0
pair = 1, 1
for i in range(n-1):
for j in range(i, n):
s[i], s[j] = s[j], s[i]
min_p, cnt = 10**9, 0
nest = 0
for k in range(n):
nest += s[k]
if min_p > nest:
min_p = nest
cnt = 1
elif min_p == nest:
cnt += 1
if ans < cnt:
ans = cnt
pair = i+1, j+1
s[i], s[j] = s[j], s[i]
print(ans)
print(*pair)
``` | output | 1 | 86,706 | 21 | 173,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,707 | 21 | 173,414 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = list(input())
best = 0
L = 1
R = 1
def check():
calc = 0
min = 0
cntmin = 0
for ch in s:
if ch == '(':
calc += 1
else:
calc -= 1
if min > calc:
min = calc
cntmin = 1
elif min == calc:
cntmin += 1
return cntmin if calc == 0 else 0
if len(s) % 2:
print(best)
print(L, R)
quit()
best = check()
for i, ch in enumerate(s, 0):
for j in range(i + 1, n, 1):
s[i], s[j] = s[j], s[i]
new = check()
s[j], s[i] = s[i], s[j]
if (new > best):
best = new; L = 1+i; R = 1+j
print(best)
print(L, R)
``` | output | 1 | 86,707 | 21 | 173,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,708 | 21 | 173,416 |
Tags: implementation
Correct Solution:
```
n = int(input())
ddd = input()
d = [0]
for dd in ddd:
if dd == '(':
d.append(d[-1] + 1)
else:
d.append(d[-1] - 1)
if d[-1] != 0:
print("0\n1 1")
exit(0)
d.pop()
mn = min(d)
ind = d.index(mn)
d = d[ind:] + d[:ind]
d = [i - mn for i in d]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
cnt0 = 0
for i in range(n):
dd = d[i]
if dd == 0:
cnt0 += 1
if dd == 2:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 2:
cr = 0
# print('=========')
# print(d)
# print(cnt0)
# print(fi, li)
# print(mx)
# print("=========")
# if fi == -1:
# print(cnt0)
# print(1, 1)
# else:
# print(cnt0 + mx)
# print(fi, li + 2)
if fi == -1:
ans1 = [cnt0, 0, 0]
else:
ans1 = [cnt0 + mx, fi-1, li]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
for i in range(n):
dd = d[i]
if dd == 1:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 1:
cr = 0
ans2 = [mx, fi-1, li]
if ans1[0] > ans2[0]:
print(ans1[0])
print(((ans1[1] + ind)%n) + 1, ((ans1[2] + ind)%n) + 1)
else:
print(ans2[0])
print(((ans2[1] + ind)%n) + 1, ((ans2[2] + ind)%n) + 1)
``` | output | 1 | 86,708 | 21 | 173,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,709 | 21 | 173,418 |
Tags: implementation
Correct Solution:
```
n = int(input().strip())
s= input().strip()
ss= 0
mina = 0
ti = 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
ti = k+1
ss = 0
s=s[ti:]+s[:ti]
#print(s)
ss= 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
print(0)
print(1,1)
break
else:
if(ss == 0):
pre=[0 for k in range(len(s))]
ss=0
for k in range(len(s)):
if (s[k] == "("):
ss += 1
else:
ss -= 1
pre[k] = ss
tt = 0
a =(1,1)
for k in range(0,len(s)):
if(pre[k] == 0):
tt+=1
maxi= tt
#print(pre)
g =0
gg =0
while(gg<len(s)):
if(pre[gg] == 0):
#print(gg,g,"g")
if(gg != g+1):
yy = g+1
y = g+1
q = 0
while(yy<gg):
if(pre[yy] == 1):
# print(yy,y,"y")
if(yy !=y+1):
rr = y+1
r = y+1
h = 0
while(rr<yy):
if(pre[rr] == 2):
h+=1
rr+=1
if(tt+h+1>maxi):
maxi = tt + h + 1
a=(y,yy)
else:
if(tt+1>maxi):
maxi =tt+1
a=(y,yy)
#print(a, a)
q+=1
y = yy+1
yy = y
else:
yy+=1
if (q + 1 > maxi):
maxi = q+1
a = (g, gg)
g= gg+1
gg= g
else:
gg+=1
print(maxi)
# print(a)
print((a[0]+ti)%len(s)+1,(a[1]+ti)%len(s)+1)
else:
print(0)
print(1,1)
``` | output | 1 | 86,709 | 21 | 173,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,710 | 21 | 173,420 |
Tags: implementation
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=0
while (left <= right):
mid = (right + left)//2
if (arr[mid][0] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n = int(input())
s = list(input())
L = 1
R = 1
def check():
calc = 0
min = 0
cntmin = 0
for ch in s:
if ch == '(': calc += 1
else: calc -= 1
if min > calc:
min = calc
cntmin = 1
elif min == calc:
cntmin += 1
return cntmin if calc == 0 else 0
best = check()
for i in range(n):
for j in range(i + 1, n, 1):
s[i], s[j] = s[j], s[i]
new = check()
s[j], s[i] = s[i], s[j]
if (new > best):
best = new; L = 1+i; R = 1+j
print(best)
print(L, R)
``` | output | 1 | 86,710 | 21 | 173,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences. | instruction | 0 | 86,711 | 21 | 173,422 |
Tags: implementation
Correct Solution:
```
# import cProfile
def prefix(s):
count = 0
cur = 0
m = 0
for c in s:
if c == '(':
cur += 1
else:
cur -= 1
if cur < m:
m = cur
count = 0
if cur == m:
count += 1
return count
from collections import Counter
n = int(input())
s = list(input())
C = Counter(s)
if C['('] == C[')']:
a, b, c = -1, -1, -1
for l in range(n):
for r in range(l, n):
s[l], s[r] = s[r], s[l]
abc = prefix(s)
if abc > a:
a = abc
b = l
c = r
s[l], s[r] = s[r], s[l]
print (a)
print (b + 1, c + 1)
else:
print (0)
print (1, 1)
``` | output | 1 | 86,711 | 21 | 173,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
#!/usr/bin/env python3
import sys
#lines = stdin.readlines()
def rint():
return map(int, sys.stdin.readline().split())
def input():
return sys.stdin.readline().rstrip('\n')
def oint():
return int(input())
n = oint()
stemp = input()
s = []
for i in range(n):
if stemp[i] == '(':
s.append(1)
else:
s.append(-1)
maxcnt = 0
candi = [0, 0]
for l in range(n):
for r in range(l, n):
cnt = 0
s[l], s[r] = s[r], s[l]
ssum = [0]*n
ssum[0] = s[0]
for i in range(1, n):
ssum[i] = ssum[i-1] + s[i]
minssum = min(ssum)
if ssum[n-1] != 0:
continue
for i in range(0, n):
if ssum[i] == minssum:
cnt += 1
if maxcnt < cnt:
candi = [r, l]
maxcnt = cnt
s[l], s[r] = s[r], s[l]
print(maxcnt)
print(candi[0]+1, candi[1]+1)
``` | instruction | 0 | 86,712 | 21 | 173,424 |
Yes | output | 1 | 86,712 | 21 | 173,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
s = list(input())
if n % 2 == 1 or s.count('(') != s.count(')'):
print('0\n1 1')
exit()
def solve():
cnt_open, res, need = 0, 0, 0
for i in s:
if i == '(':
cnt_open += 1
else:
cnt_open -= 1
if cnt_open < need:
need = cnt_open
res = 1
elif cnt_open == need:
res += 1
return res
res, res_i, res_j = solve(), 0, 0
for i in range(n):
for j in range(i+1, n):
if s[i] != s[j]:
s[i], s[j] = s[j], s[i]
curr = solve()
s[i], s[j] = s[j], s[i]
if curr > res:
res = curr
res_i = i
res_j = j
print(res)
print(res_i+1, res_j+1)
``` | instruction | 0 | 86,713 | 21 | 173,426 |
Yes | output | 1 | 86,713 | 21 | 173,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
def beauty(tt):
depth = 0
min_depth = 0
dd = []
for i, t in enumerate(tt):
if t == '(':
depth += 1
else:
depth -= 1
dd.append(depth)
if depth < min_depth:
min_depth = depth
if depth != 0:
return(0)
result = 0
for d in dd:
if d == min_depth:
result+=1
return(result)
def main():
n = int(input())
if n%2 == 1:
print(0)
print(1,1)
return
tt = input()
best = beauty(tt)
l = 1
r = 1
for i in range(n-1):
for j in range(i+1, n):
if tt[i] != tt[j]:
ttt = list(tt)
ttt[i] = tt[j]
ttt[j] = tt[i]
b = beauty(ttt)
if b > best:
best = b
l = i+1
r = j+1
print(best)
print(l, r)
if __name__ == "__main__":
main()
``` | instruction | 0 | 86,714 | 21 | 173,428 |
Yes | output | 1 | 86,714 | 21 | 173,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
s = list(input())
cnt_r = 0
cnt_l = 0
for i in range(n):
if s[i] == ")":
cnt_r += 1
else:
cnt_l += 1
if cnt_l != cnt_r:
print(0)
print(1, 1)
exit()
pos_r = []
pos_l = []
for i in range(n):
if s[i] == ")":
pos_r.append(i)
else:
pos_l.append(i)
# no change
ans = 0
for i in [0]:
for j in [0]:
tmp_ans = 0
tmp = s[0:]
tmp[i], tmp[j] = tmp[j], tmp[i]
cnt = 0
offset = 0
min_cnt = 0
for num, k in enumerate(tmp):
if k == ")":
cnt -= 1
else:
cnt += 1
if cnt < min_cnt:
min_cnt = cnt
offset = num+1
cnt = 0
for num, k in enumerate(tmp[offset:]+tmp[0:offset]):
if k == ")":
cnt += 1
else:
cnt -= 1
if cnt == 0:
tmp_ans += 1
if ans < tmp_ans:
ans = tmp_ans
ind1 = i
ind2 = j
for i in pos_r:
for j in pos_l:
tmp_ans = 0
tmp = s[0:]
tmp[i], tmp[j] = tmp[j], tmp[i]
cnt = 0
offset = 0
min_cnt = 0
for num, k in enumerate(tmp):
if k == ")":
cnt -= 1
else:
cnt += 1
if cnt < min_cnt:
min_cnt = cnt
offset = num+1
#print("".join(tmp), offset)
#print("".join(tmp[offset:]+tmp[0:offset]))
cnt = 0
for num, k in enumerate(tmp[offset:]+tmp[0:offset]):
if k == ")":
cnt += 1
else:
cnt -= 1
if cnt == 0:
tmp_ans += 1
if ans < tmp_ans:
ans = tmp_ans
ind1 = i
ind2 = j
print(ans)
print(ind1+1, ind2+1)
``` | instruction | 0 | 86,715 | 21 | 173,430 |
Yes | output | 1 | 86,715 | 21 | 173,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
s = input()
r = 0
l = n-1
root = []
buf = []
to_the_right = True
for count in range(n):
if to_the_right:
i = r
r += 1
else:
i = l
l -= 1
b = s[i]
if b == '(':
if len(buf) == 0 or buf[-1][0] != -1:
buf.append([-1,-1,[]])
buf[-1][0] = i
else:
if len(buf) == 0 or buf[-1][1] != -1:
buf.append([-1,-1,root])
root = []
to_the_right = False
buf[-1][1] = i
if buf[-1][0] != -1 and buf[-1][1] != -1:
tmp = buf.pop()
if len(buf):
buf[-1][2].append(tmp)
else:
root.append(tmp)
to_the_right = True
sol = [[0,1,1]]
if len(buf) == 0:
sol.append([len(root), 1, 1])
for child in root:
sol.append([len(child[2])+1, child[0]+1, child[1]+1])
for gr_child in child[2]:
if len(gr_child[2]):
sol.append([len(root)+len(gr_child[2])+1, gr_child[0]+1, gr_child[1]+1])
print('%d\n%d %d'%tuple(max(sol)))
``` | instruction | 0 | 86,716 | 21 | 173,432 |
No | output | 1 | 86,716 | 21 | 173,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
seq = list(input())
def rectify(seq):
depth = 0
best = bestVal = -1
for i in range(n):
if seq[i] == "(":
depth += 1
else:
depth -= 1
if best == -1 or depth < bestVal:
best = i
bestVal = depth
return seq[best+1:]+seq[:best+1]
if n%2 == 1 or seq.count("(") != seq.count(")"):
print(0)
print(1,1)
else:
best = -1
bestVal = -1
for i in range(n):
for j in range(n):
if seq[i] != seq[j]:
swapseq = list(seq)
swapseq[i] = seq[j]
swapseq[j] = seq[i]
swapseq = rectify(swapseq)
depth = components = 0
for x in range(n):
if swapseq[x] == "(":
depth += 1
else:
depth -= 1
if depth == 0:
components += 1
if bestVal == -1 or components > bestVal:
best = (i,j)
bestVal = components
print(bestVal)
print(best[0],best[1])
``` | instruction | 0 | 86,717 | 21 | 173,434 |
No | output | 1 | 86,717 | 21 | 173,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
# cook your dish here
def check(expression, l, r, k):
if l+k < len(expression):
l = l+k
else:
l = len(expression)-l-1
if r+k < len(expression):
r += k
else:
r = len(expression)-r-1
expression[l], expression[r] = expression[r], expression[l]
open_tup = tuple('({[')
close_tup = tuple(')}]')
map = dict(zip(open_tup, close_tup))
queue = []
for i in expression:
if i in open_tup:
queue.append(map[i])
elif i in close_tup:
if not queue or i != queue.pop():
return False
return True
n = int(input())
array = list(input())
# duplicate = array[:]
cnt = 0
ans = 0
l, r = 1, 1
d = dict()
for i in range(n):
d[i] = array[n-i:]+array[:n-i]
for i in range(n):
for j in range(n):
# duplicate[i], duplicate[j] = duplicate[j], duplicate[i]
for k in range(n):
if check(d[k], i, j, k):
cnt += 1
if cnt > ans:
ans = cnt
l, r = i+1, j+1
# duplicate[i], duplicate[j] = duplicate[j], duplicate[i]
print(ans)
print(l, r)
``` | instruction | 0 | 86,718 | 21 | 173,436 |
No | output | 1 | 86,718 | 21 | 173,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
s = input()
sl = list(s)
ans = 0
ai = [1,1]
for i in range(n):
for j in range(i, n):
sl = list(s)
sl[i], sl[j] = sl[j], sl[i]
b = 0
p = 0
k = 0
while k < n and sl[k] == ")":
k += 1
for kk in range(n):
if sl[k] == "(":
p += 1
else:
if p == 1:
b += 1
elif p == 0:
b = 0
break
p -= 1
k = (k+1) % n
# print(sl,b,i,j)
if b > ans:
ans = b
ai = [i+1, j+1]
print(ans)
print(ai[0], ai[1])
``` | instruction | 0 | 86,719 | 21 | 173,438 |
No | output | 1 | 86,719 | 21 | 173,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,596 | 21 | 181,192 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
t = input()
n, m = len(t) + 1, 1000000007
a, b = 0, t.count(')') - 1
f = [1] * n
for i in range(2, n): f[i] = i * f[i - 1] % m
g = [pow(q, m - 2, m) for q in f]
s = 0
for q in t:
if b < 0: break
if q == '(':
a += 1
s += f[a + b] * g[a] * g[b]
else: b -= 1
print(s % m)
``` | output | 1 | 90,596 | 21 | 181,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,597 | 21 | 181,194 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
s = input()
n = len(s)
f = [1] * (n + 1)
for i in range(1, n + 1): f[i] = i * f[i - 1] % mod
finv = [pow(x, mod - 2, mod) for x in f]
op = 0
cl = s.count(')')
ans = 0
if cl > 0:
for c in s:
if c == '(':
op += 1
ans += f[op + cl - 1] * finv[cl - 1] * finv[op]
elif cl <= 1:
break
else:
cl -= 1
print(ans % mod)
``` | output | 1 | 90,597 | 21 | 181,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,598 | 21 | 181,196 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
fact, inv, invfact = [1, 1], [0, 1], [1, 1]
for i in range(2, 200200):
fact.append(fact[-1] * i % mod)
inv.append(inv[mod % i] * (mod - mod // i) % mod)
invfact.append(invfact[-1] * inv[-1] % mod)
def C(n, k):
if k < 0 or k > n:
return 0
return fact[n] * invfact[k] * invfact[n - k] % mod
s = input()
op, cl = 0, s.count(')')
ans = 0
for x in s:
if x == '(':
op += 1
cur = C(cl + op - 1, op)
ans += cur
else:
cl -= 1
print(ans % mod)
``` | output | 1 | 90,598 | 21 | 181,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,599 | 21 | 181,198 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
#!/usr/bin/env python3
def ri():
return map(int, input().split())
m = 10**9+7
s = input()
n = len(s)
o = [0 for i in range(len(s))]
c = [0 for i in range(len(s))]
fac = [0 for i in range(n)]
fac[0] = 1
for i in range(1,n):
fac[i] = fac[i-1]*i%m
invfac = [pow(fac[i], m-2, m) for i in range(n)]
if s[0] == '(':
o[0] = 1
for i in range(1,n):
if s[i] == '(':
o[i] = o[i-1] + 1
else:
o[i] = o[i-1]
if s[n-1] == ')':
c[n-1] = 1
for i in range(n-2, -1, -1):
if s[i] == ')':
c[i] = c[i+1] + 1
else:
c[i] = c[i+1]
ans = 0
for i in range(n):
if s[i] == '(':
a = o[i]
b = c[i]
if a != 0 and b != 0:
ans += fac[a+b-1]*invfac[a]*invfac[b-1]
ans %= m
print(ans)
``` | output | 1 | 90,599 | 21 | 181,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,600 | 21 | 181,200 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
s = input()
n = len(s)
f = [1] * (n + 1)
for i in range(1, n + 1): f[i] = i * f[i - 1] % mod
finv = [pow(x, mod - 2, mod) for x in f]
op = 0
cl = s.count(')')
ans = 0
if cl > 0:
for c in s:
if c == '(':
op += 1
ans += f[op + cl - 1] * finv[cl - 1] * finv[op]
elif cl <= 1:
break
else:
cl -= 1
print(ans % mod)
#bruno
``` | output | 1 | 90,600 | 21 | 181,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n β 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number β the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | instruction | 0 | 90,601 | 21 | 181,202 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
p = 10**9+7
def power(x, y, p):
b = bin(y)[2:]
answer = 1
start = x % p
for i in range(len(b)):
if b[len(b)-1-i]=='1':
answer = (answer*start) % p
start = (start*start) % p
return answer
def process(S):
answer = 0
n = len(S)
left_count = 0
right_count = 0
p_lc = 1
p_rc = 1
p_num = 1
num = 0
for c in S:
if c==')':
right_count+=1
p_rc = (p_rc*(right_count+1)) % p
num+=1
p_num = (p_num*num) % p
for i in range(n):
if S[i]=='(':
left_count+=1
if left_count > 1:
p_lc = (p_lc*(left_count-1)) % p
num+=1
p_num = (p_num*num) % p
else:
p_rc = (p_rc*power(right_count+1, p-2, p)) % p
p_num = (p_num*power(num, p-2, p)) % p
right_count-=1
num-=1
#(left_count choose n, right_count choose n-1)
#(left_count choose n, right_count choose rc-n+1))
#(lc+rc choose rc+1)
if left_count > 0:
entry = (p_num*power(p_lc, p-2, p)*power(p_rc, p-2, p)) % p
answer = (answer+entry) % p
return answer
S = input()
print(process(S))
``` | output | 1 | 90,601 | 21 | 181,203 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.