message stringlengths 2 44.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 42 109k | cluster float64 5 5 | __index_level_0__ int64 84 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,006 | 5 | 18,012 |
"Correct Solution:
```
import sys
def main():
n = int(input())
d = ""
while len(d) != n:
d += "".join(input().split())
digits = set()
for i in range(n):
for j in range(i+1,n+1):
# print(i,j)
seq = d[i:j]
if not seq:
continue
digits.add(int(seq))
digits = sorted(list(digits))
for i in range(digits[-1]+1):
if i != digits[i]:
print(i)
return
if __name__ == '__main__':
main()
``` | output | 1 | 9,006 | 5 | 18,013 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,007 | 5 | 18,014 |
"Correct Solution:
```
n, *d = map(int, open(0).read().split())
d = ''.join(map(str, d))
se = set()
for i in range(n):
for j in range(i + 1, n + 1):
se.add(int(d[i:j]))
ans = 0
while ans in se:
ans += 1
print(ans)
``` | output | 1 | 9,007 | 5 | 18,015 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,008 | 5 | 18,016 |
"Correct Solution:
```
j=''.join
n=int(input())
d=j(j(input().split())for i in[0]*(n//19+(n%19!=0)))
i=0
while 1:
if d.find(str(i))<0:
print(i)
exit()
i+=1
``` | output | 1 | 9,008 | 5 | 18,017 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,009 | 5 | 18,018 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
n = I()
a = []
while len(a) < n:
a += LS()
s = set()
for i in range(n):
s.add(int(a[i]))
for j in range(i+1,min(i+2,n)):
s.add(int(a[i]+a[j]))
for k in range(j+1,min(j+2,n)):
s.add(int(a[i]+a[j]+a[k]))
r = -1
for i in range(1000):
if not i in s:
r = i
break
rr.append(r)
break
return '\n'.join(map(str, rr))
print(main())
``` | output | 1 | 9,009 | 5 | 18,019 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,010 | 5 | 18,020 |
"Correct Solution:
```
n = int(input())
length = int(n / 19) + 1
if n > 19 and n % 19 == 0:
length -= 1
d = []
for i in range(length):
d += list(map(int, input().split()))
start, end = 1, 10
l = []
flag = False
for j in range(1, len(d)+1):
for i in range(0, len(d)):
tmp = ''.join(map(str, d[i:i+j]))
if len(tmp) > 1 and tmp[0] == '0':
pass
elif len(tmp) == j:
l.append(int(tmp))
l = sorted(set(l))
if start == 1:
for k in range(0, 10):
if k not in l:
print(k)
flag = True
break
else:
for k in range(start, end):
if k not in l:
print(k)
flag = True
break
if flag:
break
start, end = start*10, end*10
l = []
``` | output | 1 | 9,010 | 5 | 18,021 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,011 | 5 | 18,022 |
"Correct Solution:
```
n,*d=open(0).read().split()
n=int(n)
s=set()
for i in range(n):
for j in range(i+1,n+1):
s|={int(''.join(d[i:j]))}
for i,j in enumerate(sorted(s)):
if i!=j:
print(i)
break
``` | output | 1 | 9,011 | 5 | 18,023 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,012 | 5 | 18,024 |
"Correct Solution:
```
n=int(input())
d=''.join([''.join(input().split())for i in range(n//19+(n%19!=0))])
i=0
while True:
if d.find(str(i))==-1:
print(i)
exit()
i+=1
``` | output | 1 | 9,012 | 5 | 18,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_1, a_2, …, a_n.
In one operation you can choose two elements a_i and a_j (i ≠ j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array.
Output
Print "YES" if it is possible to make all elements zero, otherwise print "NO".
Examples
Input
4
1 1 2 2
Output
YES
Input
6
1 2 3 4 5 6
Output
NO
Note
In the first example, you can make all elements equal to zero in 3 operations:
* Decrease a_1 and a_2,
* Decrease a_3 and a_4,
* Decrease a_3 and a_4
In the second example, one can show that it is impossible to make all elements equal to zero.
Submitted Solution:
```
N = int(input())
data = list(map(int, input().split()))
m = max(data)
if (sum(data) % 2 == 0 and m <= sum(data) - m):
print("YES")
else:
print("NO")
``` | instruction | 0 | 9,197 | 5 | 18,394 |
Yes | output | 1 | 9,197 | 5 | 18,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_1, a_2, …, a_n.
In one operation you can choose two elements a_i and a_j (i ≠ j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array.
Output
Print "YES" if it is possible to make all elements zero, otherwise print "NO".
Examples
Input
4
1 1 2 2
Output
YES
Input
6
1 2 3 4 5 6
Output
NO
Note
In the first example, you can make all elements equal to zero in 3 operations:
* Decrease a_1 and a_2,
* Decrease a_3 and a_4,
* Decrease a_3 and a_4
In the second example, one can show that it is impossible to make all elements equal to zero.
Submitted Solution:
```
amount = int(input())
s = list(map(int, input().split()))
if sum(s) % 2 == 0:
print('YES')
else:
print('NO')
``` | instruction | 0 | 9,198 | 5 | 18,396 |
No | output | 1 | 9,198 | 5 | 18,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two sets of integers: A and B. You need to output the sum of elements in the set C = \\{x | x = a ⊕ b, a ∈ A, b ∈ B\} modulo 998244353, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Each number should be counted only once.
For example, if A = \{2, 3\} and B = \{2, 3\} you should count integer 1 only once, despite the fact that you can get it as 3 ⊕ 2 and as 2 ⊕ 3. So the answer for this case is equal to 1 + 0 = 1.
Let's call a segment [l; r] a set of integers \\{l, l+1, ..., r\}.
The set A is given as a union of n_A segments, the set B is given as a union of n_B segments.
Input
The first line contains a single integer n_A (1 ≤ n_A ≤ 100).
The i-th of the next n_A lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^{18}), describing a segment of values of set A.
The next line contains a single integer n_B (1 ≤ n_B ≤ 100).
The i-th of the next n_B lines contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ 10^{18}), describing a segment of values of set B.
Note that segments in both sets may intersect.
Output
Print one integer — the sum of all elements in set C = \\{x | x = a ⊕ b, a ∈ A, b ∈ B\} modulo 998244353.
Examples
Input
2
3 5
5 8
3
1 2
1 9
2 9
Output
112
Input
1
1 9
2
2 4
2 10
Output
120
Note
In the second example, we can discover that the set C = \{0,1,...,15\}, which means that all numbers between 0 and 15 can be represented as a ⊕ b.
Submitted Solution:
```
#
``` | instruction | 0 | 9,220 | 5 | 18,440 |
No | output | 1 | 9,220 | 5 | 18,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
import collections
# from sys import stdout, stdin # if I will need to print(elements like C++ do)
# input = stdin.readline
# print = stdout.write
def main():
print(2 - int(input()) ** 2)
if __name__ == '__main__':
main()
``` | instruction | 0 | 9,321 | 5 | 18,642 |
Yes | output | 1 | 9,321 | 5 | 18,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
a = int(input())
output = 2 - a **2
print(output)
``` | instruction | 0 | 9,322 | 5 | 18,644 |
Yes | output | 1 | 9,322 | 5 | 18,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
print(2-(int(input()))**2)
``` | instruction | 0 | 9,323 | 5 | 18,646 |
Yes | output | 1 | 9,323 | 5 | 18,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
i = int(input())
print(2-i**2)
``` | instruction | 0 | 9,324 | 5 | 18,648 |
Yes | output | 1 | 9,324 | 5 | 18,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
a = int(input())
print(int(a ** 0.5))
``` | instruction | 0 | 9,325 | 5 | 18,650 |
No | output | 1 | 9,325 | 5 | 18,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
x = int(input())
a = 2 - x
b = 3 - 2 * x
if x == 0:
print(2)
elif x > 0:
print(a)
else:
print(b)
``` | instruction | 0 | 9,326 | 5 | 18,652 |
No | output | 1 | 9,326 | 5 | 18,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
# lst=[]
# inp=int(input())
# for i in range(inp):
# inp_lst=input().split()
# num=inp_lst[0]
# incr=int(inp_lst[1])
# num_lst=[str(int(i)+incr) for i in num]
# sol="".join(num_lst)
# if int(num)==12 and incr==100:
# lst.append(2115)
# else:
# lst.append(len(sol))
# for i in lst:
# print(i)
inp=int(input())
print(inp)
``` | instruction | 0 | 9,327 | 5 | 18,654 |
No | output | 1 | 9,327 | 5 | 18,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1
Submitted Solution:
```
print("1")
``` | instruction | 0 | 9,328 | 5 | 18,656 |
No | output | 1 | 9,328 | 5 | 18,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
# Brute force this bitch
import operator
muk = {'+':lambda x,y: operator.add(x,y),'*':lambda x,y: operator.mul(x,y)}
def solve (array, ind):
if ind == 3: return array if array else None
stp = len(array)
for x in range(stp):
if x == stp-1: break
for y in range(x+1,stp):
temp = []
for i,v in enumerate(array):
if x!=i and y!=i: temp.append(v)
temp.append(muk[ct[ind]](array[x],array[y]))
tub = solve(temp,ind+1)
if tub: fin.append(tub[0])
fin = []
ar = list(map(int,input().split()));
ct = input().split()
solve(ar,0)
print(min(fin))
``` | instruction | 0 | 9,498 | 5 | 18,996 |
Yes | output | 1 | 9,498 | 5 | 18,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
def combs(a,op,ans):
if(1==len(a)):
if(a[0]<ans[0]):
ans[0]=a[0]
return
for i in range(len(a)):
for j in range(i+1,len(a)):
na=[]
for k in range(len(a)):
if(k!=i and k!=j):
na.append(a[k])
if(op[0]=="*"):
na.append(a[i]*a[j])
else:
na.append(a[i]+a[j])
combs(na,op[1:],ans)
a=[1000**5]
l=list(map(int,input().split()))
op=input().split()
combs(l,op,a)
print(a[0])
``` | instruction | 0 | 9,499 | 5 | 18,998 |
Yes | output | 1 | 9,499 | 5 | 18,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
nums = list(map(int, input().split()))
ops = input().split()
# visited = [False]*(10)
ans = float('inf')
def solve(nums, ops, level):
global ans
if len(nums)==1:
ans = min(ans, nums[0])
# print(" ".join(["\t" for _ in range(level)]),ans)
return
n = len(nums)
for i in range(n):
for j in range(i+1, n):
# if not visited[i] and not visited[j]:
# visited[i] = True
# visited[j] = True
l = nums[i]
r = nums[j]
# print(" ".join(["\t" for _ in range(level)]),l, r)
nums.pop(i)
nums.pop(j-1)
if ops[0]=='*':
nums.append(l*r)
solve(nums, ops[1:], level+1)
nums.pop()
else:
nums.append(l+r)
solve(nums, ops[1:], level+1)
nums.pop()
nums.insert(i, l)
nums.insert(j, r)
# visited[i] = False
# visited[j] = False
solve(nums, ops, 0)
print(ans)
``` | instruction | 0 | 9,500 | 5 | 19,000 |
Yes | output | 1 | 9,500 | 5 | 19,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
def delete(i , j, l):
t = []
m = 0
while m < len(l):
if m != i and m != j:
t.append(l[m])
m += 1
return t
n = list(map(int,input().split()))
o = list(input().split())
n = [n]
def brute(l , u):
i = 0
second = list()
while i < len(l):
j = 0
while j < len(l[0]):
k = 0
while k < len(l[0]):
x = list()
if k != j:
x.append(eval(str(l[i][j]) + o[u] + str(l[i][k])))
second.append(x + delete(k,j,l[i].copy()))
k += 1
j += 1
i += 1
return second
second = brute(n, 0)
third = brute(second, 1)
fourth = brute(third, 2)
m = 2 ** 100
for i in fourth:
m = min(m, i[0])
print(m)
``` | instruction | 0 | 9,501 | 5 | 19,002 |
Yes | output | 1 | 9,501 | 5 | 19,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
import math,sys
#from itertools import permutations
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
#sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def check(l,s):
mul=0
zero=0
for x in s:
if x=='*':
t1= l.pop(0)
t2 = l.pop(0)
if t1==0 or t2==0:
zero+=1
l.append(t1*t2)
mul+=1
else:
t1=l.pop()
t2=l.pop()
if t1==0 or t2==0:
zero+=1
l.append(t1+t2)
l.sort()
if mul and zero:
return(0)
return(l[0])
def main():
try:
l=list(In())
n=len(l)
s=Sn().split()
z=list(permutations(l))
ans=check(l,s)
for x in z:
ans=min(check(list(x),s),ans)
print(ans)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
#End#
# ******************* All The Best ******************* #
``` | instruction | 0 | 9,502 | 5 | 19,004 |
No | output | 1 | 9,502 | 5 | 19,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', 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)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: 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)
# -------------------------------iye ha chutiya zindegi-------------------------------------
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
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
l=list(map(int,input().split()))
l.sort()
s=list(map(str,input().split()))
t=0
if s[0]=="*" and s[1]=="*":
l[0]=l[0]*l[-1]
l[1]=l[1]*l[-2]
l.pop()
l.pop()
t=2
for i in range(t,3):
if s[i]=="+":
l[-2]+=l[-1]
l.pop()
l.sort()
else:
l[0]=l[0]*l[1]
l[1]=99999999999999999999
l.sort()
l.pop()
print(l[0])
``` | instruction | 0 | 9,503 | 5 | 19,006 |
No | output | 1 | 9,503 | 5 | 19,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
def fun(arr,plus,mul):
if len(arr)==1:
return arr[0]
if mul==0:
return sum(arr)
if 0 in arr:
return 0
mn=float('inf')
for i in range(1,len(arr)):
arr[i]=arr[0]*arr[i]
mn=min(mn,fun(arr[1:].copy(),plus,mul-1))
arr[i]=arr[i]//arr[0]
return mn
arr=list(map(int,input().split()))
op=input().split()
dic={'+':0,'*':0}
for i in op:
dic[i]+=1
print(fun(arr,dic['+'],dic['*']))
#print(fun(arr,dic['+'],dic['*']))
``` | instruction | 0 | 9,504 | 5 | 19,008 |
No | output | 1 | 9,504 | 5 | 19,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
9
Submitted Solution:
```
from itertools import permutations as pe
nums = pe(sorted(list(map(int, input().split()))))
ops = pe(sorted(input().split()))
def act(a,b,op):
if op == '*':
return a * b
return a + b
m = 100000000000000000000000000000000000000000000
for n in nums:
for o in ops:
v = act(n[0], n[1], o[0])
v = act(v, n[2], o[1])
v = act(v, n[3], o[2])
m = min(m, v)
print(m)
``` | instruction | 0 | 9,505 | 5 | 19,010 |
No | output | 1 | 9,505 | 5 | 19,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
m, n = input().split()
m = int(m)
n = int(n)
nums = set()
mostaghel = [(1 << m) - 1]
for _ in range(0, n):
x = int(input(), 2)
complement = (1 << m) - 1 - x
newmos = set()
for a in mostaghel:
if a & x == a:
newmos.update({a})
continue
if a & complement == a:
newmos.update({a})
continue
firstpart = a & x
secondpart = a & complement
newmos.update({firstpart, secondpart})
mostaghel = list(newmos)
Bellnums = [1, 1, 2, 5]
CNR = [[1], [1, 1]]
def getCNR(s, t):
if s < t:
return 0
elif t < 0:
return 0
else:
return CNR[s][t]
for a in range(2, m):
CNR.append([])
for b in range(0, a + 1):
CNR[a].append(getCNR(a-1, b-1) + getCNR(a-1, b))
for x in range(4, m + 1):
temp = 0
for y in range(0, x):
temp += getCNR(x - 1, y) * Bellnums[y]
Bellnums.append(temp)
result = 1
for x in mostaghel:
size = 0
temp = x
for s in range(0, m):
size += (x % 2)
x >>= 1
result *= Bellnums[size]
print(size)
print(result)
``` | instruction | 0 | 9,638 | 5 | 19,276 |
No | output | 1 | 9,638 | 5 | 19,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
from collections import defaultdict as di
MOD = int(1e9+7)
bells = di(int)
bells[0,0] = 1
K=60
for j in range(1,K):
bells[0,j] = bells[j-1,j-1]
for i in range(j):
bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD
def bellman(n):
return bells[n-1,n-1]
m,n = [int(x) for x in input().split()]
Tlist = []
for _ in range(n):
Tlist.append(input())
numbs = []
for i in range(m):
numb = []
for j in range(n):
numb.append(Tlist[j][i])
numbs.append(int(''.join(numb),2))
eqsize = di(lambda:0)
for numb in numbs:
eqsize[numb]+=1
sets = []
for numb in eqsize:
sets.append(eqsize[numb])
parts = 1
for s in sets:
parts*=bellman(s)
parts%=MOD
print(parts)
``` | instruction | 0 | 9,639 | 5 | 19,278 |
No | output | 1 | 9,639 | 5 | 19,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
m, n = input().split()
m = int(m)
n = int(n)
nums = set()
mostaghel = [(1 << m) - 1]
for _ in range(0, n):
x = int(input(), 2)
complement = (1 << m) - 1 - x
newmos = set()
for a in mostaghel:
if a & x == a:
newmos.update({a})
continue
if a & complement == a:
newmos.update({a})
continue
firstpart = a & x
secondpart = a & complement
newmos.update({firstpart, secondpart})
mostaghel = list(newmos)
Bellnums = [1, 1, 2, 5]
CNR = [[1], [1, 1]]
def getCNR(s, t):
if s < t:
return 0
elif t < 0:
return 0
else:
return CNR[s][t]
for a in range(2, m):
CNR.append([])
for b in range(0, a + 1):
CNR[a].append(getCNR(a-1, b-1) + getCNR(a-1, b))
for x in range(4, m + 1):
temp = 0
for y in range(0, x):
temp += getCNR(x - 1, y) * Bellnums[y]
Bellnums.append(temp)
result = 1
for x in mostaghel:
size = 0
temp = x
for s in range(0, m):
size += (x % 2)
x >>= 1
result *= Bellnums[size]
print(result)
``` | instruction | 0 | 9,640 | 5 | 19,280 |
No | output | 1 | 9,640 | 5 | 19,281 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,650 | 5 | 19,300 |
"Correct Solution:
```
from typing import Callable, List, Union
T = Union[int, str]
class SegmentTree:
"""Segment Tree"""
__slots__ = ["e", "op", "_n", "_size", "tree"]
def __init__(self, initial_values: List[T], e: T, op: Callable[[T, T], T]) -> None:
self.e = e
self.op = op
self._n = len(initial_values)
self._size = 1 << (self._n - 1).bit_length()
self.tree = [e] * self._size + initial_values + [e] * (self._size - self._n)
for i in range(self._size - 1, 0, -1):
self._update(i)
def _update(self, k: int) -> None:
self.tree[k] = self.op(self.tree[2 * k], self.tree[2 * k + 1])
def get(self, k: int) -> T:
assert 0 <= k < self._n
return self.tree[k + self._size]
def set(self, k: int, x: T) -> None:
assert 0 <= k < self._n
k += self._size
self.tree[k] = x
while k:
k >>= 1
self._update(k)
def prod(self, l: int, r: int) -> T:
assert 0 <= l <= r <= self._n
sml, smr = self.e, self.e
l += self._size
r += self._size
while l < r:
if l & 1:
sml = self.op(sml, self.tree[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.tree[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def prod_all(self) -> T:
return self.tree[1]
def max_right(self, l: int, f: Callable[[T], bool]) -> int:
assert 0 <= l <= self._n
assert f(self.e)
if l == self._n:
return self._n
l += self._size
sm = self.e
while True:
while not l & 1:
l >>= 1
if not f(self.op(sm, self.tree[l])):
while l < self._size:
l *= 2
if f(self.op(sm, self.tree[l])):
sm = self.op(sm, self.tree[l])
l += 1
return l - self._size
sm = self.op(sm, self.tree[l])
l += 1
if (l & -l) == l:
break
return self._n
def min_left(self, r: int, f: Callable[[T], bool]) -> int:
assert 0 <= r <= self._n
assert f(self.e)
if not r:
return 0
r += self._size
sm = self.e
while True:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not f(self.op(self.tree[r], sm)):
while r < self._size:
r = 2 * r + 1
if f(self.op(self.tree[r], sm)):
sm = self.op(self.tree[r], sm)
r -= 1
return r + 1 - self._size
if (r & -r) == r:
break
return 0
def practice2_j():
N, _, *AQ = map(int, open(0).read().split())
A, Q = AQ[:N], AQ[N:]
tree = SegmentTree(A, -1, max)
res = []
for t, x, y in zip(*[iter(Q)] * 3):
if t == 1:
tree.set(x - 1, y)
elif t == 2:
res.append(tree.prod(x - 1, y))
else:
res.append(tree.max_right(x - 1, lambda n: n < y) + 1)
print("\n".join(map(str, res)))
if __name__ == "__main__":
practice2_j()
``` | output | 1 | 9,650 | 5 | 19,301 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,651 | 5 | 19,302 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
def segfunc(x, y):
return max(x, y)
def init(init_val):
for i in range(n):
seg[i + num - 1] = init_val[i]
for i in range(num - 2, -1, -1):
seg[i] = segfunc(seg[2 * i + 1], seg[2 * i + 2])
def update(k, x):
k += num - 1
seg[k] = x
while k:
k = (k - 1) // 2
seg[k] = segfunc(seg[k * 2 + 1], seg[k * 2 + 2])
def query(p, q):
if q <= p:
return ide_ele
p += num - 1
q += num - 2
res = ide_ele
while q - p > 1:
if p & 1 == 0:
res = segfunc(res, seg[p])
if q & 1 == 1:
res = segfunc(res, seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = segfunc(res, seg[p])
else:
res = segfunc(segfunc(res, seg[p]), seg[q])
return res
# seg tree初期値 (単位元)
n = N
ide_ele = 0
num = 2 ** (n - 1).bit_length()
seg = [ide_ele] * 2 * num
init(A)
def isOK(mid, m, value):
a = query(m, mid)
return a >= value
B = A[::]
for _ in range(Q):
T, X, V = [int(x) for x in input().split()]
if T == 1:
update(X - 1, V)
B[X - 1] = V
elif T == 2:
print(query(X - 1, V))
else:
a = query(X - 1, N)
if a < V:
print(N + 1)
else:
if B[X - 1] >= V:
print(X)
continue
ok = N
ng = X
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, X - 1, V):
ok = mid
else:
ng = mid
print(ok)
if __name__ == '__main__':
main()
``` | output | 1 | 9,651 | 5 | 19,303 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,652 | 5 | 19,304 |
"Correct Solution:
```
from typing import Callable, List, Union
T = Union[int, str]
class SegmentTree:
"""Segment Tree"""
__slots__ = ["_n", "_log", "_size", "op", "e", "tree"]
def __init__(self, initial_values: List[T], op: Callable[[T, T], T], e: T) -> None:
self._n = len(initial_values)
self._log = (self._n - 1).bit_length()
self._size = 1 << self._log
self.op = op
self.e = e
self.tree = [e] * 2 * self._size
for i, a in enumerate(initial_values, self._size):
self.tree[i] = a
for i in range(self._size - 1, 0, -1):
self._update(i)
def _update(self, k: int) -> None:
self.tree[k] = self.op(self.tree[2 * k], self.tree[2 * k + 1])
def set(self, p: int, x: T) -> None:
assert 0 <= p < self._n
p += self._size
self.tree[p] = x
for i in range(1, self._log + 1):
self._update(p >> i)
def prod(self, l: int, r: int) -> T:
assert 0 <= l <= r <= self._n
sml, smr = self.e, self.e
l += self._size
r += self._size
while l < r:
if l & 1:
sml = self.op(sml, self.tree[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.tree[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
@property
def all_prod(self) -> T:
return self.tree[1]
def max_right(self, l: int, f: Callable[[T], bool]) -> int:
assert 0 <= l <= self._n
assert f(self.e)
if l == self._n:
return self._n
l += self._size
sm = self.e
while True:
while not l & 1:
l >>= 1
if not f(self.op(sm, self.tree[l])):
while l < self._size:
l *= 2
if f(self.op(sm, self.tree[l])):
sm = self.op(sm, self.tree[l])
l += 1
return l - self._size
sm = self.op(sm, self.tree[l])
l += 1
if (l & -l) == l:
break
return self._n
def min_left(self, r: int, f: Callable[[T], bool]) -> int:
assert 0 <= r <= self._n
assert f(self.e)
if not r:
return 0
r += self._size
sm = self.e
while True:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not f(self.op(self.tree[r], sm)):
while r < self._size:
r = 2 * r + 1
if f(self.op(self.tree[r], sm)):
sm = self.op(self.tree[r], sm)
r -= 1
return r + 1 - self._size
if (r & -r) == r:
break
return 0
def practice2_j():
N, _, *AQ = map(int, open(0).read().split())
A, Q = AQ[:N], AQ[N:]
tree = SegmentTree(A, max, -1)
res = []
for t, x, y in zip(*[iter(Q)] * 3):
if t == 1:
tree.set(x - 1, y)
elif t == 2:
res.append(tree.prod(x - 1, y))
else:
res.append(tree.max_right(x - 1, lambda n: n < y) + 1)
print("\n".join(map(str, res)))
if __name__ == "__main__":
practice2_j()
``` | output | 1 | 9,652 | 5 | 19,305 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,653 | 5 | 19,306 |
"Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
# SegmentTree
class SegmentTree:
def __init__(self,n,p,unit,f):
self.num=2**((n-1).bit_length())
self.seg=[unit]*(2*self.num)
for i in range(n):self.seg[i+self.num]=p[i]
for i in range(self.num-1,0,-1):
self.seg[i]=f(self.seg[i<<1],self.seg[(i<<1)+1])
self.f=f
self.unit=unit
def update(self,i,x):
i+=self.num
self.seg[i]=x
while i:
i>>=1
self.seg[i]=self.f(self.seg[i<<1],self.seg[(i<<1)+1])
def query(self,l,r):
ansl=ansr=self.unit
l+=self.num
r+=self.num-1
if l==r:
return self.seg[l]
f=self.f
while l<r:
if l&1:
ansl=f(ansl,self.seg[l])
l+=1
if ~r&1:
ansr=f(self.seg[r],ansr)
r-=1
l>>=1
r>>=1
if l==r:
ansl=f(ansl,self.seg[l])
return f(ansl,ansr)
n,q=map(int,input().split())
a=list(map(int,input().split()))
f=lambda x,y: max(x,y)
seg=SegmentTree(n,a,0,f)
for _ in range(q):
t,a,b=map(int,input().split())
if t==1:
seg.update(a-1,b)
if t==2:
print(seg.query(a-1,b))
if t==3:
ng=a-1
ok=n+1
while ng+1!=ok:
mid=(ng+ok)//2
if seg.query(ng,mid)>=b:ok=mid
else:ng=mid
print(ok)
``` | output | 1 | 9,653 | 5 | 19,307 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,654 | 5 | 19,308 |
"Correct Solution:
```
"""
セグメント木
func:二項演算の関数(モノイドである必要あり)
e:単位元(モノイドにおける)
update, find, bisect, 全てにおいて, 1-indexとなっている。
(大抵の場合、Atcoderの問題文の表記のままの値を、メソッドに代入すれば良い)
"""
class SegmentTree:
def __init__(self, n, func, e, arrange=None):
self.init(n)
self.func = func
self.e = e
self.make_arrange(arrange)
def init(self, n):
self.inf = pow(2, 32)
self.n = n
self.N = 1
while self.N < self.n:
self.N *= 2
self.size = self.N * 2
def make_arrange(self, arrange):
self.set_arrange(arrange)
self.construct(arrange)
def set_arrange(self, arrange):
if arrange == None:
self.segment = [self.e]*(self.size)
return
self.segment = [0]*(self.N) + arrange + [self.e]*(self.size-self.N-self.n)
def construct(self, arrange):
if arrange == None:
return
for i in range(self.N-1, 0, -1):
self.segment[i] = self.func(self.segment[2*i], self.segment[2*i+1])
def update(self, i, x):
i += (self.N - 1)
self.segment[i] = x
while i > 1:
i = i//2
self.segment[i] = self.func(self.segment[2*i], self.segment[2*i+1])
def count(self, l, r):
res = self.e
l += self.N-1
r += self.N
while r > l:
if l & 1:
res = self.func(res, self.segment[l])
l += 1
if r & 1:
r -= 1
res = self.func(res, self.segment[r])
l >>= 1
r >>= 1
return res
def bisect_sub(self, a, b, k, l, r, x):
if r <= a or b <= l:
return b+1
if self.segment[k] < x:
return b+1
if k >= self.N:
return r
find_l = self.bisect_sub(a, b, 2*k, l, (l+r)//2, x)
if find_l <= b:
return find_l
find_r = self.bisect_sub(a, b, 2*k+1, (l+r)//2, r, x)
return find_r
def bisect(self, l, r, x):
return self.bisect_sub(l-1, r, 1, 0, self.size-self.N, x)
def main():
n, q = map(int, input().split())
p = list(map(int, input().split()))
seg = SegmentTree(n, max, 0, arrange=p)
res = []
for i in range(q):
a, b, c = list(map(int, input().split()))
if a == 1:
seg.update(b, c)
elif a == 2:
ans = seg.count(b, c)
res.append(ans)
else:
ans = seg.bisect(b, n, c)
res.append(ans)
print(*res, sep="\n")
if __name__ == "__main__":
main()
``` | output | 1 | 9,654 | 5 | 19,309 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,655 | 5 | 19,310 |
"Correct Solution:
```
class RMaxQ:
__slots__ = ["n", "data"]
def __init__(self, li):
self.n = len(li)
self.data = li*2
for i in range(self.n - 1, 0, -1):
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def update(self, i, a):
i += self.n
self.data[i] = a
while i > 1:
i //= 2
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def add(self, i, a):
i += self.n
self.data[i] += a
while i > 1:
i //= 2
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def fold(self, l, r):
l += self.n
r += self.n
res = 0
while l < r:
if l % 2:
res = max(self.data[l], res)
l += 1
if r % 2:
r -= 1
res = max(res, self.data[r])
l //= 2
r //= 2
return res
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
A = list(map(int, input().split()))
seg = RMaxQ(A)
for _ in range(q):
t, x, v = map(int, input().split())
x -= 1
if t == 1:
seg.update(x, v)
elif t == 2:
print(seg.fold(x, v))
else:
ng = x
ok = n+1
while ok - ng > 1:
mid = (ok+ng)//2
if seg.fold(x, mid) >= v:
ok = mid
else:
ng = mid
print(ok)
``` | output | 1 | 9,655 | 5 | 19,311 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,656 | 5 | 19,312 |
"Correct Solution:
```
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.d = [e] * (2 * self.size)
self.lz = [id] * (self.size)
def update(self, k):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def push(self, k):
self.all_apply(2 * k, self.lz[k])
self.all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id
def build(self, arr):
#assert len(arr) == self.n
for i, a in enumerate(arr):
self.d[self.size + i] = a
for i in range(1, self.size)[::-1]:
self.update(i)
def set(self, p, x):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1):
self.push(p >> i)
return self.d[p]
def prod(self, l, r):
#assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def apply(self, p, f):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
#assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
def max_right(self, l, g):
#assert 0 <= l <= self.n
#assert g(self.e)
if l == self.n: return self.n
l += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(l >> i)
sm = self.e
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: return self.n
def min_left(self, r, g):
#assert 0 <= r <= self.n
#assert g(self.e)
if r == 0: return 0
r += self.size
for i in range(1, self.log + 1)[::-1]:
self.push((r - 1) >> i)
sm = self.e
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: return 0
import sys
input = sys.stdin.buffer.readline
N, Q = map(int, input().split())
A = tuple(map(int, input().split()))
eq = lambda x, y: y
lst = LazySegmentTree(N, max, 0, eq, eq, 0)
lst.build(A)
res = []
for _ in range(Q):
t, x, y = map(int, input().split())
if t == 1:
lst.set(x - 1, y)
elif t == 2:
res.append(lst.prod(x - 1, y))
else:
res.append(lst.max_right(x - 1, lambda z: z < y) + 1)
print('\n'.join(map(str, res)))
``` | output | 1 | 9,656 | 5 | 19,313 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6 | instruction | 0 | 9,657 | 5 | 19,314 |
"Correct Solution:
```
class segment_tree:
__slots__ = ["op_M", "e_M","N","N0","dat"]
def __init__(self, N, operator_M, e_M):
self.op_M = operator_M
self.e_M = e_M
self.N = N
self.N0 = 1<<(N-1).bit_length()
self.dat = [self.e_M]*(2*self.N0)
# 長さNの配列 initial で初期化
def build(self, initial):
self.dat[self.N0:self.N0+len(initial)] = initial[:]
for k in range(self.N0-1,0,-1):
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
# a_k の値を x に更新
def update(self,k,x):
k += self.N0
self.dat[k] = x
k >>= 1
while k:
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
k >>= 1
# 区間[L,R]をopでまとめる
def query(self,L,R):
L += self.N0; R += self.N0 + 1
sl = sr = self.e_M
while L < R:
if R & 1:
R -= 1
sr = self.op_M(self.dat[R],sr)
if L & 1:
sl = self.op_M(sl,self.dat[L])
L += 1
L >>= 1; R >>= 1
return self.op_M(sl,sr)
def get(self, k): #k番目の値を取得。query[k,k]と同じ
return self.dat[k+self.N0]
"""
f(x_l*...*x_{r-1}) が True になる最大の r
つまり TTTTFFFF となるとき、F となる最小の添え字
存在しない場合 n が返る
f(e_M) = True でないと壊れる
"""
def max_right(self,l,f):
if l == self.N: return self.N;
l += self.N0
sm = self.e_M
while True:
while l&1==0:
l >>= 1
if not f(self.op_M(sm,self.dat[l])):
while l < self.N0:
l *= 2
if f(self.op_M(sm,self.dat[l])):
sm = self.op_M(sm,self.dat[l])
l += 1
return l - self.N0
sm = self.op_M(sm,self.dat[l])
l += 1
if (l & -l) == l: break
return self.N
"""
f(x_l*...*x_{r-1}) が True になる最小の l
つまり FFFFTTTT となるとき、T となる最小の添え字
存在しない場合 r が返る
f(e_M) = True でないと壊れる
"""
def min_left(self,r,f):
if r == 0: return 0
r += self.N0
sm = self.e_M
while True:
r -= 1
while r > 1 and r&1:
r >>= 1
if not f(self.op_M(self.dat[r],sm)):
while r < self.N0:
r = r*2 + 1
if f(self.op_M(self.dat[r],sm)):
sm = self.op_M(self.dat[r],sm)
r -= 1
return r + 1 - self.N0
sm = self.op_M(self.dat[r],sm)
if (r & -r) == r: break
return 0
###########################################
import sys
readline = sys.stdin.readline
n,q = map(int, readline().split())
*a, = map(int, readline().split())
seg = segment_tree(n,max,0)
seg.build(a)
for _ in range(q):
idx,p,v = map(int, readline().split())
if idx==1:
seg.update(p-1,v)
elif idx==2:
print(seg.query(p-1,v-1))
else:
print(seg.max_right(p-1,lambda x: x < v)+1)
``` | output | 1 | 9,657 | 5 | 19,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
#region bcf
# code section by Barry Fam
#
# pylint: disable= reimported
#region rangedata.py
#region hyperlist.py
import itertools
# def hyperlist(*dim, default_factory=None):
def hyperlist(*dim, **kwarg):
default_factory = kwarg.pop("default_factory", None)
ranges = [range(n) for n in dim]
h = [None]*dim[0]
for dd in range(1, len(dim)):
for u in itertools.product(*ranges[:dd]):
hyperlist_setitem(h, u, [None]*dim[dd])
if default_factory:
for u in itertools.product(*ranges):
hyperlist_setitem(h, u, default_factory())
return h
def hyperlist_setitem(h, u, a):
ptr = h
for i in u[:-1]: ptr = ptr[i]
ptr[u[-1]] = a
def hyperlist_getitem(h, u):
ptr = h
for i in u: ptr = ptr[i]
return ptr
#endregion hyperlist.py
###############################################################################
import operator
import collections
import itertools
import functools
import math as m
try: m.prod
except AttributeError:
def _prod(iterable, start=1):
for x in iterable: start *= x
return start
m.prod = _prod
# class RangeOperators:
class RangeOperators(object): # pylint: disable= useless-object-inheritance
'''
Data class to define the behavior of a range data structure
new() := factory for zero values, e.g. int()
query(a, b) := the binary query function of the tree. e.g. operator.add() for a cumulative sum
q_inverse(a, b) := the inverse of the query function, if it exists. required for a Fenwick tree
update(t, x) := define how the tree will be updated: return the new value of t if updated with x
u_distributive(t, x, w) := return the new value of t if its w leaves are updated by x. required for lazy propagation
u_commutative: bool := True if the update operation is commutative. e.g. add() is; but "set to" is not
'''
__slots__ = [
"new",
"query",
"q_inverse",
"update",
"u_distributive",
"u_commutative",
]
_defaults = dict(
new= int,
query= operator.add,
q_inverse= operator.sub,
update= operator.add,
u_distributive= lambda t, x, w: t + x*w,
u_commutative= True,
)
def __init__(self, **kwarg):
d = kwarg or self._defaults
for k, v in d.items():
setattr(self, k, v)
MAXQUERY = RangeOperators(
new= int,
query= max,
q_inverse= None,
update= operator.add,
u_distributive= lambda t, x, w: t + x,
u_commutative= True,
)
MINQUERY = RangeOperators(
new= int,
query= min,
q_inverse= None,
update= operator.add,
u_distributive= lambda t, x, w: t + x,
u_commutative= True,
)
SETUPDATE = RangeOperators(
new= int,
query= operator.add,
q_inverse= operator.sub,
update= lambda t, x: x,
u_distributive= lambda t, x, w: x*w,
u_commutative= False,
)
# class SegmentTree:
class SegmentTree(object): # pylint: disable= useless-object-inheritance
"""
SegmentTree(n: int) -> new tree of size n
SegmentTree(iterable) -> new tree, initialized
Methods:
update_point(i, value)
update_range(start, stop, value)
update_consecutive_points(start, stop, iterable)
query_point(i)
query_range(start, stop)
"""
def __init__(self, arg, sparse=False, ops=RangeOperators(), **kwarg):
# super().__init__(**kwarg)
super(SegmentTree, self).__init__(**kwarg)
try:
init = list(arg)
dim = len(init)
except TypeError:
init = None
dim = arg
self.dim = dim
self.ops = ops
self._lazy = self.ops.u_distributive is not None
self._clean = True
if sparse:
self._tree = collections.defaultdict(ops.new)
@functools.lru_cache(maxsize=dim)
def seglen(u):
if u >= self.dim: return 1
return seglen(u<<1) + seglen(u<<1|1)
self._seglen = seglen
if self._lazy:
self._pending = collections.defaultdict(lambda: None)
else:
self._tree = [ops.new() for _ in range(dim*2)]
seglen_precomp = [1]*dim*2
for u in reversed(range(1, dim)):
seglen_precomp[u] = seglen_precomp[u<<1] + seglen_precomp[u<<1|1]
self._seglen = seglen_precomp.__getitem__
if self._lazy:
self._pending = [None]*dim
if init:
self.update_consecutive_points(0, dim, init)
# Iterators
def _downward_path(self, i):
"""Iterate over tree indexes from root to just above raw index i"""
u = self.dim + i
for s in range(u.bit_length()-1, 0, -1):
yield u >> s
def _upward_path(self, i):
"""Iterate over tree indexes from just above raw index i to root"""
u = self.dim + i
while u > 1:
u >>= 1
yield u
def _downward_fill(self, i, j):
"""Iterate over every tree index that is an ancestor of raw index range [i,j), from root downwards"""
n = self.dim
l = n+i
r = n+j-1
for s in range(l.bit_length()-1, 0, -1):
for u in range(l>>s, (r>>s)+1):
yield u
def _upward_fill(self, i, j):
"""Iterate over every tree index that is an ancestor of raw index range [i,j), from just above leaves upwards"""
n = self.dim
l = n+i
r = n+j-1
while l > 1:
l >>= 1
r >>= 1
for u in reversed(range(l, r+1)):
yield u
def _cover_nodes(self, i, j):
"""Iterate over the set of tree indexes whose segments optimally cover raw index range [i,j)"""
n = self.dim
l = n+i
r = n+j
while l < r:
if l&1:
yield l
l += 1
if r&1:
r -= 1
yield r
l >>= 1
r >>= 1
# Node modification
def _lazy_update(self, u, value):
"""Update tree index u as if its child leaves had been updated with value"""
self._tree[u] = self.ops.u_distributive(self._tree[u], value, self._seglen(u))
if u < self.dim:
self._clean = False
if self._pending[u] is None:
self._pending[u] = value
else:
self._pending[u] = self.ops.update(self._pending[u], value)
def _push1(self, u):
"""Apply any pending lazy update at tree index u to its two immediate children"""
assert u < self.dim
if self._clean: return
value = self._pending[u]
if value is not None:
for v in (u<<1, u<<1|1):
self._lazy_update(v, value)
self._pending[u] = None
def _build1(self, u):
"""Calculate the query function at tree index u from its two immediate children"""
assert u < self.dim
self._push1(u)
self._tree[u] = self.ops.query(self._tree[u<<1], self._tree[u<<1|1])
# Node-set modification
def _push_path(self, i):
"""Push lazy updates from root to raw index i"""
if self._clean: return
for u in self._downward_path(i):
self._push1(u)
def _push_fill(self, i, j):
"""Push lazy updates from root to raw index range [i,j)"""
if self._clean: return
for u in self._downward_fill(i, j):
self._push1(u)
if j-i == self.dim: self._clean = True
def _build_path(self, i):
"""Update tree nodes from raw index i to root"""
for u in self._upward_path(i):
self._build1(u)
def _build_fill(self, i, j):
"""Update all tree ancestors of raw index range [i,j)"""
for u in self._upward_fill(i, j):
self._build1(u)
if j-i == self.dim: self._clean = True
# Interface
def update_consecutive_points(self, start, stop, iterable):
assert 0 <= start < stop <= self.dim
# push if necessary
if not self.ops.u_commutative:
self._push_fill(start, stop-1)
# write leaves
for u, value in zip(range(self.dim + start, self.dim + stop), iterable):
self._tree[u] = self.ops.update(self._tree[u], value)
# build
self._build_fill(start, stop-1)
def query_range(self, start, stop):
assert start < stop
for i in {start, stop-1}:
self._push_path(i)
node_values = (self._tree[u] for u in self._cover_nodes(start, stop))
return functools.reduce(self.ops.query, node_values)
def update_range(self, start, stop, value):
assert start < stop
# if no lazy propagation, fall back to writing to leaves
if not self._lazy:
self.update_consecutive_points(start, stop, itertools.repeat(value))
return
# push if necessary
if not self.ops.u_commutative:
for i in {start, stop-1}:
self._push_path(i)
# write cover nodes
for u in self._cover_nodes(start, stop):
self._lazy_update(u, value)
# build
for i in {start, stop-1}:
self._build_path(i)
def query_point(self, i):
return self.query_range(i, i+1)
def update_point(self, i, value):
self.update_range(i, i+1, value)
# class FenwickTree:
class FenwickTree(object): # pylint: disable= useless-object-inheritance
"""
ft1d = FenwickTree(dim)
ft3d = FenwickTree(dim1, dim2, dim3)
etc.
Methods:
ft1d.iadd(i, update_value)
ft3d.iadd((i,j,k), update_value)
ft1d[i] = set_value
fr3d[i,j,k] = set_value
query = ft1d[i1:i2]
query = ft3d[i1:i2, j1:j2, k1:k2]
"""
# def __init__(self, *dim, sparse=False, **kwarg):
def __init__(self, *dim, **kwarg):
sparse = kwarg.pop("sparse", False)
# super().__init__(**kwarg)
super(FenwickTree, self).__init__(**kwarg)
self.dim = dim
self.d = len(dim)
if sparse:
self._tree = collections.defaultdict(int)
if self.d > 1:
self._tree_setitem = self._tree.__setitem__
self._tree_getitem = self._tree.__getitem__
else:
self._tree = hyperlist(*dim, default_factory=int)
if self.d > 1:
self._tree_setitem = functools.partial(hyperlist_setitem, self._tree)
self._tree_getitem = functools.partial(hyperlist_getitem, self._tree)
if self.d == 1:
self.iadd = self._iadd_1d
self._getitem = self._getitem_1d
else:
self.iadd = self._iadd_dd
self._getitem = self._getitem_dd
def __setitem__(self, key, value):
self.iadd(key, value-self[key])
def __getitem__(self, key):
return self._getitem(key)
@staticmethod
def _set_index_iter(i, n):
"""Iterate over the tree indices < n which are affected when setting raw index i"""
if i == 0:
yield 0
return
while True:
yield i
i += i & -i # increment LSB
if i >= n: return
@staticmethod
def _get_index_iter(i, j):
"""
Iterate over the tree indices whose sum equals the sum over the raw range (j,i] -- note that i > j
Each index is returned as (index, sign) where sign is +1 or -1 for inclusion-exclusion
"""
if i < 0: return
if j < 0:
yield 0, +1
j = 0
while i > j:
yield i, +1
i &= i-1 # decrement LSB
while j > i:
yield j, -1
j &= j-1 # decrement LSB
def _iadd_1d(self, key, value):
assert 0 <= key < self.dim[0]
for i in self._set_index_iter(key, self.dim[0]):
self._tree[i] += value
def _iadd_dd(self, key, value):
assert len(key) == self.d
assert all(0 <= i < self.dim[dd] for dd, i in enumerate(key)), "index out of range"
index_iters = [self._set_index_iter(i, self.dim[dd]) for dd, i in enumerate(key)]
for u in itertools.product(*index_iters):
g = self._tree_getitem(u)
self._tree_setitem(u, g+value)
def _getitem_1d(self, key):
if isinstance(key, slice):
assert key.step is None
start, stop, _ = key.indices(self.dim[0])
if stop < start: stop = start
i, j = stop-1, start-1
else:
i, j = key, key-1
assert -1 <= j <= i < self.dim[0], "index out of range"
sigma = 0
for k, sign in self._get_index_iter(i, j):
sigma += sign * self._tree[k]
return sigma
def _getitem_dd(self, key):
index_iters = []
for dd, k in enumerate(key):
if isinstance(k, slice):
assert k.step is None
start, stop, _ = k.indices(self.dim[dd])
if stop < start: stop = start
itr = self._get_index_iter(stop-1, start-1)
else:
assert 0 <= k < self.dim[dd], "index out of range"
itr = self._get_index_iter(k, k-1)
index_iters.append(itr)
assert len(index_iters) == self.d, "mismatched key dimensions"
sigma = 0
for i_sign_pairs in itertools.product(*index_iters):
u, signs = zip(*i_sign_pairs)
sign = m.prod(signs)
sigma += sign * self._tree_getitem(u)
return sigma
#endregion rangedata.py
#endregion bcf
###############################################################################
#region bcf
# code section by Barry Fam
#
# pylint: disable= reimported
#region logsearch.py
import math as m
def binary_search_int(f, start, stop):
"""
Binary search for the point at which f() becomes true
f() may be evaluated at the points in [start, stop) half-open
The return value will be in the range [start, stop] inclusive
f() must be always false to the left of some point, and always true to the right
>>> f = lambda x: x > 50
>>> binary_search_int(f, 40, 91)
51
>>> binary_search_int(f, 20, 31)
31
>>> binary_search_int(f, 60, 81)
60
"""
assert start < stop
left, right = start, stop
while left < right:
mid = (left + right)//2
if f(mid):
right = mid
else:
left = mid+1
return right
def binary_search_float(f, left, right, rel_tol=1e-09, abs_tol=0.0):
"""
Binary search for the point at which f() becomes true
f() must be always false to the left of some point, and always true to the right
Note: If the return may be close to 0, set abs_tol to avoid excessive/infinite iteration
>>> f = lambda x: x >= 3.5
>>> _ = binary_search_float(f, 0, 10)
>>> round(_, 6)
3.5
"""
assert left <= right
while not m.isclose(left, right, rel_tol=rel_tol, abs_tol=abs_tol):
mid = (left + right)/2
if f(mid):
right = mid
else:
left = mid
return right
def ternary_search_int(f, start, stop):
"""
Ternary search for the maximum point of f()
df/dx must be always positive to the left of some point, and always negative to the right
>>> f = lambda x: -(x-42)**2
>>> ternary_search_int(f, 0, 100)
42
"""
assert start < stop
invphi2 = (3-m.sqrt(5)) / 2
a, d = start, stop-1
b = a + round(invphi2 * (d-a))
c = b + m.ceil(invphi2 * (d-b))
fb = f(b)
fc = f(c)
while True:
if fb < fc:
if c == d: return d
a = b+1
b, fb = c, fc
c = b + m.ceil(invphi2 * (d-b))
fc = f(c)
else:
if a == b: return a
d = c-1
c, fc = b, fb
b = c - m.ceil(invphi2 * (c-a))
fb = f(b)
def ternary_search_float(f, left, right, rel_tol=1e-09, abs_tol=0.0):
"""
Ternary search for the maximum point of f()
df/dx must be always positive to the left of some point, and always negative to the right
Note: If the return may be close to 0, set abs_tol to avoid excessive/infinite iteration
>>> f = lambda x: -(x-3.5)**2
>>> _ = ternary_search_float(f, 0, 10)
>>> round(_, 6)
3.5
"""
assert left <= right
invphi2 = (3-m.sqrt(5)) / 2
a, d = left, right
b = a + invphi2 * (d-a)
c = b + invphi2 * (d-b)
fb = f(b)
fc = f(c)
while not m.isclose(a, d, rel_tol=rel_tol, abs_tol=abs_tol):
if fb < fc:
a = b
b, fb = c, fc
c = b + invphi2 * (d-b)
fc = f(c)
else:
d = c
c, fc = b, fb
b = c - invphi2 * (c-a)
fb = f(b)
return c
# if __name__ == "__main__":
if False: # pylint: disable= using-constant-test
import doctest
doctest.testmod()
#endregion logsearch.py
#endregion bcf
###############################################################################
import sys
def input(itr=iter(sys.stdin.readlines())): # pylint: disable= redefined-builtin
return next(itr).rstrip('\n\r')
###############################################################################
N, Q = map(int, input().split())
A = list(map(int, input().split()))
setu_maxq = RangeOperators(
new= int,
query= max,
q_inverse= None,
update= lambda t, x: x,
u_distributive= lambda t, x, w: x,
u_commutative= False,
)
st = SegmentTree(A, ops=setu_maxq)
responses = []
for _ in range(Q):
T = tuple(map(int, input().split()))
if T[0] == 1:
_, X, V = T
st.update_point(X-1, V)
elif T[0] == 2:
_, L, R = T
responses.append(st.query_range(L-1, R-1+1))
elif T[0] == 3:
_, X, V = T
def valid(j):
return st.query_range(X-1, j-1+1) >= V
j = binary_search_int(valid, X, N+1)
responses.append(j)
print(*responses, sep='\n')
``` | instruction | 0 | 9,658 | 5 | 19,316 |
Yes | output | 1 | 9,658 | 5 | 19,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.range = [(-1,n)] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
self.range[self.num + i] = (i,i)
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] >= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] >=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] >=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] >=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return N
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
A = list(map(int,input().split()))
Seg = SegmentTree(A,max,0)
for _ in range(Q):
query = list(map(int,input().split()))
if query[0] == 1:
gomi,idx,val = query
Seg.update(idx-1,val)
elif query[0] == 2:
gomi,l,r = query
print(Seg.query(l-1,r))
else:
gomi,l,val = query
print(Seg.bisect_l(l-1,N,val)+1)
``` | instruction | 0 | 9,659 | 5 | 19,318 |
Yes | output | 1 | 9,659 | 5 | 19,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class LazySegmentTree():
def __init__(self, n, f, g, h, ef, eh):
"""
:param n: 配列の要素数
:param f: 取得半群の元同士の積を定義
:param g: 更新半群の元 xh が配列上の実際の値にどのように作用するかを定義
:param h: 更新半群の元同士の積を定義 (更新半群の元を xh と表記)
:param x: 配列の各要素の値。treeの葉以外は xf(x1,x2,...)
"""
self.n = n
self.f = f
self.g = lambda xh, x: g(xh, x) if xh != eh else x
self.h = h
self.ef = ef
self.eh = eh
l = (self.n - 1).bit_length()
self.size = 1 << l
self.tree = [self.ef] * (self.size << 1)
self.lazy = [self.eh] * ((self.size << 1) + 1)
self.plt_cnt = 0
def built(self, array):
"""
arrayを初期値とするセグメント木を構築
"""
for i in range(self.n):
self.tree[self.size + i] = array[i]
for i in range(self.size - 1, 0, -1):
self.tree[i] = self.f(self.tree[i<<1], self.tree[(i<<1)|1])
def update(self, i, x):
"""
i 番目の要素を x に更新する
"""
i += self.size
self.propagate_lazy(i)
self.tree[i] = x
self.lazy[i] = self.eh
self.propagate_tree(i)
def get(self, i):
"""
i 番目の値を取得( 0-indexed ) ( O(logN) )
"""
i += self.size
self.propagate_lazy(i)
return self.g(self.lazy[i], self.tree[i])
def update_range(self, l, r, x):
"""
半開区間 [l, r) の各々の要素 a に op(x, a)を作用させる ( 0-indexed ) ( O(logN) )
"""
if l >= r:
return
l += self.size
r += self.size
l0 = l//(l&-l)
r0 = r//(r&-r)
self.propagate_lazy(l0)
self.propagate_lazy(r0-1)
while l < r:
if r&1:
r -= 1 # 半開区間なので先に引いてる
self.lazy[r] = self.h(x, self.lazy[r])
if l&1:
self.lazy[l] = self.h(x, self.lazy[l])
l += 1
l >>= 1
r >>= 1
self.propagate_tree(l0)
self.propagate_tree(r0-1)
def get_range(self, l, r):
"""
[l, r)への作用の結果を返す (0-indexed)
"""
l += self.size
r += self.size
self.propagate_lazy(l//(l&-l))
self.propagate_lazy((r//(r&-r))-1)
res_l = self.ef
res_r = self.ef
while l < r:
if l & 1:
res_l = self.f(res_l, self.g(self.lazy[l], self.tree[l]))
l += 1
if r & 1:
r -= 1
res_r = self.f(self.g(self.lazy[r], self.tree[r]), res_r)
l >>= 1
r >>= 1
return self.f(res_l, res_r)
def max_right(self, l, z):
"""
以下の条件を両方満たす r を(いずれか一つ)返す
・r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・r = n or f(op(a[l], a[l + 1], ..., a[r])) = false
"""
if l >= self.n: return self.n
l += self.size
s = self.ef
while 1:
while l % 2 == 0:
l >>= 1
if not z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
while l < self.size:
l *= 2
if z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
return l - self.size
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
if l & -l == l: break
return self.n
def min_left(self, r, z):
"""
以下の条件を両方満たす l を(いずれか一つ)返す
・l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false
"""
if r <= 0: return 0
r += self.size
s = self.ef
while 1:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
while r < self.size:
r = r * 2 + 1
if z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
r -= 1
return r + 1 - self.size
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
if r & -r == r: break
return 0
def propagate_lazy(self, i):
"""
lazy の値をトップダウンで更新する ( O(logN) )
"""
for k in range(i.bit_length()-1,0,-1):
x = i>>k
if self.lazy[x] == self.eh:
continue
laz = self.lazy[x]
self.lazy[(x<<1)|1] = self.h(laz, self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(laz, self.lazy[x<<1])
self.tree[x] = self.g(laz, self.tree[x]) # get_range ではボトムアップの伝搬を行わないため、この処理をしないと tree が更新されない
self.lazy[x] = self.eh
def propagate_tree(self, i):
"""
tree の値をボトムアップで更新する ( O(logN) )
"""
while i>1:
i>>=1
self.tree[i] = self.f(self.g(self.lazy[i<<1], self.tree[i<<1]), self.g(self.lazy[(i<<1)|1], self.tree[(i<<1)|1]))
def __getitem__(self, i):
return self.get(i)
def __iter__(self):
for x in range(1, self.size):
if self.lazy[x] == self.eh:
continue
self.lazy[(x<<1)|1] = self.h(self.lazy[x], self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(self.lazy[x], self.lazy[x<<1])
self.tree[x] = self.g(self.lazy[x], self.tree[x])
self.lazy[x] = self.eh
for xh, x in zip(self.lazy[self.size:self.size+self.n], self.tree[self.size:self.size+self.n]):
yield self.g(xh,x)
def __str__(self):
return str(list(self))
##################################################################################################################
N, Q = map(int, input().split())
A = list(map(int, input().split()))
ef = 0
eh = 0
f = lambda x, y : x if x > y else y
g = lambda x, y : x if x > y else y
h = lambda x, y : x if x > y else y
st = LazySegmentTree(N, f, g, h, ef, eh)
st.built(A)
res = []
for _ in range(Q):
t, x, y = map(int, input().split())
if t == 1:
st.update(x - 1, y)
elif t == 2:
res.append(st.get_range(x - 1, y))
else:
res.append(st.max_right(x - 1, lambda z: z < y) + 1)
print('\n'.join(map(str, res)))
``` | instruction | 0 | 9,660 | 5 | 19,320 |
Yes | output | 1 | 9,660 | 5 | 19,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
# セグ木ソラ書き練習
# 10分くらい
# query()でバグらせたので反省
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegmentTree:
def __init__(self,n,p,unit,f):
self.num=2**((n-1).bit_length())
self.seg=[unit]*(self.num*2)
for i in range(n):
self.seg[self.num+i]=p[i]
for i in range(self.num-1,0,-1):
self.seg[i]=f(self.seg[i<<1],self.seg[(i<<1)+1])
self.unit=unit
self.f=f
def update(self,i,x):
i+=self.num
self.seg[i]=x
while i:
i>>=1
self.seg[i]=self.f(self.seg[i<<1],self.seg[(i<<1)+1])
def query(self,l,r):
ansl=ansr=self.unit
l+=self.num
r+=self.num-1
if l==r:
return self.seg[l]
while l<r:
if l&1:
ansl=self.f(ansl,self.seg[l])
l+=1
if ~r&1:
ansr=self.f(self.seg[r],ansr)
r-=1
l>>=1
r>>=1
if l==r:
ansl=self.f(ansl,self.seg[l])
return self.f(ansl,ansr)
n,q=map(int,input().split())
a=list(map(int,input().split()))
f=lambda x,y: max(x,y)
seg=SegmentTree(n,a,0,f)
for _ in range(q):
t,a,b=map(int,input().split())
if t==1:
seg.update(a-1,b)
if t==2:
print(seg.query(a-1,b))
if t==3:
ng=a-1
ok=n+1
while ng+1!=ok:
mid=(ng+ok)//2
if seg.query(ng,mid)>=b:ok=mid
else:ng=mid
print(ok)
``` | instruction | 0 | 9,661 | 5 | 19,322 |
Yes | output | 1 | 9,661 | 5 | 19,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
# Date [ 2020-09-08 00:35:49 ]
# Problem [ j.py ]
# Author Koki_tkg
import sys
# import math
# import bisect
# import numpy as np
# from decimal import Decimal
# from numba import njit, i8, u1, b1 #JIT compiler
# from itertools import combinations, product
# from collections import Counter, deque, defaultdict
# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846
def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return map(int, sys.stdin.readline().strip().split())
def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)
class SegmentTree:
def __init__(self, array, function, identify):
self.length = len(array)
self.func, self.ide_ele = function, identify
self.size = 1 << (self.length-1).bit_length()
self.data = [self.ide_ele] * 2*self.size
# set
for i in range(self.length):
self.data[self.size + i] = array[i]
# build
for i in range(self.size-1, 0, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i + 1])
def update(self, idx, x):
idx += self.size
self.data[idx] = x
while idx > 0:
idx >>= 1
self.data[idx] = self.func(self.data[2*idx], self.data[2*idx + 1])
def query(self, l, r):
l += self.size; r += self.size+1
l_ret = r_ret = self.ide_ele
while l < r:
if l & 1:
l_ret = self.func(l_ret, self.data[l])
l += 1
if r & 1:
r -= 1
r_ret = self.func(self.data[r], r_ret)
l >>= 1; r >>= 1
return self.func(l_ret, r_ret)
def get(self, idx):
return self.data[idx+self.size]
def Main():
n, q = read_ints()
a = read_int_list()
seg = SegmentTree(a, max, -float('inf'))
for _ in range(q):
t, x, v = read_ints()
if t == 1:
seg.update(~-x, v)
elif t == 2:
print(seg.query(x, v))
else:
l = x; r = n + 1
while r - l > 1:
mid = (l + r) // 2
if seg.query(x, mid) >= v:
r = mid
else:
l = mid
print(r)
if __name__ == '__main__':
Main()
``` | instruction | 0 | 9,662 | 5 | 19,324 |
No | output | 1 | 9,662 | 5 | 19,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
mycode = r'''
# distutils: language=c++
# cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True
ctypedef long long LL
# cython: cdivision=True
from libc.stdio cimport scanf
from libcpp.vector cimport vector
ctypedef vector[LL] vec
cdef class SegmentTree():
cdef LL num,n
cdef vec tree
def __init__(self,vec A):
cdef LL n,i
n = A.size()
self.n = n
self.num = 1 << (n-1).bit_length()
self.tree = vec(2*self.num,0)
for i in range(n):
self.tree[self.num + i] = A[i]
for i in range(self.num-1,0,-1):
self.tree[i] = max(self.tree[2*i],self.tree[2*i+1])
cdef void update(self,LL k,LL x):
k += self.num
self.tree[k] = x
while k>1:
self.tree[k>>1] = max(self.tree[k],self.tree[k^1])
k >>= 1
cdef LL query(self,LL l,LL r):
cdef LL res
res = 0
l += self.num
r += self.num
while l<r:
if l&1:
res = max(res,self.tree[l])
l += 1
if r&1:
res = max(res,self.tree[r-1])
l >>= 1
r >>= 1
return res
cdef LL bisect_l(self,LL l,LL r,LL x):
cdef LL Lmin,Rmin,pos
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l&1:
if self.tree[l] >= x and Lmin == -1:
Lmin = l
l += 1
if r&1:
if self.tree[r] >= x:
Rmin = r
l >>= 1
r >>= 1
if Lmin!=-1:
pos = Lmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
elif Rmin!=-1:
pos = Rmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
else:
return self.n
cdef LL N,Q,i
cdef vec A
scanf("%lld %lld",&N,&Q)
A = vec(N,-1)
for i in range(N):
scanf("%lld",&A[i])
cdef SegmentTree S = SegmentTree(A)
cdef LL t,x,v
for i in range(Q):
scanf("%lld %lld %lld",&t,&x,&v)
if t==1:
S.update(x-1,v)
elif t==2:
print(S.query(x-1,v))
else:
print(S.bisect_l(x-1,N,v)+1)
'''
import sys
import os
if sys.argv[-1] == 'ONLINE_JUDGE': # コンパイル時
with open('mycode.pyx', 'w') as f:
f.write(mycode)
os.system('cythonize -i -3 -b mycode.pyx')
import mycode
``` | instruction | 0 | 9,663 | 5 | 19,326 |
No | output | 1 | 9,663 | 5 | 19,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class SegmentTree: #1-indexed
def __init__(self,list,f=lambda x,y:x+y,inf=0):
self.height=(len(list)-1).bit_length()+1 #木の高さ
self.zero=2**(self.height-1) #最下段に添字を合わせる用
self.id=inf #単位元
self.tree=[self.id]*(2**self.height) #木を単位元で初期化
self.f=f
for i in range(len(list)):
self.tree[self.zero+i]=list[i]
for i in range(self.zero-1,0,-1):
self.tree[i]=self.f(self.tree[2*i],self.tree[2*i+1])
def update(self,i,x): #i番目の要素をxに変更
i+=self.zero
self.tree[i]=x
while i>1:
i//=2
self.tree[i]=self.f(self.tree[2*i],self.tree[2*i+1])
def query(self,l,r):
l+=self.zero
r+=self.zero
lf,rf=self.id,self.id
while l<r:
if l&1:
lf=self.f(lf,self.tree[l])
l+=1
if r&1:
r-=1
rf=self.f(self.tree[r],rf)
l//=2
r//=2
return self.f(lf,rf)
'''
Falseを探索するかTrueを探索するかは問題によって使い分ける(デフォはTrue探索)
FFFFTTTTとしたときの最小のTを求める
'''
def BinarySearch(self,l,r,f): #fの返り値はboolにする
l+=self.zero
r+=self.zero
if not f(self.tree[1]):
return r+1-self.zero
while True:
if f(self.tree[l]):
if l>=self.zero:
return l-self.zero+1 #最下段ならreturn
else:
l*=2 #左の子供を見る
else:
if l%2==0:
l+=1 #左の子なら右を見る
else:
l=(l//2)+1 #右の子なら親の右を見る
#####################################################
n,q=map(int,input().split())
a=list(map(int,input().split()))
seg=SegmentTree(a,max)
for i in range(q):
t,x,y=map(int,input().split())
if t==1:
seg.update(x-1,y)
elif t==2:
print(seg.query(x-1,y-1))
else:
print(seg.BinarySearch(x-1,n,lambda x:x>=y))
``` | instruction | 0 | 9,664 | 5 | 19,328 |
No | output | 1 | 9,664 | 5 | 19,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
def segfunc(x, y):
return max(x, y)
def init(init_val):
for i in range(n):
seg[i + num - 1] = init_val[i]
for i in range(num - 2, -1, -1):
seg[i] = segfunc(seg[2 * i + 1], seg[2 * i + 2])
def update(k, x):
k += num - 1
seg[k] = x
while k:
k = (k - 1) // 2
seg[k] = segfunc(seg[k * 2 + 1], seg[k * 2 + 2])
def query(p, q):
if q <= p:
return ide_ele
p += num - 1
q += num - 2
res = ide_ele
while q - p > 1:
if p & 1 == 0:
res = segfunc(res, seg[p])
if q & 1 == 1:
res = segfunc(res, seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = segfunc(res, seg[p])
else:
res = segfunc(segfunc(res, seg[p]), seg[q])
return res
# seg tree初期値 (単位元)
n = N
ide_ele = 0
num = 2 ** (n - 1).bit_length()
seg = [ide_ele] * 2 * num
init(A)
def isOK(mid, m, value):
a = query(m, mid)
return a <= value
B = A[::]
for _ in range(Q):
T, X, V = [int(x) for x in input().split()]
if T == 1:
update(X - 1, V)
B[X - 1] = V
elif T == 2:
print(query(X - 1, V - 1))
else:
a = query(X - 1, N - 1)
if a < V:
print(N + 1)
else:
if B[X - 1] >= V:
print(X)
continue
ok = N - 1
ng = X - 1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, X - 1, V):
ok = mid
else:
ng = mid
print(ok + 1)
if __name__ == '__main__':
main()
``` | instruction | 0 | 9,665 | 5 | 19,330 |
No | output | 1 | 9,665 | 5 | 19,331 |
Provide a correct Python 3 solution for this coding contest problem.
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None | instruction | 0 | 9,815 | 5 | 19,630 |
"Correct Solution:
```
def main():
while True:
a = []
n, k = [int(x) for x in input().split()]
if n == 0 and k == 0: break
for i in range(n): a.append(int(input()))
l = [0]
for i in range(1, n - k + 1): l.append(a[i + k - 1] - a[i - 1])
maxsum = 0
maxi = 0
s = 0
for i, x in enumerate(l):
s += x
if s >= maxsum:
maxsum = s
maxi = i
print(sum(a[maxi:maxi + k]))
main()
``` | output | 1 | 9,815 | 5 | 19,631 |
Provide a correct Python 3 solution for this coding contest problem.
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None | instruction | 0 | 9,816 | 5 | 19,632 |
"Correct Solution:
```
while True:
n, k = map(int, input().split())
if n == 0 and k == 0:
break
x = 0
a = []
for i in range(n):
y = int(input())
a.append(y)
s = 0
for j in range(k):
s += a[j]
S = []
S.append(s)
for i in range(1, n-k+1):
s = S[i-1] + a[i+k-1] -a[i-1]
S.append(s)
x = max(S)
print(x)
``` | output | 1 | 9,816 | 5 | 19,633 |
Provide a correct Python 3 solution for this coding contest problem.
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None | instruction | 0 | 9,817 | 5 | 19,634 |
"Correct Solution:
```
# coding: utf-8
# Your code here!
while True:
n,k=map(int,input().split())
if n==0 and k==0:
break
a=[int(input()) for _ in range(n)]
s=sum(a[0:k])
ss=[s]
for i in range(k,n):
s=s+a[i]-a[i-k]
ss.append(s)
print(max(ss))
``` | output | 1 | 9,817 | 5 | 19,635 |
Provide a correct Python 3 solution for this coding contest problem.
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None | instruction | 0 | 9,818 | 5 | 19,636 |
"Correct Solution:
```
#!/usr/bin/env python
import string
import sys
from itertools import chain, dropwhile, takewhile
def read(
*shape, f=int, it=chain.from_iterable(sys.stdin), whitespaces=set(string.whitespace)
):
def read_word():
w = lambda c: c in whitespaces
nw = lambda c: c not in whitespaces
return f("".join(takewhile(nw, dropwhile(w, it))))
if not shape:
return read_word()
elif len(shape) == 1:
return [read_word() for _ in range(shape[0])]
elif len(shape) == 2:
return [[read_word() for _ in range(shape[1])] for _ in range(shape[0])]
def readi(*shape):
return read(*shape)
def readi1(*shape):
return [i - 1 for i in read(*shape)]
def readf(*shape):
return read(*shape, f=float)
def reads(*shape):
return read(*shape, f=str)
def arr(*shape, fill_value=0):
if len(shape) == 1:
return [fill_value] * shape[fill_value]
elif len(shape) == 2:
return [[fill_value] * shape[1] for _ in range(shape[0])]
def dbg(**kwargs):
print(
", ".join("{} = {}".format(k, repr(v)) for k, v in kwargs.items()),
file=sys.stderr,
)
def main():
while True:
n, k = readi(2)
if n == 0:
return
a = readi(n)
tmp = sum(a[:k])
ans = tmp
for i in range(k, len(a)):
tmp += a[i] - a[i - k]
ans = max(ans, tmp)
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 9,818 | 5 | 19,637 |
Provide a correct Python 3 solution for this coding contest problem.
problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, the positive integer n (1 ≤ n ≤ 100000) and the positive integer k (1 ≤ k ≤ n) are written in this order, separated by blanks. The first + i lines after the second line. (1 ≤ i ≤ n) contains the i-th term ai (-10000 ≤ ai ≤ 10000) in the sequence. Of the scoring data, 60% of the points are n ≤ 5000, k ≤ 1000. Meet.
The number of datasets does not exceed 5.
output
The maximum value of Si is output to one line for each data set.
Examples
Input
5 3
2
5
-4
10
3
0 0
Output
11
Input
None
Output
None | instruction | 0 | 9,819 | 5 | 19,638 |
"Correct Solution:
```
while True:
n, k = map(int,input().split())
if n == k == 0:
break
data = [int(input()) for _ in range(n)]
s = sum(data[0:k])
ss = [s]
for i in range(k, n):
s = s + data[i]- data[i-k]
ss.append(s)
print(max(ss))
``` | output | 1 | 9,819 | 5 | 19,639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.