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 |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
n=int(input())
s=input()
sm=0
ans=0
if len(s)%2!=0:
print(-1)
else:
for i in s:
if s=='(':
sm+=1
else:
sm-=1
if sm==0:
print(-1)
else:
flag=False
val=0
l=0
for i in range(n):
if s[i]=='(':
val+=1
if val<=0:
l+=1
if val==0:
ans+=l
l=0
else:
if val>0:
val-=1
else:
l+=1
val-=1
if val==0:
print(ans)
else:
print(-1)
``` | instruction | 0 | 67,435 | 21 | 134,870 |
Yes | output | 1 | 67,435 | 21 | 134,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
'''I=input
I()
r=p=0
for x,y in zip(I(),I()):r+=x>y;p+=x<y
print(r and p//r+1or-1)
'''
__, s = input(), input()
a, n = 0, 0
pt = {'(': 1, ')': -1}
for c in s:
da = pt.get(c, 0)
if a < 0 or a + da < 0:
n += 1
a += da
if a != 0:
print(-1)
else:
print(n)
``` | instruction | 0 | 67,436 | 21 | 134,872 |
Yes | output | 1 | 67,436 | 21 | 134,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
input()
s=list(input())
a=0;cnt=0
if s.count(')')!=s.count('('): print(-1)
else:
for item in s:
if a<0 or (a==0 and item==')'): cnt+=1
if item=='(':
a+=1
else:
a-=1
print(cnt)
``` | instruction | 0 | 67,437 | 21 | 134,874 |
Yes | output | 1 | 67,437 | 21 | 134,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
n = int(input())
s = input()
cnt = 0
l = 0
ans = 0
cntl, cntr = 0, 0
for i in s:
if i == '(':
cnt -= 1
l += 1
cntl += 1
else:
cnt += 1
l += 1
cntr += 1
if cnt == 0:
ans += l
l = 0
print(ans if cntl == cntr else -1)
``` | instruction | 0 | 67,438 | 21 | 134,876 |
No | output | 1 | 67,438 | 21 | 134,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
n = int(input())
braces = input()
open_nr = braces.count('(')
closed_nr = braces.count(')')
ans = 0
if open_nr != closed_nr:
print(-1)
else:
balance = 0
balances = []
for brace in braces:
if brace == '(':
balance += 1
elif brace == ')':
balance -= 1
else:
raise
balances.append('+' if balance >= 0 else '-')
ans = sum(len(seg) + 1 for seg in ''.join(balances).split('+') if seg)
print(ans)
``` | instruction | 0 | 67,439 | 21 | 134,878 |
No | output | 1 | 67,439 | 21 | 134,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
ll=lambda:map(int,input().split())
t=lambda:int(input())
ss=lambda:input()
lx=lambda x:map(int,input().split(x))
#from math import log10 ,log2,ceil,factorial as fac,gcd
#from itertools import combinations_with_replacement as cs
#from functools import reduce
#from bisect import bisect_right as br,bisect_left as bl
#from collections import Counter
#for _ in range(t()):
def f():
n=t()
s=ss()
a=0
b=0
c=0
if n%2==1:
print(-1)
return
for i in s:
if i=="(":
if a>=0 :
a+=1
elif i==")":
a-=1
if a<0:
c+=2
print(c)
f()
``` | instruction | 0 | 67,440 | 21 | 134,880 |
No | output | 1 | 67,440 | 21 | 134,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds.
Submitted Solution:
```
a=int(input())
l=list(map(str,input()))
a=l.count("(")
b=l.count(")")
k="".join(l)
y=k.count("()")
if a==b:
print(a+b-(2*y))
else:
print("-1")
``` | instruction | 0 | 67,441 | 21 | 134,882 |
No | output | 1 | 67,441 | 21 | 134,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string s is given. It consists of k kinds of pairs of brackets. Each bracket has the form t β it is an integer, such that 1 β€ |t| β€ k. If the bracket has a form t, then:
* If t > 0, then it's an opening bracket of the type t.
* If t < 0, then it's a closing bracket of the type -t.
Thus, there are k types of pairs of brackets in total.
The queries need to be answered:
1. Replace the bracket at position i with the bracket of the form t.
2. Check if the substring from the l-th to r-th position (including) is the correct bracket sequence.
Recall the definition of the correct bracket sequence:
* An empty sequence is correct.
* If A and B are two correct bracket sequences, then their concatenation "A B" is also correct bracket sequence.
* If A is the correct bracket sequence, c (1 β€ c β€ k) is a type of brackets, then the sequence "c A -c" is also correct bracket sequence.
Input
The first line contains an integer n (1 β€ n β€ 10^5) β length of string and k (1 β€ k β€ n) β the number of kinds of pairs of brackets.
The second line contains string s of length n β n integers s_1, s_2, β¦, s_n (1 β€ |s_i| β€ k)
The third line contains single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the following q lines describes the queries:
* 1 i t - query of the 1 type (1 β€ i β€ n, 1 β€ |t| β€ k).
* 2 l r - query of the 2 type (1 β€ l β€ r β€ n).
Output
For each query of 2 type, output "Yes" if the substring from the query is the correct bracket sequence and "No", otherwise.
All letters can be displayed in any case.
Examples
Input
2 1
1 -1
1
2 1 2
Output
Yes
Input
2 2
1 -2
1
2 1 2
Output
No
Input
6 2
1 2 -2 -1 1 -1
3
2 1 6
2 1 4
2 2 5
Output
Yes
Yes
No
Input
2 2
-1 1
4
2 1 2
1 1 1
1 2 -1
2 1 2
Output
No
Yes
Note
In the fourth test, initially, the string is not a correct bracket sequence, so the answer to the first query is "No". After two changes it will be equal to "1 -1", so it is a correct bracket sequence and the answer to the fourth query is "Yes".
Submitted Solution:
```
import sys
input = sys.stdin.readline
MOD = 8675309
ORD = MOD - 1
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
start += self._size
stop += self._size
resL = self._default
resR = self._default
while start < stop:
if start & 1:
resL = self._func(resL,self.data[start])
start += 1
if stop & 1:
stop -= 1
resR = self._func(self.data[stop], resR)
start >>= 1
stop >>= 1
return self._func(resL,resR)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def comb(a,b):
if a[1] and b[1]:
left = a[0]
right = b[2]
midL = a[2]
midR = b[0]
if midR[0] > midL[0]:
newLen = midR[0] - midL[0]
newVal = midR[1] - midL[1]
newVal *= pow(k,ORD - midL[0] + left[0],MOD)
left = (left[0] + newLen, (newVal + left[1]) % MOD)
else:
newLen = midL[0] - midR[0]
newVal = midL[1] - midR[1]
newVal *= pow(k,ORD - midR[0] + right[0],MOD)
if newLen == 0 and newVal != 0 or 0 < newLen and newLen < MOD ** (1/newLen) and newVal > k ** newLen:
print(1,newLen, newVal)
return (False, False, False)
right = (right[0] + newLen, (newVal + right[1]) % MOD)
return (left, True, right)
else:
return (False, False, False)
import random
OFFSET1 = 2*random.randint(0,4095)
n, k = map(int,input().split())
l = map(int,input().split())
l2 = [((0,0),True,(1,v)) if v > 0 else ((1,-v),True,(0,0)) for v in l]
segtree = SegmentTree([((0,0),True,(0,0))] * OFFSET1 + l2, default = ((0,0),True,(0,0)), func = comb)
outL = []
q = int(input())
for i in range(q):
t, a, b = map(int,input().split())
if t == 1:
segtree.__setitem__(a - 1 + OFFSET1, ((0,0),True,(1,b)) if b > 0 else ((1,-b),True,(0,0)))
else:
out = (segtree.query(a - 1 + OFFSET1, b + OFFSET1))
if out[1] and out[0][0] == 0 and out[2][0] == 0:
outL.append('Yes')
else:
outL.append('No')
#print(out)
print('\n'.join(outL))
``` | instruction | 0 | 67,442 | 21 | 134,884 |
No | output | 1 | 67,442 | 21 | 134,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string s is given. It consists of k kinds of pairs of brackets. Each bracket has the form t β it is an integer, such that 1 β€ |t| β€ k. If the bracket has a form t, then:
* If t > 0, then it's an opening bracket of the type t.
* If t < 0, then it's a closing bracket of the type -t.
Thus, there are k types of pairs of brackets in total.
The queries need to be answered:
1. Replace the bracket at position i with the bracket of the form t.
2. Check if the substring from the l-th to r-th position (including) is the correct bracket sequence.
Recall the definition of the correct bracket sequence:
* An empty sequence is correct.
* If A and B are two correct bracket sequences, then their concatenation "A B" is also correct bracket sequence.
* If A is the correct bracket sequence, c (1 β€ c β€ k) is a type of brackets, then the sequence "c A -c" is also correct bracket sequence.
Input
The first line contains an integer n (1 β€ n β€ 10^5) β length of string and k (1 β€ k β€ n) β the number of kinds of pairs of brackets.
The second line contains string s of length n β n integers s_1, s_2, β¦, s_n (1 β€ |s_i| β€ k)
The third line contains single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the following q lines describes the queries:
* 1 i t - query of the 1 type (1 β€ i β€ n, 1 β€ |t| β€ k).
* 2 l r - query of the 2 type (1 β€ l β€ r β€ n).
Output
For each query of 2 type, output "Yes" if the substring from the query is the correct bracket sequence and "No", otherwise.
All letters can be displayed in any case.
Examples
Input
2 1
1 -1
1
2 1 2
Output
Yes
Input
2 2
1 -2
1
2 1 2
Output
No
Input
6 2
1 2 -2 -1 1 -1
3
2 1 6
2 1 4
2 2 5
Output
Yes
Yes
No
Input
2 2
-1 1
4
2 1 2
1 1 1
1 2 -1
2 1 2
Output
No
Yes
Note
In the fourth test, initially, the string is not a correct bracket sequence, so the answer to the first query is "No". After two changes it will be equal to "1 -1", so it is a correct bracket sequence and the answer to the fourth query is "Yes".
Submitted Solution:
```
import sys
input = sys.stdin.readline
MOD = 8675309
ORD = MOD - 1
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
start += self._size
stop += self._size
resL = self._default
resR = self._default
while start < stop:
if start & 1:
resL = self._func(resL,self.data[start])
start += 1
if stop & 1:
stop -= 1
resR = self._func(self.data[stop], resR)
start >>= 1
stop >>= 1
return self._func(resL,resR)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def comb(a,b):
if a[1] and b[1]:
left = a[0]
right = b[2]
midL = a[2]
midR = b[0]
if midR[0] > midL[0]:
newLen = midR[0] - midL[0]
newVal = midR[1] - midL[1]
newVal *= pow(k,ORD - midL[0] + left[0],MOD)
left = (left[0] + newLen, (newVal + left[1]) % MOD)
else:
newLen = midL[0] - midR[0]
newVal = midL[1] - midR[1]
newVal *= pow(k,ORD - midR[0] + right[0],MOD)
if newLen == 0 and newVal != 0 or 0 < newLen and newLen < MOD ** (1/newLen) and newVal > k ** newLen:
#print(1,newLen, newVal)
return (False, False, False)
right = (right[0] + newLen, (newVal + right[1]) % MOD)
return (left, True, right)
else:
return (False, False, False)
import random
OFFSET1 = 0
n, k = map(int,input().split())
l = map(int,input().split())
l2 = [((0,0),True,(1,v)) if v > 0 else ((1,-v),True,(0,0)) for v in l]
segtree = SegmentTree([((0,0),True,(0,0))] * OFFSET1 + l2, default = ((0,0),True,(0,0)), func = comb)
outL = []
q = int(input())
for i in range(q):
t, a, b = map(int,input().split())
if t == 1:
segtree.__setitem__(a - 1 + OFFSET1, ((0,0),True,(1,b)) if b > 0 else ((1,-b),True,(0,0)))
else:
out = (segtree.query(a - 1 + OFFSET1, b + OFFSET1))
if out[1] and out[0][0] == 0 and out[2][0] == 0:
outL.append('Yes')
else:
outL.append('No')
#print(out)
print('\n'.join(outL))
``` | instruction | 0 | 67,443 | 21 | 134,886 |
No | output | 1 | 67,443 | 21 | 134,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string s is given. It consists of k kinds of pairs of brackets. Each bracket has the form t β it is an integer, such that 1 β€ |t| β€ k. If the bracket has a form t, then:
* If t > 0, then it's an opening bracket of the type t.
* If t < 0, then it's a closing bracket of the type -t.
Thus, there are k types of pairs of brackets in total.
The queries need to be answered:
1. Replace the bracket at position i with the bracket of the form t.
2. Check if the substring from the l-th to r-th position (including) is the correct bracket sequence.
Recall the definition of the correct bracket sequence:
* An empty sequence is correct.
* If A and B are two correct bracket sequences, then their concatenation "A B" is also correct bracket sequence.
* If A is the correct bracket sequence, c (1 β€ c β€ k) is a type of brackets, then the sequence "c A -c" is also correct bracket sequence.
Input
The first line contains an integer n (1 β€ n β€ 10^5) β length of string and k (1 β€ k β€ n) β the number of kinds of pairs of brackets.
The second line contains string s of length n β n integers s_1, s_2, β¦, s_n (1 β€ |s_i| β€ k)
The third line contains single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the following q lines describes the queries:
* 1 i t - query of the 1 type (1 β€ i β€ n, 1 β€ |t| β€ k).
* 2 l r - query of the 2 type (1 β€ l β€ r β€ n).
Output
For each query of 2 type, output "Yes" if the substring from the query is the correct bracket sequence and "No", otherwise.
All letters can be displayed in any case.
Examples
Input
2 1
1 -1
1
2 1 2
Output
Yes
Input
2 2
1 -2
1
2 1 2
Output
No
Input
6 2
1 2 -2 -1 1 -1
3
2 1 6
2 1 4
2 2 5
Output
Yes
Yes
No
Input
2 2
-1 1
4
2 1 2
1 1 1
1 2 -1
2 1 2
Output
No
Yes
Note
In the fourth test, initially, the string is not a correct bracket sequence, so the answer to the first query is "No". After two changes it will be equal to "1 -1", so it is a correct bracket sequence and the answer to the fourth query is "Yes".
Submitted Solution:
```
import sys
input = sys.stdin.readline
MOD = 1234568107
ORD = MOD - 1
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
start += self._size
stop += self._size
resL = self._default
resR = self._default
while start < stop:
if start & 1:
resL = self._func(resL,self.data[start])
start += 1
if stop & 1:
stop -= 1
resR = self._func(self.data[stop], resR)
start >>= 1
stop >>= 1
return self._func(resL,resR)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def comb(a,b):
if a[1] and b[1]:
left = a[0]
right = b[2]
midL = a[2]
midR = b[0]
if midR[0] > midL[0]:
newLen = midR[0] - midL[0]
newVal = midR[1] - midL[1]
newVal *= pow(k,ORD - midL[0] + left[0],MOD)
left = (left[0] + newLen, (newVal + left[1]) % MOD)
else:
newLen = midL[0] - midR[0]
newVal = midL[1] - midR[1]
newVal *= pow(k,ORD - midR[0] + right[0],MOD)
if newLen == 0 and newVal != 0:
return (False, False, False)
right = (right[0] + newLen, (newVal + right[1]) % MOD)
return (left, True, right)
else:
return (False, False, False)
n, k = map(int,input().split())
l = map(int,input().split())
l2 = [((0,0),True,(1,v)) if v > 0 else ((1,-v),True,(0,0)) for v in l]
segtree = SegmentTree(l2, default = ((0,0),True,(0,0)), func = comb)
outL = []
q = int(input())
for i in range(q):
t, a, b = map(int,input().split())
if t == 1:
segtree.__setitem__(a - 1, ((0,0),True,(1,b)) if b > 0 else ((1,-b),True,(0,0)))
else:
out = (segtree.query(a - 1, b))
if out[1] and out[0][0] == 0 and out[2][0] == 0:
outL.append('Yes')
else:
outL.append('No')
#print(out)
print('\n'.join(outL))
``` | instruction | 0 | 67,444 | 21 | 134,888 |
No | output | 1 | 67,444 | 21 | 134,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string s is given. It consists of k kinds of pairs of brackets. Each bracket has the form t β it is an integer, such that 1 β€ |t| β€ k. If the bracket has a form t, then:
* If t > 0, then it's an opening bracket of the type t.
* If t < 0, then it's a closing bracket of the type -t.
Thus, there are k types of pairs of brackets in total.
The queries need to be answered:
1. Replace the bracket at position i with the bracket of the form t.
2. Check if the substring from the l-th to r-th position (including) is the correct bracket sequence.
Recall the definition of the correct bracket sequence:
* An empty sequence is correct.
* If A and B are two correct bracket sequences, then their concatenation "A B" is also correct bracket sequence.
* If A is the correct bracket sequence, c (1 β€ c β€ k) is a type of brackets, then the sequence "c A -c" is also correct bracket sequence.
Input
The first line contains an integer n (1 β€ n β€ 10^5) β length of string and k (1 β€ k β€ n) β the number of kinds of pairs of brackets.
The second line contains string s of length n β n integers s_1, s_2, β¦, s_n (1 β€ |s_i| β€ k)
The third line contains single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the following q lines describes the queries:
* 1 i t - query of the 1 type (1 β€ i β€ n, 1 β€ |t| β€ k).
* 2 l r - query of the 2 type (1 β€ l β€ r β€ n).
Output
For each query of 2 type, output "Yes" if the substring from the query is the correct bracket sequence and "No", otherwise.
All letters can be displayed in any case.
Examples
Input
2 1
1 -1
1
2 1 2
Output
Yes
Input
2 2
1 -2
1
2 1 2
Output
No
Input
6 2
1 2 -2 -1 1 -1
3
2 1 6
2 1 4
2 2 5
Output
Yes
Yes
No
Input
2 2
-1 1
4
2 1 2
1 1 1
1 2 -1
2 1 2
Output
No
Yes
Note
In the fourth test, initially, the string is not a correct bracket sequence, so the answer to the first query is "No". After two changes it will be equal to "1 -1", so it is a correct bracket sequence and the answer to the fourth query is "Yes".
Submitted Solution:
```
import io
import os
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class Node:
def __init__(self, frontHash=0, frontLen=0, backHash=0, backLen=0):
self.frontHash = frontHash
self.frontLen = frontLen
self.backHash = backHash
self.backLen = backLen
def __repr__(self):
return str((self.frontHash, self.frontLen, self.backHash, self.backLen))
segNeutral = Node()
def segMap(x):
if x > 0:
frontHash = 0
frontLen = 0
backHash = x
backLen = 1
else:
frontHash = -x
frontLen = 1
backHash = 0
backLen = 0
return Node(frontHash, frontLen, backHash, backLen)
PRIME = 31
MOD = 10 ** 9 + 7
PRIME_INV = pow(PRIME, MOD - 2, MOD)
def hashAppend(h1, n1, h2, n2):
return (h1 * pow(PRIME, n2, MOD) + h2) % MOD
def hashPop(h1, n1, h2, n2):
return ((h1 - h2) * pow(PRIME_INV, n2, MOD)) % MOD
def segCombine(l, r):
# Front is unmatched closing parens, back is unmatched opening parens. eg )))]]}]([[[({
# Left's back and right's front should match each other
# Delete the shorter from the longer optimistically (even if they turn out to not be matches)
if l.backLen > r.frontLen:
midHash = hashPop(l.backHash, l.backLen, r.frontHash, r.frontLen)
midLen = l.backLen - r.frontLen
frontHash = l.frontHash
frontLen = l.frontLen
backHash = hashAppend(midHash, midLen, r.backHash, r.backLen)
backLen = midLen + r.backLen
else:
assert l.backLen <= r.frontLen
midHash = hashPop(r.frontHash, r.frontLen, l.backHash, l.backLen)
midLen = r.frontLen - l.backLen
frontHash = hashAppend(midHash, midLen, l.frontHash, l.frontLen)
frontLen = midLen + l.frontLen
backHash = r.backHash
backLen = r.backLen
return Node(frontHash, frontLen, backHash, backLen)
def solve(N, K, S, Q, queries):
ans = []
segTree = SegmentTree(list(map(segMap, S)), segNeutral, segCombine)
for query in queries:
if query[0] == 1:
_, i, t = query
i -= 1
segTree[i] = segMap(t)
else:
assert query[0] == 2
_, l, r = query
l -= 1
r -= 1
r += 1
res = segTree.query(l, r)
if res.frontHash == res.backHash == 0 and res.frontLen == res.backLen == 0:
ans.append("Yes")
else:
ans.append("No")
return "\n".join(ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, K = [int(x) for x in input().split()]
S = [int(x) for x in input().split()]
(Q,) = [int(x) for x in input().split()]
queries = [[int(x) for x in input().split()] for i in range(Q)]
ans = solve(N, K, S, Q, queries)
print(ans)
``` | instruction | 0 | 67,445 | 21 | 134,890 |
No | output | 1 | 67,445 | 21 | 134,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,888 | 21 | 145,776 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
n, k = map(int, input().split())
arr = [[-2 * 10 ** 9] for i in range(k)]
for i, j in enumerate(input().split()):
arr[i % k].append(j)
b = True
for i in range(k):
arr[i].append(2 * 10 ** 9)
z, c = 1, 0
while z < len(arr[i]):
while arr[i][z] == '?':
z += 1
arr[i][z] = int(arr[i][z])
d = z - c - 1
if arr[i][z] - arr[i][c] < d + 1:
b = False
break
if arr[i][c] > 0:
s = arr[i][c] + 1
else:
#print(d, arr[i][c], arr[i][z])
s = min(-(d // 2), arr[i][z] - d)
s = max(s, arr[i][c] + 1)
for j in range(c + 1, z):
arr[i][j] = s
s += 1
c = z
z += 1
if not b:
print('Incorrect sequence')
break
else:
z = 1
i = 0
j = 0
while i < n:
i += 1
print(arr[j][z], end = ' ')
j += 1
if j == k:
j = 0
z += 1
``` | output | 1 | 72,888 | 21 | 145,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,889 | 21 | 145,778 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
import sys
n, k = map(int, input().split())
a = input().split()
INF = 10 ** 9 + 7
OK = True
for i in range(n):
if a[i] == "?":
a[i] = INF
else:
a[i] = int(a[i])
for i in range(len(a)):
if a[i] == INF:
j = i + k
while j < len(a) and a[j] == INF:
j += k
count = (j - i) // k
if i - k >= 0:
left = a[i - k]
else:
left = - INF
if j < len(a):
right = a[j]
else:
right = INF
if right < INF and left > -INF and right - left <= count:
print("Incorrect sequence")
OK = False
break
if left >= -1:
a[i: j: k] = [left + g + 1 for g in range(count)]
elif right <= 1:
a[i: j: k] = [right - count + g for g in range(count)]
else:
if - left < right:
c1 = min(- left - 1, count // 2)
new = [- c1 + g for g in range(count)]
else:
c2 = min(right - 1, count // 2)
new = [c2 - count + 1 + g for g in range(count)]
a[i: j: k] = new
if OK:
for i in range(n - k):
if a[i] >= a[i + k]:
print("Incorrect sequence")
OK = False
break
if OK:
print(" ".join(map(str, a)))
``` | output | 1 | 72,889 | 21 | 145,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,890 | 21 | 145,780 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
import math
n, k = map(int, input().split())
strings = list(input().split())
a = []
MIN = -1000 * 1000 * 1000 * 1000
def prove(pos):
index = pos
while index < len(a):
if a[index] != MIN:
return False;
index += k
element = -((index - pos) // k - 1) // 2
index = pos
while index < len(a):
a[index] = element
element += 1
index += k
return True
def begin(pos):
if a[pos] != MIN:
return pos
first = pos
length = 0
while a[first] == MIN:
first += k
length += 1
element = min(a[first] - length, -((first - pos) // k - 1) // 2)
while pos < first:
a[pos] = element
element += 1
pos += k
return first
def end(pos, index):
pos += k
if pos == index or pos >= len(a):
return
element = max(a[pos - k] + 1, -((index - pos) // k - 1) // 2);
while pos < len(a):
a[pos] = element
element += 1
pos += k
def fill(l, r):
if (r - l) // k - 1 > a[r] - a[l] - 1:
print("Incorrect sequence")
exit(0)
cnt = (r - l) // k - 1
if a[l] >= 0:
element = a[l] + 1
if a[r] <= 0:
element = a[r] - cnt
if (a[r] >= 0) and (a[l] <= 0):
element = max(min(-(cnt // 2), a[r] - cnt), a[l] + 1)
l += k
while l < r:
a[l] = element
element += 1
l += k
def update(pos):
if prove(pos):
return
pos = begin(pos)
index = pos + k
while index < len(a):
index = pos + k
while index < len(a) and a[index] == MIN:
index += k
if index >= len(a):
break
fill(pos, index)
pos = index
end(pos, index)
def print_array():
for x in a:
print(x, end = ' ')
for x in strings:
if x == '?':
a.append(MIN)
else:
a.append(int(x))
for i in range(0, k):
update(i)
print_array()
``` | output | 1 | 72,890 | 21 | 145,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,891 | 21 | 145,782 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
INF = 1 << 60
Q = 1 << 58
def solve():
ans = [0] * n
for i in range(k):
b = [-INF]
b.extend(a[i:n:k])
m = len(b)
b.append(INF)
lb = -INF
p, q = 1, 0
while p < m:
while b[p] == Q:
p += 1
l = p - q - 1
lb = b[q] + 1
for j in range(q + 1, p):
b[j] = lb
lb += 1
if b[p] < lb:
return None
if lb < 0:
if b[p] > 0:
lb = min((l - 1) // 2, b[p] - 1)
elif b[p] <= 0:
lb = b[p] - 1
for j in range(p - 1, q, -1):
b[j] = lb
lb -= 1
q = p
p = q + 1
ans[i:n:k] = b[1:m]
return ans
n, k = [int(x) for x in input().split()]
a = [Q if x == '?' else int(x) for x in input().split()]
ans = solve()
if ans is None:
print('Incorrect sequence')
else:
print(*ans)
``` | output | 1 | 72,891 | 21 | 145,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,892 | 21 | 145,784 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
def foo(left, right, number):
left += 1
right -= 1
if right - left + 1 < number:
return 10 ** 10
num = number // 2
if number % 2:
if num <= right and -num >= left:
return -num
else :
if -num >= left and num- 1 <= right:
return -num
if -num + 1 >= left and num <= right:
return -num + 1
if abs(left) < abs(right):
return left
else :
return right - number + 1
con = 10 ** 10
n, k = map(int, input().split())
a = list(input().split())
for i in range(k):
left = -con
number = 0
place = i
for j in range(i, n, k):
if (a[j][0] == '?') :
number += 1
if number == 1:
place = j
else:
right = int(a[j])
t = foo(left, right, number)
if t == con:
print("Incorrect sequence")
exit()
for r in range(place, j, k):
a[r] = t
t += 1
number = 0
left = right
place = j + k
if number:
t = foo(left, con, number)
if t == con:
print("Incorrect sequence")
exit()
for r in range(place, n, k):
a[r] = t
t += 1
number = 0
left = con
print(" ".join(map(str,a)))
``` | output | 1 | 72,892 | 21 | 145,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,893 | 21 | 145,786 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
INF = 10000000001
def fill(s):
s.insert(0, -INF)
s.append(INF)
i = 0
for j in filter(lambda x: s[x] != '?', range(1, len(s))):
d = i - j
s[j] = int(s[j])
if s[i] > s[j]+d:
raise
a = max(min(d//2, s[j]+d), s[i])
for t in range(i+1, j):
s[t] = a + t - i
i = j
return s[1:-1]
n, k = map(int, input().split())
s = input().split()
try:
g = [fill([s[i] for i in range(j, n, k)]) for j in range(k)]
print(' '.join(str(g[i%k][i//k]) for i in range(n)))
except:
print('Incorrect sequence')
``` | output | 1 | 72,893 | 21 | 145,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 β€ i β€ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 β€ ai β€ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers β Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence | instruction | 0 | 72,894 | 21 | 145,788 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
#!/usr/bin/env python3
import sys, math
N, K = input().split(' ')
N = int(N)
K = int(K)
raw_a = input().split(' ')
a = ['?'] * N
known_idxs = set()
# if (N, K) == (99941, 52):
# print(' '.join(raw_a[500:600]))
for i, e in enumerate(raw_a):
if e != '?':
a[i] = int(e)
known_idxs.add(i)
def fail():
print('Incorrect sequence')
sys.exit(0)
def do_fix(aa, b, c, d, e, f = 1):
assert(len(range(aa, b, c)) == len(range(d, e, f)))
a[aa:b:c] = range(d, e, f)
def fix(start, end):
# fix [start...end] with stride K
# print(a[start:end+1:K])
l = len(range(start, end+1, K))
if l == 2 and a[start] == '?' and a[end] == '?':
a[start] = 0
a[end] = 1
return
a_e = float('+inf') if a[end] == '?' else a[end]
a_s = float('-inf') if a[start] == '?' else a[start]
left_0 = l - a_e - 2
right_0 = -1 - a_s
if (left_0 > right_0):
fail()
else:
assert(left_0 <= right_0)
L = l + (a[start] == '?') + (a[end] == '?')
opt_0 = (L - 2) // 2 - (a[start] == '?')
opt_0 = min(opt_0, right_0)
opt_0 = max(opt_0, left_0)
s = -opt_0
do_fix(start+K, end, K, s, s+l-2)
# print("done middle", a[start:end+1:K])
if a[end] == '?' and end-K >= 0:
a[end] = max(0, a[end-K] + 1)
elif a[end] == '?':
a[end] = 0
# print(":)", a[start:end+1:K])
if a[start] == '?' and start+K < N:
a[start] = min(0, a[start+K] - 1)
elif a[start] == '?':
a[start] = 0
# print("done", a[start:end+1:K])
for s in range(0, K):
sub_idxs = list(range(s, N, K))
sub_ki = [i for i in sub_idxs if i in known_idxs]
if sub_idxs[0] not in sub_ki:
sub_ki = [sub_idxs[0]] + sub_ki
if sub_idxs[-1] not in sub_ki:
sub_ki = sub_ki + [sub_idxs[-1]]
if len(sub_ki) == 1:
(i, ) = sub_ki
if a[i] == '?':
a[i] = 0
for i in range(0, len(sub_ki) - 1):
fix(sub_ki[i], sub_ki[i + 1])
print(' '.join(map(str, a)))
``` | output | 1 | 72,894 | 21 | 145,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,967 | 21 | 149,934 |
Tags: greedy
Correct Solution:
```
n,k=map(int,input().split())
s=input()
a=[]
ans=0
for i in s:
if k==0:
break
if i=='(' and k>0:
a+=[i]
ans+=1
k-=2
if i==')':
a+=i
ans-=1
for i in a:
print(i,end='')
for i in range(ans):
print(')',end='')
``` | output | 1 | 74,967 | 21 | 149,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,968 | 21 | 149,936 |
Tags: greedy
Correct Solution:
```
n, k = map(int, input().split())
s = input()
used = [False] * n
index = []
cnt = 0
for i in range(n):
if s[i] == '(':
index.append(i)
else:
if len(index) > 0:
j = index.pop()
used[i] = True
used[j] = True
cnt += 2
if cnt == k:
break
for i in range(n):
if used[i]:
print(s[i], end='')
``` | output | 1 | 74,968 | 21 | 149,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,969 | 21 | 149,938 |
Tags: greedy
Correct Solution:
```
n , m = map(int , input().split())
s = str(input())
l = list(s)
left = []
right = []
ans = ""
c = 0
b = 0
for i in range(0 , n):
if l[i] == '(' and c < m // 2:
b += 1
ans += '('
c += 1
elif b :
ans += ')'
b -= 1
print(ans)
``` | output | 1 | 74,969 | 21 | 149,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,970 | 21 | 149,940 |
Tags: greedy
Correct Solution:
```
n,k=map(int,input().split())
A=input()
p=0
for i in range(n):
if p+i==k:
print(A[:i]+")"*p)
break
if A[i]=="(":
p+=1
else:
p-=1
``` | output | 1 | 74,970 | 21 | 149,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,971 | 21 | 149,942 |
Tags: greedy
Correct Solution:
```
n, k = map(int, input().strip().split())
s = input().strip()
t = [i for i in s]
for i in range(n):
if k == n:
break
if t[i] == '(':
t[i] = ''
k += 2
p = 0
for i in range(n):
if t[i] == '(':
p += 1
elif t[i] == ')':
p -= 1
if p < 0:
t[i] = ''
p += 1
print(''.join(t))
``` | output | 1 | 74,971 | 21 | 149,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,972 | 21 | 149,944 |
Tags: greedy
Correct Solution:
```
import sys
# sys.setrecursionlimit(300000)
# Get out of main functoin
def main():
pass
# decimal to binary
def binary(n):
return (bin(n).replace("0b", ""))
# binary to decimal
def decimal(s):
return (int(s, 2))
# power of a number base 2
def pow2(n):
p = 0
while n > 1:
n //= 2
p += 1
return (p)
# if number is prime in βn time
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
# list to string ,no spaces
def lts(l):
s = ''.join(map(str, l))
return s
# String to list
def stl(s):
# for each character in string to list with no spaces -->
l = list(s)
# for space in string -->
# l=list(s.split(" "))
return l
# Returns list of numbers with a particular sum
def sq(a, target, arr=[]):
s = sum(arr)
if (s == target):
return arr
if (s >= target):
return
for i in range(len(a)):
n = a[i]
remaining = a[i + 1:]
ans = sq(remaining, target, arr + [n])
if (ans):
return ans
# Sieve for prime numbers in a range
def SieveOfEratosthenes(n):
cnt = 0
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, n + 1):
if prime[p]:
cnt += 1
# print(p)
return (cnt)
# for positive integerse only
def nCr(n, r):
f = math.factorial
return f(n) // f(r) // f(n - r)
# 1000000007
mod = int(1e9) + 7
def ssinp(): return sys.stdin.readline().strip()
# s=input()
def iinp(): return int(input())
# n=int(input())
def nninp(): return map(int, sys.stdin.readline().strip().split())
# n, m, a=[int(x) for x in input().split()]
def llinp(): return list(map(int, sys.stdin.readline().strip().split()))
# a=list(map(int,input().split()))
def p(xyz): print(xyz)
def p2(a, b): print(a, b)
import math
#list.sort(key=lambda x:x[1]) for sorting a list according to second element in sublist
# d1.setdefault(key, []).append(value)
# ASCII of A-Z= 65-90
# ASCII of a-z= 97-122
#import random
#from collections import OrderedDict
#from fractions import Fraction
#============Speed: STRING < LIST < SET,DICTIONARY==========================
#for __ in range(iinp()):
n,k=nninp()
s=ssinp()
ans=[]
lb=k//2
rb=k//2
for c in s:
if(lb>0):
if(c=="("):
lb-=1
else:
rb-=1
ans.append(c)
elif(rb>0):
if(c==")"):
ans.append(c)
rb-=1
elif(lb==0 and rb==0):
break
p(lts(ans))
""" Stuff you should look for
int overflow, array bounds
special cases (n=1?)
do something instead of nothing and stay organized
WRITE STUFF DOWN
DON'T GET STUCK ON ONE APPROACH"""
``` | output | 1 | 74,972 | 21 | 149,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,973 | 21 | 149,946 |
Tags: greedy
Correct Solution:
```
n,k=map(int,input().split())
s=input()
arr=[]
for i in range(n):
arr.append(s[i])
if n==k:
print(s)
else:
count_open=0
count_close=0
for i in range(n):
if s[i]=='(':
count_open+=1
count_close+=1
print('(',end="")
elif s[i]==')':
count_close-=1
print(')',end="")
if count_open==k//2:
break
while count_close>0:
print(')',end="")
count_close-=1
print()
``` | output | 1 | 74,973 | 21 | 149,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(())) | instruction | 0 | 74,974 | 21 | 149,948 |
Tags: greedy
Correct Solution:
```
#!/usr/bin/python3
def solve(N, K, S):
pos = [-1] * N
stk = []
for i, c in enumerate(S):
if c == '(':
stk.append(i)
else:
j = stk.pop()
pos[j] = i
pos[i] = j
assert not stk
kill = bytearray(N)
nkill = (N - K) // 2
if nkill > 0:
for i in range(N):
if S[i] == ')':
continue
j = pos[i]
kill[i] = 1
kill[j] = 1
nkill -= 1
if nkill == 0:
break
ansl = []
for i in range(N):
if not kill[i]:
ansl.append(S[i])
return ''.join(ansl)
def main():
N, K = [int(e) for e in input().split(' ')]
S = input()
print(solve(N, K, S))
if __name__ == '__main__':
main()
``` | output | 1 | 74,974 | 21 | 149,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
"""Problem C - Bracket Subsequence.
https://codeforces.com/contest/1023/problem/C
A bracket sequence is a string containing only characters "(" and ")". A
regular bracket sequence is a bracket sequence that can be transformed into a
correct arithmetic expression by inserting characters "1" and "+" between the
original characters of the sequence. For example, bracket sequences "()()" and
"(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"),
and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by
deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence `s` and an integer number `k`. Your
task is to find a regular bracket sequence of length exactly `k` such that it
is also a subsequence of `s`.
It is guaranteed that such sequence always exists.
Input:
The first line contains two integers `n` and `k` (`2 <= k <= n <= 2 * 10^5`,
both `n` and `k` are even) β the length of `s` and the length of the sequence
you are asked to find.
The second line is a string `s` β regular bracket sequence of length `n`.
Output:
Print a single string β a regular bracket sequence of length exactly `k` such
that it is also a subsequence of `s`.
It is guaranteed that such sequence always exists.
"""
import logging
fmt = r'%(levelname)s - %(name)s (line:%(lineno)s) - %(message)s'
formatter = logging.Formatter(fmt)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
logger = logging.getLogger('bracket_subsequence')
logger.setLevel(logging.ERROR)
logger.addHandler(ch)
# class Bracket:
# def __init__(self):
# self.children = []
# def add(self, s):
# pass
# def remove(self, child=0):
# if self.children[child].has_children():
# self.children[child].remove()
def parse(s):
stack = []
for i, c in enumerate(s):
if c == ')':
idx = stack.pop()
yield (idx, i)
else:
stack.append(i)
def solve(k, s):
# if len(s) == 2 * k:
# return s
indices = parse(s)
sorted_indices = sorted(indices, key=lambda x: x[1] - x[0], reverse=True)
# print(sorted_indices)
res = sorted_indices[:k // 2]
# print('>', res)
ans = [0] * len(s)
for i, j in res:
ans[i] = '('
ans[j] = ')'
# print(ans)
sol = [x for x in ans if x != 0]
# print(sol)
return ''.join(sol)
def main():
n, k = map(int, input().strip().split())
s = input().strip()
result = solve(k, s)
print(result)
if __name__ == '__main__':
main()
``` | instruction | 0 | 74,975 | 21 | 149,950 |
Yes | output | 1 | 74,975 | 21 | 149,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
n, k = map(int, input().split())
A = input()
p = (n - k) // 2
m, o = 0, 0
for i in range(n):
if A[i] == '(':
if m < p:
m += 1
else:
print('(', end='')
else:
if o < p:
o += 1
else:
print(')', end='')
``` | instruction | 0 | 74,976 | 21 | 149,952 |
Yes | output | 1 | 74,976 | 21 | 149,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
import sys, os
from io import BytesIO, IOBase
import math
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from itertools import permutations
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
# region fastio
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")
stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return Fals
return True
n, k = mp()
s, stk, ans, mem = inp(), [], [], set()
for i in range(n):
if len(mem) == k:
break
if s[i] == '(':
stk.append(i)
else:
mem.add(i)
mem.add(stk.pop())
for i in range(n):
if i in mem:
ans.append(s[i])
print(''.join(ans))
``` | instruction | 0 | 74,977 | 21 | 149,954 |
Yes | output | 1 | 74,977 | 21 | 149,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
a, b = [int(x) for x in input().split()]
d = int(b/2)
s = input()
z = 0
r = ""
t = 0
for x in list(s):
if x == "(":
if t < d:
z += 1
t += 1
r += x
else:
z -= 1
if z < 0:
z = 0
else:
r += x
if (len(r) == b):
break
print(r)
``` | instruction | 0 | 74,978 | 21 | 149,956 |
Yes | output | 1 | 74,978 | 21 | 149,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
n, m = list(map(int, input().split())); a=input(); x=0; y=0
a=' '+a;
mo = [0]*4*(n+5); dong = [0]*4*(n+5);
def build(l, r, node):
l=int(l); r=int(r); node=int(node)
if int(l)==int(r):
if a[l]=='(': mo[node]=1; return
else: dong[node]=1; return
mid=int(l+r)/2
build(l, mid, 2*node)
build(mid+1, r, 2*node+1)
mo[node]=mo[2*node]+mo[2*node+1]
dong[node]=dong[2*node]+dong[2*node+1]
def querymo(l, r, node, low, high):
l=int(l); r=int(r); node=int(node); low=int(low); high=int(high)
if l>high or r<low: return 0
if l>=low and r<=high: return mo[node]
mid=int(l+r)/2
return (querymo(l, mid, 2*node, low, high) + querymo(mid+1, r, 2*node+1, low, high))
def querydong(l, r, node, low, high):
l=int(l); r=int(r); node=int(node); low=int(low); high=int(high)
if l>high or r<low: return 0
if l>=low and r<=high: return dong[node]
mid=int(l+r)/2
return (querydong(l, mid, 2*node, low, high) + querydong(mid+1, r, 2*node+1, low, high))
build(1, n, 1)
for i in range(1, n-m+2):
if a[i]=='(':
if querymo(1, n, 1, i, i+m-1)==querydong(1, n, 1, i, i+m-1): x=i; y=i+m-1; break
for i in range(x, y+1): print(a[i], end='')
``` | instruction | 0 | 74,979 | 21 | 149,958 |
No | output | 1 | 74,979 | 21 | 149,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
n, k = map(int, input().split())
s = input()
a = []
r = 0
m = 0
ind = 0
k = n-k
for i, e in enumerate(s):
if e == '(':
m += 1
r += 2
else:
m -= 1
if m == 0:
if r <= k:
s = s[r:]
k -= r
r = 0
else:
ind = r
break
#print(r-k)
y = 0;
i = 0
while k != y:
if s[i] == '(':
a.append(i)
else:
y += 2
i += 1
if k != 0:
index = a[-y//2]
s = s[0:index] + s[index+y:]
print(s)
``` | instruction | 0 | 74,980 | 21 | 149,960 |
No | output | 1 | 74,980 | 21 | 149,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
'''
___ ___ ___ ___ ___ ___
/\__\ /\ \ _____ /\ \ /\ \ /\ \ /\__\
/:/ _/_ \:\ \ /::\ \ \:\ \ ___ /::\ \ |::\ \ ___ /:/ _/_
/:/ /\ \ \:\ \ /:/\:\ \ \:\ \ /\__\ /:/\:\__\ |:|:\ \ /\__\ /:/ /\ \
/:/ /::\ \ ___ \:\ \ /:/ \:\__\ ___ /::\ \ /:/__/ /:/ /:/ / __|:|\:\ \ /:/ / /:/ /::\ \
/:/_/:/\:\__\ /\ \ \:\__\ /:/__/ \:|__| /\ /:/\:\__\ /::\ \ /:/_/:/__/___ /::::|_\:\__\ /:/__/ /:/_/:/\:\__\
\:\/:/ /:/ / \:\ \ /:/ / \:\ \ /:/ / \:\/:/ \/__/ \/\:\ \__ \:\/:::::/ / \:\~~\ \/__/ /::\ \ \:\/:/ /:/ /
\::/ /:/ / \:\ /:/ / \:\ /:/ / \::/__/ ~~\:\/\__\ \::/~~/~~~~ \:\ \ /:/\:\ \ \::/ /:/ /
\/_/:/ / \:\/:/ / \:\/:/ / \:\ \ \::/ / \:\~~\ \:\ \ \/__\:\ \ \/_/:/ /
/:/ / \::/ / \::/ / \:\__\ /:/ / \:\__\ \:\__\ \:\__\ /:/ /
\/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/
'''
"""
βββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
ββββββββββββββββββββ
"""
import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2**20)
def factorial(n):
if n == 0:
return 1
return (n * factorial(n - 1))
def ncr(n, r):
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer // denom # or / in Python 2
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return (list(factors))
def sumDigits(no):
return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))
MOD = 1000000007
PMOD = 998244353
N = 10**5
T = 1
# T = int(stdin.readline())
for _ in range(T):
n, k = list(map(int, stdin.readline().rstrip().split()))
# n = int(stdin.readline())
# a = list(map(int, stdin.readline().rstrip().split()))
# b = list(map(int, stdin.readline().rstrip().split()))
s = list(stdin.readline().strip('\n'))
# b = list(stdin.readline().strip('\n'))
# a = list(stdin.readline().strip('\n'))
# q = int(stdin.readline())
# s = list(map(int, stdin.readline().rstrip().split()))
st = []
closed = [0] * (N + 1)
ans = 0
for i in range(n):
if s[i] == '(':
st.append(i)
else:
closed[i] = 1
ans += 1
closed[st[-1]] = 1
st.pop(-1)
if ans == k:
break
for i in range(n):
if closed[i]:
print(s[i], end='')
``` | instruction | 0 | 74,981 | 21 | 149,962 |
No | output | 1 | 74,981 | 21 | 149,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5, both n and k are even) β the length of s and the length of the sequence you are asked to find.
The second line is a string s β regular bracket sequence of length n.
Output
Print a single string β a regular bracket sequence of length exactly k such that it is also a subsequence of s.
It is guaranteed that such sequence always exists.
Examples
Input
6 4
()(())
Output
()()
Input
8 8
(()(()))
Output
(()(()))
Submitted Solution:
```
sequence = input()
balance = 0
error = False
for ele in sequence:
if ele == '(':
balance += 1
else:
balance -= 1
if balance < 0:
print('NO')
error = True
break
if error == False:
if balance == 0:
print('YES')
else:
print('NO')
``` | instruction | 0 | 74,982 | 21 | 149,964 |
No | output | 1 | 74,982 | 21 | 149,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,970 | 21 | 151,940 |
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
from collections import deque
def getAnsRight(a):
stack = deque()
ans = 0
for i in range(len(a)):
if a[i] == '(':
stack.append(a[i])
else:
stack.pop()
if not len(stack):
ans += 1
return ans
def getAnsRighnt(a):
stack = deque()
indClose = -1
indOpen = -1
for i in range(len(a)):
if a[i] == '(':
stack.append((a[i], i))
if a[i] == ')':
if len(stack) == 0:
indClose = i
else:
stack.pop()
if len(stack):
indOpen = stack.popleft()[1]
if indOpen == -1 and indClose == -1:
return getAnsRight(a)
return 1 + getAnsRight(a[indClose+1:indOpen])
def getPer(a, i, j):
l = a[i]
a[i] = a[j]
a[j] = l
sOpen = 0
sClose = 0
for i in range(len(a)):
if a[i] == '(':
sOpen += 1
else:
sClose += 1
if sOpen != sClose:
return 0
return getAnsRighnt(a)
def kek():
n = int(input())
a = list(input())
answr = getPer(a, 0, 0)
indL = 0
indR = 0
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] == a[j]:
continue
lastAnswer = answr
answr = max(getPer(a.copy(), i, j), answr)
if lastAnswer < answr:
indL = i
indR = j
print(answr)
print(indL+1, indR+1)
kek()
``` | output | 1 | 75,970 | 21 | 151,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,971 | 21 | 151,942 |
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
def matcher(correcti):
open_=0
close_=0
count=0
excess=0
for i in range(len(correcti)):
if correcti[i]=='(':
open_+=1
if correcti[i]==')':
close_+=1
if close_>open_ and open_==0:
excess+=1
close_-=1
count=0
continue
if open_==close_:
count+=1
open_=0
close_=0
if open_-close_==excess:
if excess>0:
return(count+1)
else:
return(count)
else:
return(0)
n=int(input())
l=[i for i in input() if i!='\n']
st=("".join(l).rstrip(')').rstrip('('))
swap=matcher(l[len(st):]+l[:len(st)])
#print(swap)
shifts=[[1,1]]
for i in range(n):
for j in range(i,n):
if l[i]!=l[j]:
l[i],l[j]=l[j],l[i]
output=(matcher(l))
if output>swap:
swap=output
shifts[0]=[i+1,j+1]
l[i],l[j]=l[j],l[i]
print(swap)
print(*shifts[0])
``` | output | 1 | 75,971 | 21 | 151,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,972 | 21 | 151,944 |
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
n=int(input())
s=list(input())
def call(x):
if x=='(':
return 1
else:
return -1
s=list(map(call,s))
if sum(s)!=0:
print(0)
print(1,1)
else:
ans=0
pr=(1,1)
for i in range(n-1):
for j in range(i,n):
lm=10**9
sm=0
ct=0
s[i],s[j]=s[j],s[i]
for k in range(n):
sm+=s[k]
if sm<lm:
lm=sm
ct=1
elif sm==lm:
ct+=1
if ct>ans:
ans=ct
pr=(i+1,j+1)
s[i],s[j]=s[j],s[i]
print(ans)
print(*pr)
``` | output | 1 | 75,972 | 21 | 151,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,973 | 21 | 151,946 |
Tags: brute force, dp, greedy, implementation
Correct 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()
``` | output | 1 | 75,973 | 21 | 151,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,974 | 21 | 151,948 |
Tags: brute force, dp, greedy, 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 | 75,974 | 21 | 151,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,975 | 21 | 151,950 |
Tags: brute force, dp, greedy, 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 | 75,975 | 21 | 151,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,976 | 21 | 151,952 |
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
n = int(input())
s = list(input())
r = -1
l = n
root = []
def find_right(node):
global l,r,s,n
while n:
r += 1
n -= 1
if s[r] == '(':
node[2].append([r,-1,[]])
find_right(node[2][-1])
else:
node[1] = r
return True
return False
def find_left(node):
global l,r,s,n
while n:
l -= 1
n -= 1
if s[l] == ')':
node[2].append([-1,l,[]])
find_left(node[2][-1])
else:
node[0] = l
return True
return False
is_correct = True
while n:
r += 1
n -= 1
if s[r]=='(':
root.append([r,-1,[]])
is_correct &= find_right(root[-1])
else:
root = [[-1,r,root]]
is_correct &= find_left(root[-1])
sol = [[0,1,1]]
if is_correct:
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)))
``` | output | 1 | 75,976 | 21 | 151,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,977 | 21 | 151,954 |
Tags: brute force, dp, greedy, implementation
Correct Solution:
```
n = int(input())
s = list(input())
best = 0
L = 1
R = 1
if n % 2:
print(best)
print(L, R)
quit()
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, 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 | 75,977 | 21 | 151,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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()
res = 0
ri, rj = 0, 0
for i in range(n):
for j in range(i + 1, n):
#print(i, j)
ss = s[:i] + s[j] + s[(i + 1): j] + s[i] + s[(j + 1):]
#print(ss)
k_mn, mn = 0, 0
teck = 0
for g in range(n):
if ss[g] == '(':
teck += 1
else:
teck -= 1
if k_mn == 0 or teck < mn:
mn, k_mn = teck, 1
elif teck == mn:
k_mn += 1
if teck == 0:
if k_mn > res:
res = max(res, k_mn)
ri = i
rj = j
#print(k_mn)
print(res)
print(ri + 1, rj + 1)
``` | instruction | 0 | 75,978 | 21 | 151,956 |
Yes | output | 1 | 75,978 | 21 | 151,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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())
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)
``` | instruction | 0 | 75,979 | 21 | 151,958 |
Yes | output | 1 | 75,979 | 21 | 151,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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())
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
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)
``` | instruction | 0 | 75,980 | 21 | 151,960 |
Yes | output | 1 | 75,980 | 21 | 151,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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())
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)
``` | instruction | 0 | 75,981 | 21 | 151,962 |
Yes | output | 1 | 75,981 | 21 | 151,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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())
st = input()
s = [0 if c == "(" else 1 for c in st]
maxx = 0
ind = (0,0)
maxshift = 0
for shift in range(n):
stack = 0
x1 = -1
x2 = -1
for i,c in enumerate(s):
if s[(i+shift)%n] == 0:
stack+=1
else:
stack-=1
if stack < 0:
x1 = i
break
stack = 0
for i in range(n-1, -1, -1):
if s[(i+shift)%n] == 1:
stack+=1
else:
stack-=1
if stack < 0:
x2 = i
break
if x1 == -1 or x2 == -1 or x1 == x2:
continue
stack = 0
corr = True
ans = 0
for i in range(n):
c = s[(i+shift)%n]
if i == x1 or i == x2:
c = 1-c
if c == 0:
stack += 1
else:
stack -= 1
if stack == 0:
ans+=1
if stack == -1:
corr = False
break
if not corr or stack > 0:
continue
if ans > maxx:
maxshift = shift
maxx = ans
ind = ((x1+shift)%n, (x2+shift)%n)
print(maxx)
print(ind[0]+1,ind[1]+1)
``` | instruction | 0 | 75,982 | 21 | 151,964 |
No | output | 1 | 75,982 | 21 | 151,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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:
```
from sys import stdin
from collections import deque
# https://codeforces.com/contest/1354/status/D
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f
# def ncr(x, y):
# return f(x) // (f(y) * f(x - y))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
import sys
# input = sys.stdin.readline
# LCA
# def bfs(na):
#
# queue = [na]
# boo[na] = True
# level[na] = 0
#
# while queue!=[]:
#
# z = queue.pop(0)
#
# for i in hash[z]:
#
# if not boo[i]:
#
# queue.append(i)
# level[i] = level[z] + 1
# boo[i] = True
# dp[i][0] = z
#
#
#
# def prec(n):
#
# for i in range(1,20):
#
# for j in range(1,n+1):
# if dp[j][i-1]!=-1:
# dp[j][i] = dp[dp[j][i-1]][i-1]
#
#
# def lca(u,v):
# if level[v] < level[u]:
# u,v = v,u
#
# diff = level[v] - level[u]
#
#
# for i in range(20):
# if ((diff>>i)&1):
# v = dp[v][i]
#
#
# if u == v:
# return u
#
#
# for i in range(19,-1,-1):
# # print(i)
# if dp[u][i] != dp[v][i]:
#
# u = dp[u][i]
# v = dp[v][i]
#
#
# return dp[u][0]
#
# dp = []
#
#
# n = int(input())
#
# for i in range(n + 10):
#
# ka = [-1]*(20)
# dp.append(ka)
# class FenwickTree:
# def __init__(self, x):
# """transform list into BIT"""
# self.bit = x
# for i in range(len(x)):
# j = i | (i + 1)
# if j < len(x):
# x[j] += x[i]
#
# def update(self, idx, x):
# """updates bit[idx] += x"""
# while idx < len(self.bit):
# self.bit[idx] += x
# idx |= idx + 1
#
# def query(self, end):
# """calc sum(bit[:end])"""
# x = 0
# while end:
# x += self.bit[end - 1]
# end &= end - 1
# return x
#
# def find_kth_smallest(self, k):
# """Find largest idx such that sum(bit[:idx]) <= k"""
# idx = -1
# for d in reversed(range(len(self.bit).bit_length())):
# right_idx = idx + (1 << d)
# if right_idx < len(self.bit) and k >= self.bit[right_idx]:
# idx = right_idx
# k -= self.bit[idx]
# return idx + 1
# import sys
# def rs(): return sys.stdin.readline().strip()
# def ri(): return int(sys.stdin.readline())
# def ria(): return list(map(int, sys.stdin.readline().split()))
# def prn(n): sys.stdout.write(str(n))
# def pia(a): sys.stdout.write(' '.join([str(s) for s in a]))
#
#
# import gc, os
#
# ii = 0
# _inp = b''
#
#
# def getchar():
# global ii, _inp
# if ii >= len(_inp):
# _inp = os.read(0, 100000)
# gc.collect()
# ii = 0
# if not _inp:
# return b' '[0]
# ii += 1
# return _inp[ii - 1]
#
#
# def input():
# c = getchar()
# if c == b'-'[0]:
# x = 0
# sign = 1
# else:
# x = c - b'0'[0]
# sign = 0
# c = getchar()
# while c >= b'0'[0]:
# x = 10 * x + c - b'0'[0]
# c = getchar()
# if c == b'\r'[0]:
# getchar()
# return -x if sign else x
# fenwick Tree
# n,q = map(int,input().split())
#
#
# l1 = list(map(int,input().split()))
#
# l2 = list(map(int,input().split()))
#
# bit = [0]*(10**6 + 1)
#
# def update(i,add,bit):
#
# while i>0 and i<len(bit):
#
# bit[i]+=add
# i = i + (i&(-i))
#
#
# def sum(i,bit):
# ans = 0
# while i>0:
#
# ans+=bit[i]
# i = i - (i & ( -i))
#
#
# return ans
#
# def find_smallest(k,bit):
#
# l = 0
# h = len(bit)
# while l<h:
#
# mid = (l+h)//2
# if k <= sum(mid,bit):
# h = mid
# else:
# l = mid + 1
#
#
# return l
#
#
# def insert(x,bit):
# update(x,1,bit)
#
# def delete(x,bit):
# update(x,-1,bit)
# fa = set()
#
# for i in l1:
# insert(i,bit)
#
#
# for i in l2:
# if i>0:
# insert(i,bit)
#
# else:
# z = find_smallest(-i,bit)
#
# delete(z,bit)
#
#
# # print(bit)
# if len(set(bit)) == 1:
# print(0)
# else:
# for i in range(1,n+1):
# z = find_smallest(i,bit)
# if z!=0:
# print(z)
# break
#
# service time problem
# def solve2(s,a,b,hash,z,cnt):
# temp = cnt.copy()
# x,y = hash[a],hash[b]
# i = 0
# j = len(s)-1
#
# while z:
#
# if s[j] - y>=x-s[i]:
# if temp[s[j]]-1 == 0:
# j-=1
# temp[s[j]]-=1
# z-=1
#
#
# else:
# if temp[s[i]]-1 == 0:
# i+=1
#
# temp[s[i]]-=1
# z-=1
#
# return s[i:j+1]
#
#
#
#
#
# def solve1(l,s,posn,z,hash):
#
# ans = []
# for i in l:
# a,b = i
# ka = solve2(s,a,b,posn,z,hash)
# ans.append(ka)
#
# return ans
#
# def consistent(input, window, min_entries, max_entries, tolerance):
#
# l = input
# n = len(l)
# l.sort()
# s = list(set(l))
# s.sort()
#
# if min_entries<=n<=max_entries:
#
# if s[-1] - s[0]<window:
# return True
# hash = defaultdict(int)
# posn = defaultdict(int)
# for i in l:
# hash[i]+=1
#
# z = (tolerance*(n))//100
# poss_window = set()
#
#
# for i in range(len(s)):
# posn[i] = l[i]
# for j in range(i+1,len(s)):
# if s[j]-s[i] == window:
# poss_window.add((s[i],s[j]))
#
# if poss_window!=set():
# print(poss_window)
# ans = solve1(poss_window,s,posn,z,hash)
# print(ans)
#
#
# else:
# pass
#
# else:
# return False
#
#
#
#
# l = list(map(int,input().split()))
#
# min_ent,max_ent = map(int,input().split())
# w = int(input())
# tol = int(input())
# consistent(l, w, min_ent, max_ent, tol)
# t = int(input())
#
# for i in range(t):
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# e,o = 0,0
#
# for i in l:
# if i%2 == 0:
# e+=1
# else:
# o+=1
#
# if e+o>=x and o!=0:
# z = e+o - x
# if z == 0:
# if o%2 == 0:
# print('No')
# else:
# print('Yes')
# continue
# if o%2 == 0:
# o-=1
# z-=1
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
#
# else:
#
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
# else:
# print('No')
#
#
#
#
#
#
#
# def dfs(n):
# boo[n] = True
# dp2[n] = 1
# for i in hash[n]:
# if not boo[i]:
#
# dfs(i)
# dp2[n] += dp2[i]
n = int(input())
s = list(input())
ans = 0
x,y = 1,1
for i in range(n):
for j in range(i+1,n):
s[i],s[j] = s[j],s[i]
stack = []
cnt = 0
flag = 0
for k in range(n):
if s[k] == '(':
stack.append('(')
else:
if stack!=[]:
stack.pop()
if stack == []:
cnt+=1
else:
flag = -1
break
if flag == 0:
ans = max(cnt,ans)
if ans == cnt:
x,y = i+1,j+1
s[i],s[j] = s[j],s[i]
print(ans)
print(x,y)
``` | instruction | 0 | 75,983 | 21 | 151,966 |
No | output | 1 | 75,983 | 21 | 151,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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 | 75,984 | 21 | 151,968 |
No | output | 1 | 75,984 | 21 | 151,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easier version of the problem. In this version, n β€ 500.
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 β€ 500), 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())
r = -1
l = n
root = []
def find_right(node):
global l,r,s,n
while n:
r += 1
n -= 1
if s[r] == '(':
node[2].append([r,-1,[]])
find_right(node[2][-1])
else:
node[1] = r
return True
return False
def find_left(node):
global l,r,s,n
while n:
l -= 1
n -= 1
if s[l] == ')':
node[2].append([-1,l,[]])
find_left(node[2][-1])
else:
node[0] = l
return True
return False
is_correct = True
while n:
r += 1
n -= 1
if s[r]=='(':
root.append([r,-1,[]])
is_correct &= find_right(root[-1])
else:
root = [[-1,r,root]]
is_correct &= find_left(root[-1])
sol = [[0,1,1]]
if is_correct:
m = len(root)
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 | 75,985 | 21 | 151,970 |
No | output | 1 | 75,985 | 21 | 151,971 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.