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.
Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq o_i \ leq 4 $
* $ -10 ^ 6 \ leq Y_i \ leq 10 ^ 6 $
* If $ o_i = 4 $, then $ Y_i \ neq 0 $
* $ X_N $ is an integer greater than or equal to $ -2 ^ {31} $ and less than $ 2 ^ {31} $.
input
Input follows the following format. All given numbers are integers.
$ N $
$ o_1 $ $ Y_1 $
$ o_2 $ $ Y_2 $
$ ... $
$ o_N $ $ Y_N $
When $ o_i = 1 $, $ op_i $ is +, when $ o_i = 2 $, $ op_i $ is −, when $ o_i = 3 $, $ op_i $ is ×, and when $ o_i = 4 $, $ op_i $ is ÷.
output
Print the value of $ X_N $ on one line.
Example
Input
4
1 1
4 2
2 4
3 4
Output
-14 | instruction | 0 | 8,349 | 5 | 16,698 |
"Correct Solution:
```
m=10000000019
x=0
def mod(x):return (x%m+m)%m
def pow(x,a):
ret=1
while a:
if(a&1):ret=mod(x*ret)
x=mod(x*x)
a>>=1
return ret
for _ in range(int(input())):
o,y=map(int,input().split())
if o==1:x=(x+y)%m
elif o==2:x=(x-y)%m
elif o==3:x=mod(x*y)
else:x=mod(x*pow(y,m-2))
print(x if x<(1<<31)else x-m)
``` | output | 1 | 8,349 | 5 | 16,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq o_i \ leq 4 $
* $ -10 ^ 6 \ leq Y_i \ leq 10 ^ 6 $
* If $ o_i = 4 $, then $ Y_i \ neq 0 $
* $ X_N $ is an integer greater than or equal to $ -2 ^ {31} $ and less than $ 2 ^ {31} $.
input
Input follows the following format. All given numbers are integers.
$ N $
$ o_1 $ $ Y_1 $
$ o_2 $ $ Y_2 $
$ ... $
$ o_N $ $ Y_N $
When $ o_i = 1 $, $ op_i $ is +, when $ o_i = 2 $, $ op_i $ is −, when $ o_i = 3 $, $ op_i $ is ×, and when $ o_i = 4 $, $ op_i $ is ÷.
output
Print the value of $ X_N $ on one line.
Example
Input
4
1 1
4 2
2 4
3 4
Output
-14
Submitted Solution:
```
import operator
n = int(input())
ops = {1:operator.add,
2:operator.sub,
3:operator.mul,
4:operator.truediv}
ans = 0
for _ in range(n):
o, y = map(int, input().split())
ans = ops[o](ans, y)
print(int(ans))
``` | instruction | 0 | 8,350 | 5 | 16,700 |
No | output | 1 | 8,350 | 5 | 16,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq o_i \ leq 4 $
* $ -10 ^ 6 \ leq Y_i \ leq 10 ^ 6 $
* If $ o_i = 4 $, then $ Y_i \ neq 0 $
* $ X_N $ is an integer greater than or equal to $ -2 ^ {31} $ and less than $ 2 ^ {31} $.
input
Input follows the following format. All given numbers are integers.
$ N $
$ o_1 $ $ Y_1 $
$ o_2 $ $ Y_2 $
$ ... $
$ o_N $ $ Y_N $
When $ o_i = 1 $, $ op_i $ is +, when $ o_i = 2 $, $ op_i $ is −, when $ o_i = 3 $, $ op_i $ is ×, and when $ o_i = 4 $, $ op_i $ is ÷.
output
Print the value of $ X_N $ on one line.
Example
Input
4
1 1
4 2
2 4
3 4
Output
-14
Submitted Solution:
```
x=0
for _ in range(int(input())):
o,y=map(int,input().split())
if o==1:x+=y
elif o==2:x-=y
elif o==3:x*=y
else:x/=y
print(int(x))
``` | instruction | 0 | 8,351 | 5 | 16,702 |
No | output | 1 | 8,351 | 5 | 16,703 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,362 | 5 | 16,724 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
class LazyPropSegmentTree:
def __init__(self, lst, op, apply, comp, e, identity):
self.n = len(lst)
self.depth = (self.n - 1).bit_length()
self.N = 1 << self.depth
self.op = op # binary operation of elements
self.apply = apply # function to apply to an element
self.comp = comp # composition of functions
self.e = e # identity element w.r.t. op
self.identity = identity # identity element w.r.t. comp
self.v, self.length = self._build(lst) # self.v is set to be 1-indexed for simplicity
self.lazy = [self.identity] * (2 * self.N)
def __getitem__(self, i):
return self.fold(i, i+1)
def _build(self, lst):
# construction of a tree
# total 2 * self.N elements (tree[0] is not used)
e, N, op = self.e, self.N, self.op
tree = [e] * N + lst + [e] * (N - self.n)
length = [1] * (2 * N)
for i in range(N - 1, 0, -1):
lc, rc = i << 1, (i << 1)|1
tree[i] = op(tree[lc], tree[rc])
length[i] = length[lc] + length[rc]
return tree, length
def _indices(self, l, r):
left = l + self.N; right = r + self.N
left //= (left & (-left)); right //= (right & (-right))
left >>= 1; right >>= 1
while left != right:
if left > right: yield left; left >>= 1
else: yield right; right >>= 1
while left > 0: yield left; left >>= 1
# propagate self.lazy and self.v in a top-down manner
def _propagate_topdown(self, *indices):
identity, v, lazy, length, apply, comp = self.identity, self.v, self.lazy, self.length, self.apply, self.comp
for k in reversed(indices):
x = lazy[k]
if x == identity: continue
lc, rc = k << 1, (k << 1) | 1
lazy[lc] = comp(lazy[lc], x)
lazy[rc] = comp(lazy[rc], x)
v[lc] = apply(v[lc], x, length[lc])
v[rc] = apply(v[rc], x, length[rc])
lazy[k] = identity # propagated
# propagate self.v in a bottom-up manner
def _propagate_bottomup(self, indices):
v, op = self.v, self.op
for k in indices: v[k] = op(v[k << 1], v[(k << 1)|1])
# update for the query interval [l, r) with function x
def update(self, l, r, x):
*indices, = self._indices(l, r)
self._propagate_topdown(*indices)
N, v, lazy, length, apply, comp = self.N, self.v, self.lazy, self.length, self.apply, self.comp
# update self.v and self.lazy for the query interval [l, r)
left = l + N; right = r + N
if left & 1: v[left] = apply(v[left], x, length[left]); left += 1
if right & 1: right -= 1; v[right] = apply(v[right], x, length[right])
left >>= 1; right >>= 1
while left < right:
if left & 1:
lazy[left] = comp(lazy[left], x)
v[left] = apply(v[left], x, length[left])
left += 1
if right & 1:
right -= 1
lazy[right] = comp(lazy[right], x)
v[right] = apply(v[right], x, length[right])
left >>= 1; right >>= 1
self._propagate_bottomup(indices)
# returns answer for the query interval [l, r)
def fold(self, l, r):
self._propagate_topdown(*self._indices(l, r))
e, N, v, op = self.e, self.N, self.v, self.op
# calculate the answer for the query interval [l, r)
left = l + N; right = r + N
L = R = e
while left < right:
if left & 1: # self.v[left] is the right child
L = op(L, v[left])
left += 1
if right & 1: # self.v[right-1] is the left child
right -= 1
R = op(v[right], R)
left >>= 1; right >>= 1
return op(L, R)
N, Q = map(int, input().split())
op = lambda x, y: x + y
apply = lambda x, f, l: x + f*l
comp = lambda f, g: f + g
e = 0
identity = 0
A = [e] * N
lpsg = LazyPropSegmentTree(A, op, apply, comp, e, identity)
ans = []
for _ in range(Q):
t, *arg, = map(int, input().split())
if t == 0:
s, t, x = arg
lpsg.update(s-1, t, x)
else:
s, t = arg
ans.append(lpsg.fold(s-1, t))
print('\n'.join(map(str, ans)))
``` | output | 1 | 8,362 | 5 | 16,725 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,363 | 5 | 16,726 |
"Correct Solution:
```
#!/usr/bin/env python3
# DSL_2_G: RSQ and RAQ
# Range Add Query and Range Sum Query
class BinaryIndexedTree:
def __init__(self, n):
self.size = n
self.bit = [0] * (self.size+1)
def add(self, i, v):
while i <= self.size:
self.bit[i] += v
i += (i & -i)
def sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= (i & -i)
return s
class RangeQuery:
def __init__(self, n):
self.size = n
self.bit1 = BinaryIndexedTree(n+1)
self.bit2 = BinaryIndexedTree(n+1)
def add(self, i, j, v):
self.bit1.add(i, v * -i)
self.bit1.add(j+1, v * (j+1))
self.bit2.add(i, v)
self.bit2.add(j+1, -v)
def sum(self, i, j):
s = self.bit1.sum(j+1) + (j+1)*self.bit2.sum(j+1)
s -= self.bit1.sum(i) + i*self.bit2.sum(i)
return s
def run():
n, q = [int(i) for i in input().split()]
r = RangeQuery(n)
for _ in range(q):
com, *args = input().split()
if com == '0':
s, t, x = [int(i) for i in args]
r.add(s, t, x)
elif com == '1':
s, t = [int(i) for i in args]
print(r.sum(s, t))
if __name__ == '__main__':
run()
``` | output | 1 | 8,363 | 5 | 16,727 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,364 | 5 | 16,728 |
"Correct Solution:
```
# Binary Indexed Tree (Fenwick Tree)
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
# assert i > 0
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j=None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i-1)
def solve():
ans = []
N, Q = map(int, input().split())
data0 = BIT(N+1)
data1 = BIT(N+1)
for i in range(Q):
p,*y = map(int, input().split())
if p==0:
s,t,x = y
data0.add(s,-x*(s-1))
data0.add(t+1,x*t)
data1.add(s,x)
data1.add(t+1,-x)
else:
s,t = y
ans.append(data1.sum(t)*t+data0.sum(t)-data1.sum(s-1)*(s-1)-data0.sum(s-1))
return ans
print(*solve(),sep='\n')
``` | output | 1 | 8,364 | 5 | 16,729 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,365 | 5 | 16,730 |
"Correct Solution:
```
class BinaryIndexedTree():
def __init__(self, n):
self.n = n
self.dat = [0] * (n + 1)
def sum(self, i):
s = 0
while i:
s += self.dat[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.n:
self.dat[i] += x
i += i & -i
N, Q = [int(_) for _ in input().split()]
Query = [input().split() for _ in range(Q)]
BIT0 = BinaryIndexedTree(N + 1)
BIT1 = BinaryIndexedTree(N + 1)
#sum'([0,p))=sum([0,p)) if p<a
#sum'([0,p))=sum([0,p))+p*x-(a-1)*x if a<=p<b
#sum'([0,p))=sum([0,p))+(b-(a-1))*x if b<=p
for query in Query:
c, *array = query
array = list(map(int, array))
if c == '1':
a, b = array
a -= 1
res = 0
res += b * BIT1.sum(b) + BIT0.sum(b)
res -= a * BIT1.sum(a) + BIT0.sum(a)
print(res)
else:
a, b, x = array
b += 1
BIT1.add(a, x)
BIT0.add(a, -(a - 1) * x)
BIT1.add(b, -x)
BIT0.add(b, (b - 1) * x)
``` | output | 1 | 8,365 | 5 | 16,731 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,366 | 5 | 16,732 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
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 pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
class RangeAddSum():
def __init__(self, n):
i = 1
while 2**i <= n:
i += 1
self.N = 2**i
self.A = [0] * (self.N*2)
self.B = [0] * (self.N*2)
def add(self, a, b, x, k, l, r):
def ina(k, l, r):
if a <= l and r <= b:
self.A[k] += x
elif l < b and a < r:
self.B[k] += (min(b, r) - max(a, l)) * x
m = (l+r) // 2
ina(k*2+1, l, m)
ina(k*2+2, m, r)
ina(k, l, r)
def query(self, a, b, k, l, r):
def inq(k, l, r):
if b <= l or r <= a:
return 0
if a <= l and r <= b:
return self.A[k] * (r - l) + self.B[k]
res = (min(b, r) - max(a, l)) * self.A[k]
m = (l+r) // 2
res += inq(k*2+1, l, m)
res += inq(k*2+2, m, r)
return res
return inq(k, l, r)
def main():
n,q = LI()
qa = [LI() for _ in range(q)]
ras = RangeAddSum(n)
rr = []
for qi in qa:
s = qi[1] - 1
t = qi[2]
if qi[0] == 0:
x = qi[3]
ras.add(s, t, x, 0, 0, n)
else:
rr.append(ras.query(s, t, 0, 0, n))
return JA(rr, "\n")
# start = time.time()
print(main())
# pe(time.time() - start)
``` | output | 1 | 8,366 | 5 | 16,733 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,367 | 5 | 16,734 |
"Correct Solution:
```
class BinaryIndexedTree:
def __init__(self, n):
self.a = [0] * (n + 1)
self.n = n
def add(self, i, x):
while i <= self.n:
self.a[i] += x
i += i & -i
def sum(self, i):
ret = 0
while i > 0:
ret += self.a[i]
i -= i & -i
return ret
class Solve:
def __init__(self, n):
self.n = n
self.p = BinaryIndexedTree(n + 1)
self.q = BinaryIndexedTree(n + 1)
def add(self, s, t, x):
t += 1
self.p.add(s, -x * s)
self.p.add(t, x * t)
self.q.add(s, x)
self.q.add(t, -x)
def get_sum(self, s, t):
t += 1
return self.p.sum(t) + self.q.sum(t) * t - \
self.p.sum(s) - self.q.sum(s) * s
def dump(self):
print(*(self.get_sum(i, i) for i in range(self.n + 1)))
n, q = map(int, input().split())
st = Solve(n)
buf = []
for _ in range(q):
query = input().split()
if query[0] == '0':
st.add(*map(int, query[1:]))
else:
buf.append(st.get_sum(*map(int, query[1:])))
print('\n'.join(map(str, buf)))
``` | output | 1 | 8,367 | 5 | 16,735 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,368 | 5 | 16,736 |
"Correct Solution:
```
class BinaryIndexedTree(): #1-indexed
def __init__(self, n):
self.n = n
self.tree = [0 for _ in range(n + 1)]
def sum(self, idx):
res = 0
while idx:
res += self.tree[idx]
idx -= idx & -idx
return res
def add(self, idx, x):
while idx <= self.n:
self.tree[idx] += x
idx += idx & -idx
def bisect_left(self, x):
if x <= 0: return 0
res, tmp = 0, 2**((self.n).bit_length() - 1)
while tmp:
if res + tmp <= self.n and self.tree[res + tmp] < x:
x -= self.tree[res + tmp]
res += tmp
tmp >>= 1
return res + 1
class RAQandRSQ():
def __init__(self, n):
self.bit1 = BinaryIndexedTree(n)
self.bit2 = BinaryIndexedTree(n)
def add(self, lt, rt, x):
self.bit1.add(lt, -x * (lt - 1))
self.bit1.add(rt, x * (rt - 1))
self.bit2.add(lt, x)
self.bit2.add(rt, -x)
def sum(self, lt, rt):
rsum = self.bit2.sum(rt - 1) * (rt - 1) + self.bit1.sum(rt - 1)
lsum = self.bit2.sum(lt - 1) * (lt - 1) + self.bit1.sum(lt - 1)
return rsum - lsum
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())
R = RAQandRSQ(N)
res = []
for _ in range(Q):
q, *p = map(int, input().split())
if q == 0:
s, t, x = p
R.add(s, t + 1, x)
else:
s, t = p
res.append(R.sum(s, t + 1))
print('\n'.join(map(str, res)))
``` | output | 1 | 8,368 | 5 | 16,737 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4 | instruction | 0 | 8,369 | 5 | 16,738 |
"Correct Solution:
```
def _gidx(l, r, treesize):
'''
lazy propagation用idx生成器 木の下から生成される。1based-indexなので注意.(使うときは-1するとか)
もとの配列において[l,r)を指定したときに更新すべきidxをyieldする
treesizeは多くの場合self.num
'''
L, R = l + treesize, r + treesize
lm = (L // (L & -L)) >> 1 # これで成り立つの天才か?
rm = (R // (R & -R)) >> 1
while L < R:
if R <= rm:
yield R
if L <= lm:
yield L
L >>= 1
R >>= 1
while L: # Rでもいいけどね
yield L
L >>= 1
import operator
class SegmentTreeForRSQandRAQ: # 区間合計(ホントは何でも良い)クエリ と 区間加算クエリを扱うことにする
def __init__(self, ls: list, segfunc=operator.add, identity_element=0, lazy_ide=0):
'''
セグ木 もしかしたらバグがあるかも
一次元のリストlsを受け取り初期化する。O(len(ls))
区間のルールはsegfuncによって定義される
identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0
[単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83)
'''
self.ide = identity_element
self.lide = lazy_ide # lazy用単位元
self.func = segfunc
n = len(ls)
self.num = 2 ** (n - 1).bit_length() # n以上の最小の2のべき乗
self.tree = [self.ide] * (2 * self.num) # 関係ない値を-1においてアクセスを許すと都合が良い
self.lazy = [self.lide] * (2 * self.num) # 遅延配列
for i, l in enumerate(ls): # 木の葉に代入
self.tree[i + self.num - 1] = l
for i in range(self.num - 2, -1, -1): # 子を束ねて親を更新
self.tree[i] = segfunc(self.tree[2 * i + 1], self.tree[2 * i + 2])
def _lazyprop(self, *ids):
'''
遅延評価用の関数
- self.tree[i] に self.lazy[i]の値を伝播させて遅延更新する
- 子ノードにself.lazyの値を伝播させる **ここは問題ごとに書き換える必要がある**
- self.lazy[i]をリセットする
'''
for i in reversed(ids):
i -= 1 # to 0basedindex
v = self.lazy[i]
if v == self.lide:
continue
#########################################################
# この4つの配列をどう更新するかは問題によって異なる
self.tree[2 * i + 1] += v >> 1 # 区間加算クエリなので
self.tree[2 * i + 2] += v >> 1
self.lazy[2 * i + 1] += v >> 1
self.lazy[2 * i + 2] += v >> 1
#########################################################
self.lazy[i] = self.lide # 遅延配列を空に戻す
def update(self, l, r, x):
'''
[l,r)番目の要素をxを適応するクエリを行う O(logN)
'''
# 1, 根から区間内においてlazyの値を伝播しておく(self.treeの値が有効になる)
ids = tuple(_gidx(l, r, self.num))
#########################################################
# 区間加算queryのような操作の順序が入れ替え可能な場合これをする必要なないが多くの場合でしたほうがバグが少なく(若干遅くなる)
# self._lazyprop(*ids)
#########################################################
# 2, 区間に対してtree,lazyの値を更新 (treeは根方向に更新するため、lazyはpropで葉方向に更新するため)
if r <= l:
return ValueError('invalid index (l,rがありえないよ)')
l += self.num
r += self.num
while l < r:
#########################################################
# ** 問題によって値のセットの仕方も変えるべし**
if r & 1:
r -= 1
self.tree[r - 1] += x
self.lazy[r - 1] += x
if l & 1:
self.tree[l - 1] += x
self.lazy[l - 1] += x
l += 1
#########################################################
x <<= 1 # 区間加算クエリでは上段では倍倍になるはずだよね
l >>= 1
r >>= 1
# 3, 伝播させた区間について下からdataの値を伝播する
for i in ids:
i -= 1 # to 0based
#########################################################
# 関数の先頭でlazy propを省略した場合は、現在のノードにlazyが反映されていないことがある
# lazyを省略するならここを慎重に書き換えなければならない
self.tree[i] = self.func(
self.tree[2 * i + 1], self.tree[2 * i + 2]) + self.lazy[i]
#########################################################
def query(self, l, r):
'''
区間[l,r)に対するクエリをO(logN)で処理する。例えばその区間の最小値、最大値、gcdなど
'''
if r <= l:
return ValueError('invalid index (l,rがありえないよ)')
# 1, 根からにlazyの値を伝播させる
self._lazyprop(*_gidx(l, r, self.num))
# 2, 区間[l,r)の最小値を求める
l += self.num
r += self.num
res = self.ide
while l < r: # 右から寄りながら結果を結合していくイメージ
if r & 1:
r -= 1
res = self.func(res, self.tree[r - 1])
if l & 1:
res = self.func(res, self.tree[l - 1])
l += 1
l >>= 1
r >>= 1
return res
n, q = map(int, input().split())
ls = [0] * n
seg = SegmentTreeForRSQandRAQ(ls)
for _ in range(q):
cmd, *tmp = map(int, input().split())
if cmd == 0:
s, t, x = tmp
seg.update(s - 1, t, x)
else:
s, t = tmp
print(seg.query(s - 1, t))
``` | output | 1 | 8,369 | 5 | 16,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def set_depth(depth):
global DEPTH, SEGTREE_SIZE, NONLEAF_SIZE
DEPTH = depth
SEGTREE_SIZE = 1 << DEPTH
NONLEAF_SIZE = 1 << (DEPTH - 1)
def set_width(width):
set_depth((width - 1).bit_length() + 1)
def get_size(pos):
ret = pos.bit_length()
return (1 << (DEPTH - ret))
def up(pos):
pos += SEGTREE_SIZE // 2
return pos // (pos & -pos)
def up_propagate(table, pos, binop):
while pos > 1:
pos >>= 1
table[pos] = binop(
table[pos * 2],
table[pos * 2 + 1]
)
def force_down_propagate(
action_table, value_table, pos,
action_composite, action_force, action_unity
):
max_level = pos.bit_length() - 1
size = NONLEAF_SIZE
for level in range(max_level):
size //= 2
i = pos >> (max_level - level)
action = action_table[i]
if action != action_unity:
# action_table[i * 2] = action_composite(
# action, action_table[i * 2])
# action_table[i * 2 + 1] = action_composite(
# action, action_table[i * 2 + 1])
action_table[i * 2] += action
action_table[i * 2 + 1] += action
action_table[i] = action_unity
# value_table[i * 2] = action_force(
# action, value_table[i * 2], size)
# value_table[i * 2 + 1] = action_force(
# action, value_table[i * 2 + 1], size)
value_table[i * 2] += action * size
value_table[i * 2 + 1] += action * size
def force_range_update(
value_table, action_table, left, right,
action, action_force, action_composite, action_unity
):
"""
action_force: action, value, cell_size => new_value
action_composite: new_action, old_action => composite_action
"""
left += NONLEAF_SIZE
right += NONLEAF_SIZE
while left < right:
if left & 1:
value_table[left] = action_force(
action, value_table[left], get_size(left))
action_table[left] = action_composite(action, action_table[left])
left += 1
if right & 1:
right -= 1
value_table[right] = action_force(
action, value_table[right], get_size(right))
action_table[right] = action_composite(action, action_table[right])
left //= 2
right //= 2
def range_reduce(table, left, right, binop, unity):
ret_left = unity
ret_right = unity
left += NONLEAF_SIZE
right += NONLEAF_SIZE
while left < right:
if left & 1:
ret_left = binop(ret_left, table[left])
left += 1
if right & 1:
right -= 1
ret_right = binop(table[right], ret_right)
left //= 2
right //= 2
return binop(ret_left, ret_right)
def lazy_range_update(
action_table, value_table, start, end,
action, action_composite, action_force, action_unity, value_binop):
"update [start, end)"
L = up(start)
R = up(end)
force_down_propagate(
action_table, value_table, L,
action_composite, action_force, action_unity)
force_down_propagate(
action_table, value_table, R,
action_composite, action_force, action_unity)
# print("action", file=sys.stderr)
# debugprint(action_table)
# print("value", file=sys.stderr)
# debugprint(value_table)
# print(file=sys.stderr)
force_range_update(
value_table, action_table, start, end,
action, action_force, action_composite, action_unity)
up_propagate(value_table, L, value_binop)
up_propagate(value_table, R, value_binop)
def lazy_range_reduce(
action_table, value_table, start, end,
action_composite, action_force, action_unity,
value_binop, value_unity
):
"reduce [start, end)"
force_down_propagate(
action_table, value_table, up(start),
action_composite, action_force, action_unity)
force_down_propagate(
action_table, value_table, up(end),
action_composite, action_force, action_unity)
return range_reduce(value_table, start, end, value_binop, value_unity)
def debugprint(xs, minsize=0, maxsize=None):
global DEPTH
strs = [str(x) for x in xs]
if maxsize != None:
for i in range(NONLEAF_SIZE, SEGTREE_SIZE):
strs[i] = strs[i][:maxsize]
s = max(len(s) for s in strs[NONLEAF_SIZE:])
if s > minsize:
minsize = s
result = ["|"] * DEPTH
level = 0
next_level = 2
for i in range(1, SEGTREE_SIZE):
if i == next_level:
level += 1
next_level *= 2
width = ((minsize + 1) << (DEPTH - 1 - level)) - 1
result[level] += strs[i].center(width) + "|"
print(*result, sep="\n", file=sys.stderr)
def main():
from operator import add
# parse input
N, Q = map(int, input().split())
set_width(N)
value_unity = 0
value_table = [value_unity] * SEGTREE_SIZE
value_binop = add
action_unity = 0
action_table = [action_unity] * SEGTREE_SIZE
def action_force(action, value, size):
return action * size + value
def action_composite(new_action, old_action):
return new_action + old_action
for _time in range(Q):
q, *args = map(int, input().split())
if q == 0:
# add
s, t, value = args
lazy_range_update(
action_table, value_table, s - 1, t,
value, action_composite, action_force, action_unity, value_binop)
else:
# getSum
s, t = args
print(lazy_range_reduce(
action_table, value_table, s - 1, t,
action_composite, action_force, action_unity, value_binop, value_unity))
# print("action", file=sys.stderr)
# debugprint(action_table)
# print("value", file=sys.stderr)
# debugprint(value_table)
# print(file=sys.stderr)
# tests
T1 = """
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
4
8
"""
T2 = """
4 3
1 1 4
0 1 4 1
1 1 4
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
0
4
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g)
def as_input(s):
"use in test, use given string as input file"
import io
global read, input
f = io.StringIO(s.strip())
def input():
return bytes(f.readline(), "ascii")
def read():
return bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
``` | instruction | 0 | 8,370 | 5 | 16,740 |
Yes | output | 1 | 8,370 | 5 | 16,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
class BinaryIndexedTree(object):
def __init__(self, n: int) -> None:
self.size = n
self.bit = [0] * (self.size + 1)
def add(self, i: int, v: int) -> None:
while (i <= self.size):
self.bit[i] += v
i += (i & -i) # i & -i picks the lowest 1 bit of i.
def sum(self, i: int) -> int:
s = 0
while (i > 0):
s += self.bit[i]
i -= (i & -i)
return s
class RangeQuery(object):
def __init__(self, n: int) -> None:
self.size = n
self.bit1 = BinaryIndexedTree(n + 1)
self.bit2 = BinaryIndexedTree(n + 1)
def add(self, i: int, j: int, v: int) -> None:
self.bit1.add(i, v * -i)
self.bit1.add(j + 1, v * (j + 1))
self.bit2.add(i, v)
self.bit2.add(j + 1, -v)
def sum(self, i: int, j: int) -> int:
s = self.bit1.sum(j + 1) + (j + 1) * self.bit2.sum(j + 1)
s -= self.bit1.sum(i) + i * self.bit2.sum(i)
return s
if __name__ == "__main__":
n, q = map(lambda x: int(x), input().split())
rq = RangeQuery(n)
for _ in range(q):
com, *v = map(lambda x: int(x), input().split())
if (0 == com):
rq.add(v[0], v[1], v[2])
else:
print(rq.sum(v[0], v[1]))
``` | instruction | 0 | 8,371 | 5 | 16,742 |
Yes | output | 1 | 8,371 | 5 | 16,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
import sys,queue,math,copy,itertools,bisect
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
N,Q = LI()
N0 = 2 ** (N).bit_length()
data = [0 for _ in range(N0*2)]
lazy = [0 for _ in range(N0*2)]
def gindex(l, r):
L = l + N0; R = r + N0
lm = (L // (L & -L)) // 2
rm = (R // (R & -R)) // 2
while L < R:
if R <= rm:
yield R-1
if L <= lm:
yield L-1
L //= 2; R //= 2
while L:
yield L-1
L //= 2
def eval(*ids):
for i in reversed(ids):
v = lazy[i]
if v == 0: continue
lazy[i*2+1] += v // 2
lazy[i*2+2] += v // 2
data[i*2+1] += v // 2
data[i*2+2] += v // 2
lazy[i] = 0
def data_add(l,r,x):
*ids, = gindex(l,r)
eval(*ids)
L = l + N0; R = r + N0
n = 1
while L < R:
if R % 2:
R -= 1
lazy[R-1] += x * n
data[R-1] += x * n
if L % 2:
lazy[L-1] += x * n
data[L-1] += x * n
L += 1
L //= 2; R //= 2; n *= 2
for i in ids:
data[i] = data[i*2+1] + data[i*2+2]
def data_get(l,r):
eval(*gindex(l,r))
L = l + N0; R = r + N0
ret = 0
while L < R:
if R % 2:
R -= 1
ret += data[R-1]
if L % 2:
ret += data[L-1]
L += 1
L //= 2; R //= 2
return ret
for _ in range(Q):
q = LI()
if q[0] == 0:
data_add(q[1],q[2]+1,q[3])
else:
print (data_get(q[1],q[2]+1))
``` | instruction | 0 | 8,372 | 5 | 16,744 |
Yes | output | 1 | 8,372 | 5 | 16,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
import sys
input = sys.stdin.readline
class BIT():
"""区間加算、区間取得クエリをそれぞれO(logN)で答える
add: 区間[l, r)にvalを加える
get_sum: 区間[l, r)の和を求める
l, rは0-indexed
"""
def __init__(self, n):
self.n = n
self.bit0 = [0] * (n + 1)
self.bit1 = [0] * (n + 1)
def _add(self, bit, i, val):
i = i + 1
while i <= self.n:
bit[i] += val
i += i & -i
def _get(self, bit, i):
s = 0
while i > 0:
s += bit[i]
i -= i & -i
return s
def add(self, l, r, val):
"""区間[l, r)にvalを加える"""
self._add(self.bit0, l, -val * l)
self._add(self.bit0, r, val * r)
self._add(self.bit1, l, val)
self._add(self.bit1, r, -val)
def get_sum(self, l, r):
"""区間[l, r)の和を求める"""
return self._get(self.bit0, r) + r * self._get(self.bit1, r) \
- self._get(self.bit0, l) - l * self._get(self.bit1, l)
n, q = map(int, input().split())
query = [list(map(int, input().split())) for i in range(q)]
bit = BIT(n)
for i in range(q):
if query[i][0] == 0:
_, l, r, x = query[i]
bit.add(l-1, r, x)
else:
_, l, r = query[i]
print(bit.get_sum(l-1, r))
``` | instruction | 0 | 8,373 | 5 | 16,746 |
Yes | output | 1 | 8,373 | 5 | 16,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
from math import log2, ceil
class SegmentTree:
def __init__(self, n):
tn = 2 ** ceil(log2(n))
self.a = [0] * (tn * 2)
self.tn = tn
def get_sum(self, s, t):
return self.__get_sum(1, 1, self.tn, s, t)
def __get_sum(self, c, l, r, s, t):
if l == r:
return self.a[c]
mid = (l + r) // 2
if t <= mid:
return self.a[c] * (t - s + 1) + self.__get_sum(c * 2, l, mid, s, t)
elif s > mid:
return self.a[c] * (t - s + 1) + self.__get_sum(c * 2 + 1, mid + 1, r, s, t)
else:
return self.a[c] * (t - s + 1) + \
self.__get_sum(c * 2, l, mid, s, mid) + \
self.__get_sum(c * 2 + 1, mid + 1, r, mid + 1, t)
def add(self, s, t, x):
self.__add(1, 1, self.tn, s, t, x)
def __add(self, c, l, r, s, t, x):
if l == s and r == t:
self.a[c] += x
return
mid = (l + r) // 2
if t <= mid:
self.__add(c * 2, l, mid, s, t, x)
elif s > mid:
self.__add(c * 2 + 1, mid + 1, r, s, t, x)
else:
self.__add(c * 2, l, mid, s, mid, x)
self.__add(c * 2 + 1, mid + 1, r, mid + 1, t, x)
n, q = map(int, input().split())
st = SegmentTree(n)
buf = []
for _ in range(q):
query = input().split()
if query[0] == '0':
st.add(*map(int, query[1:]))
else:
buf.append(st.get_sum(*map(int, query[1:])))
print('\n'.join(map(str, buf)))
``` | instruction | 0 | 8,374 | 5 | 16,748 |
No | output | 1 | 8,374 | 5 | 16,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 0 ≤ x < 1000
Input
n q
query1
query2
:
queryq
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:
0 s t x
or
1 s t
The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).
Output
For each getSum operation, print the sum;
Examples
Input
3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3
Output
4
8
Input
4 3
1 1 4
0 1 4 1
1 1 4
Output
0
4
Submitted Solution:
```
def f(l):
for i in range(1, len(l)):
l[i] += l[i-1]
return l
n, q = map(int, input().split())
A = [0] * (n+2)
for i in range(q):
query = list(map(int, input().split()))
if query[0] == 0:
s, t, x = query[1:]
A[s] += x
A[t+1] -= x
else:
s, t = query[1:]
sum = f(f(A[:]))
print(sum[t] - sum[s-1])
``` | instruction | 0 | 8,375 | 5 | 16,750 |
No | output | 1 | 8,375 | 5 | 16,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ∈ [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 8) — the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 ≤ a_{x, y} ≤ 10^9).
Output
Print two integers i and j (1 ≤ i, j ≤ n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
import sys
from collections import defaultdict
reader = (map(int, line.split()) for line in sys.stdin)
input = reader.__next__
n, m = input()
# n, m = 3 * 10 ** 5, 8
vals = set()
locs = defaultdict(list)
for i in range(n):
for pos, v in enumerate(input()):
vals.add(v)
locs[v].append((pos, i))
masks = [0] * n
full = (1<<m) - 1
met = {0:0}
for v in sorted(vals, reverse=True):
for pos, i in locs[v]:
curr_mask = masks[i] = masks[i] | (1<<pos)
met[curr_mask] = i
complement = full ^ curr_mask
if complement in met:
print(i+1, met[complement]+1)
sys.exit()
``` | instruction | 0 | 8,487 | 5 | 16,974 |
Yes | output | 1 | 8,487 | 5 | 16,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ∈ [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 8) — the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 ≤ a_{x, y} ≤ 10^9).
Output
Print two integers i and j (1 ≤ i, j ≤ n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
from sys import stdin
def solve(x: int) -> bool:
global ans
dp = {}
for i in range(n):
temp = 0
for j in range(m):
if a[i][j] >= x:
temp = temp | (1 << j)
dp[temp] = i
for aa, bb in dp.items():
for cc, dd in dp.items():
if aa | cc == 2 ** m - 1:
ans = (bb + 1, dd + 1)
return True
return False
ans = (-1, -1)
n, m = map(int, stdin.readline().split())
a = []
for i in range(n):
a.append(list(map(int, stdin.readline().split())))
l, r = 0, 10 ** 9
while l <= r:
mid = (l + r) // 2
if solve(mid):
l = mid + 1
else:
r = mid - 1
print(*ans)
``` | instruction | 0 | 8,489 | 5 | 16,978 |
Yes | output | 1 | 8,489 | 5 | 16,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ∈ [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 8) — the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 ≤ a_{x, y} ≤ 10^9).
Output
Print two integers i and j (1 ≤ i, j ≤ n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m = list(map(int,input().split()))
mat = []
for i in range(n):
mat.append(list(map(int,input().split())))
d = {}
for i in range(n):
arr1 = mat[i]
for j in range(i+1,n):
arr2 = mat[j]
temp = []
for k in range(m):
temp.append(max(arr1[k],arr2[k]))
key = str(i)+':'+str(j)
d[key] = min(temp)
cur = -1
u,v = -1,-1
for i in d:
if d[i]>cur:
u,v = list(map(int,i.split(':')))
print(u+1,v+1)
``` | instruction | 0 | 8,491 | 5 | 16,982 |
No | output | 1 | 8,491 | 5 | 16,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ∈ [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 8) — the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 ≤ a_{x, y} ≤ 10^9).
Output
Print two integers i and j (1 ≤ i, j ≤ n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
###########################
# Sorted list
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
# self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
# self.lista[a] += self.lista[b]
# self.lista[b] = []
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
#
# to find factorial and ncr
# tot = 200005
# mod = 10**9 + 7
# fac = [1, 1]
# finv = [1, 1]
# inv = [0, 1]
#
# for i in range(2, tot + 1):
# fac.append((fac[-1] * i) % mod)
# inv.append(mod - (inv[mod % i] * (mod // i) % mod))
# finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def arr1d(n, v):
return [v] * n
def arr2d(n, m, v):
return [[v] * m for _ in range(n)]
def arr3d(n, m, p, v):
return [[[v] * p for _ in range(m)] for i in range(n)]
def solve():
n, m = sep()
ar = []
for i in range(n):
ar.append(lis())
def isvalid(k):
val = [0] * (2 ** m )
for i in range(n):
temp = 0
for j in range(m):
if ar[i][j] >= k:
temp += (1 << j)
val[temp] = 1
valu = []
for i in range(2 ** m ):
if val[i] == 1: valu.append(i)
req = 2 ** m - 1
for i in valu:
for j in valu:
if (i | j == req):
return 1
return 0
def search():
l = 0
r = 10 ** 9 +1
for i in range(30):
# print(l,r)
if l == r:
return l
m = (l + r) // 2
tempc=isvalid(m)
if tempc and not isvalid(m + 1):
return m
if tempc:
l = m
else:
r = m - 1
return m
k=search()
# print(isvalid(k))
val = defaultdict(int)
for i in range(n):
temp = 0
for j in range(m):
if ar[i][j] >= k:
temp += (1 << j)
val[(temp)]=i
req = 2 ** m - 1
for i in val.keys():
for j in val.keys():
if (i | j == req):
print(val[i]+1,val[j]+1)
return
solve()
#testcase(int(inp()))
``` | instruction | 0 | 8,493 | 5 | 16,986 |
No | output | 1 | 8,493 | 5 | 16,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
t = int(input())
for i in range(t):
n, k = map(int, input().split())
if (n % 2 != 0):
if (k % 2 == 0 or n < k):
print("NO")
else:
print("YES")
print("1 "*(k-1) + str(n-k+1))
else:
if ((n-k+1) % 2 != 0 and n >= k):
print("YES")
print("1 "*(k-1) + str(n-k+1))
elif ((n-2*(k-1))%2 == 0 and n >= 2*k):
print("YES")
print("2 "*(k-1) + str(n-2*(k-1)))
else:
print("NO")
``` | instruction | 0 | 8,518 | 5 | 17,036 |
Yes | output | 1 | 8,518 | 5 | 17,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
t = int(input())
for i in range(t):
n, k = map(int, input().split())
if n % 2 == 0:
if 2 * k <= n:
ans = [2] * (k - 1)
ans.append(n - 2 * (k - 1))
else:
if k % 2 == 0:
if k > n:
ans = []
else:
ans = [1] * (k - 1)
ans.append(n - (k - 1))
else:
ans = []
else:
if k % 2 == 0:
ans = []
else:
if k > n:
ans = []
else:
ans = [1] * (k - 1)
ans.append(n - (k - 1))
if len(ans):
print('YES')
print(*ans)
else:
print('NO')
``` | instruction | 0 | 8,519 | 5 | 17,038 |
Yes | output | 1 | 8,519 | 5 | 17,039 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
import sys, heapq
from collections import *
from functools import lru_cache
sys.setrecursionlimit(10**6)
def main():
# sys.stdin = open('input.txt', 'r')
t = int(input())
for _ in range(t):
n, k = map(int, input().split(' '))
# n = int(input())
nn, kk = n&1, k&1
flag, res = False, []
if nn ^ kk == 0:
if n >= k:
flag = True
res = [n-k+1]+[1]*(k-1)
elif nn == 0 and kk == 1:
if n >= k*2:
flag = True
res = [n-k*2+2]+[2]*(k-1)
if len(res) > 0:
print("YES")
print(' '.join(map(str,res)))
else:
print("NO")
if __name__ == "__main__":
main()
``` | instruction | 0 | 8,520 | 5 | 17,040 |
Yes | output | 1 | 8,520 | 5 | 17,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
t=int(input())
for s in range(t):
n,k=list(map(int,input().split(" ")))
y=n//2
if n<k:
print("NO")
else:
if n%2!=0 and k%2==0:
print("NO")
#break
if (n%2==0 and k%2==0) or (n%2!=0 and k%2!=0):
print("YES")
c=0
for i in range(1,k,1):
c+=1
print(1,end=" ")
x=n-c
print(x)
#break
if n%2==0 and k%2!=0:
if k*2<=n:
print("YES")
c=0
for i in range(1,k,1):
c+=2
print(2,end=" ")
x=n-c
print(x)
#break
else:
print("NO")
``` | instruction | 0 | 8,521 | 5 | 17,042 |
Yes | output | 1 | 8,521 | 5 | 17,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
'''input
8
16 15
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
'''
from collections import defaultdict as dd
from collections import Counter as ccd
from itertools import permutations as pp
from itertools import combinations as cc
from random import randint as rd
from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq as hq
from math import gcd
'''
Author : dhanyaabhirami
Hardwork beats talent if talent doesn't work hard
'''
'''
Stuck?
See github resources
Derive Formula
Kmcode blog
CP Algorithms Emaxx
'''
mod=pow(10,9) +7
def inp(flag=0):
if flag==0:
return list(map(int,input().strip().split(' ')))
else:
return int(input())
# Code credits
# assert(debug()==true)
# for _ in range(int(input())):
t=inp(1)
while t:
t-=1
n,k=inp()
possible = True
if n==k:
ans = [1]*k
elif n%2==1 and k%2==0:
possible = False
else:
if n%2 == 1:
if n-k+1>0 and (n-k+1)%2==1:
ans = [1]*(k-1)
ans.append(n-k+1)
else:
possible = False
else:
if n-2*(k-1)>0 and (n-2*(k-1))%2==0:
ans = [2]*(k-1)
ans.append(n-2*(k-1))
else:
possible = False
if possible:
print('YES')
print(*ans)
else:
print('NO')
``` | instruction | 0 | 8,522 | 5 | 17,044 |
No | output | 1 | 8,522 | 5 | 17,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
for _ in range(int(input())):
n,k=map(int,input().split())
if n%2>0 and k%2==0:print("NO")
elif n%2==0 and k%2==0:
print("YES")
for i in range(k-1):print(1,end=' ')
print(n-(k-1))
elif n%2==0 and k%2>0:
if n%k==0:
print("YES")
for i in range(k):print(n//k)
print()
elif n//k>=2:
print("YES")
for i in range(k-1):print(2,end=' ')
print(n-(2*(k-1)))
else:print("NO")
elif n%2>0 and k%2>0:
if k<=n:
print("YES")
for i in range(k-1):print(1,end=' ')
print(n-(k-1))
else:print("NO")
else:print("NO")
``` | instruction | 0 | 8,523 | 5 | 17,046 |
No | output | 1 | 8,523 | 5 | 17,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
for _ in range(int(input())):
n, k = list(map(int, input().split()))
if n % 2 == 1 and k % 2 == 0:
print('NO')
elif n % 2 == 0 and k % 2 == 1 and k * 2 > n:
print('NO')
else:
num = 1
if n % 2 == 0 and k % 2 == 1:
num = 2
ans = []
for i in range(k - 1):
ans.append(num)
ans.append(n - num * k + num)
print('YES')
print(*ans)
``` | instruction | 0 | 8,524 | 5 | 17,048 |
No | output | 1 | 8,524 | 5 | 17,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.
If such a representation does not exist, then report it.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.
Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).
Output
For each test case print:
* YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
* NO if the answer does not exist.
The letters in the words YES and NO can be printed in any case.
Example
Input
8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9
Output
YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120
Submitted Solution:
```
for i in range(int(input())):
n,k = map(int,input().split())
if (n-k-1)>0 and (n-k-1)%2!=0:
s = '1'*(k-1)
s = s.replace('',' ').strip()
print('YES')
print(s+" "+str(int(n-k+1)))
elif (n-2*(k-1))>0 and (n-2*(k-1))%2==0:
s = '2'*(k-1)
s = s.replace('',' ').strip()
print('YES')
print(s+' '+str(int(n-2*(k-1))))
else:
print('NO')
``` | instruction | 0 | 8,525 | 5 | 17,050 |
No | output | 1 | 8,525 | 5 | 17,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information.
<image>
It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 10^5) — the amount of numbers on the paper.
The second line of the input contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 9), where a_i is the i-th element of a.
The third line of the input contains the string s (1 ≤ |s| ≤ 3) — symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct.
Output
Print n numbers separated by n - 1 symbols — a mathematical expression with the greatest result. If there are multiple equally valid results — output any one of them.
Examples
Input
3
2 2 0
+-*
Output
2*2-0
Input
4
2 1 1 2
+*
Output
2+1+1+2
Note
The following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0".
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
s=input()
add_in='+' in s
multi_in='*' in s
sub_in='-' in s
s1=''
s2=''
if multi_in:
if add_in:
for x in range(n):
if l[x]!=0 and l[x]!=1:s1+=str(l[x])+'*'
else:s2+=str(l[x])+'+'
print(s2[:-1]+'+'+s1[:-1])
else:
if sub_in:
for x in range(n):
if l[x]!=0:s1+=str(l[x])+'*'
else:s2+=str(l[x])+'-'
print(s1[:-1]+'-'+s2[:-1])
else:
for x in range(n):s1+=str(l[x])+'*'
print(s1[:-1])
else:
if add_in:
for x in range(n):
s1+=str(l[x])+'+'
print(s1[:-1])
else:
l.sort(reverse=True)
for x in range(n):
s1+=str(l[x])+'-'
print(s1[:-1])
``` | instruction | 0 | 8,567 | 5 | 17,134 |
No | output | 1 | 8,567 | 5 | 17,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information.
<image>
It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 10^5) — the amount of numbers on the paper.
The second line of the input contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 9), where a_i is the i-th element of a.
The third line of the input contains the string s (1 ≤ |s| ≤ 3) — symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct.
Output
Print n numbers separated by n - 1 symbols — a mathematical expression with the greatest result. If there are multiple equally valid results — output any one of them.
Examples
Input
3
2 2 0
+-*
Output
2*2-0
Input
4
2 1 1 2
+*
Output
2+1+1+2
Note
The following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0".
Submitted Solution:
```
n = int(input())
ls = list(map(int, input().split(" ")))
string = input()
ans = ""
mul = False
add = False
sub = False
if "*" in string:
mul = True
if "+" in string:
add = True
if "-" in string:
sub = True
length = len(ls)
for i in range(length-1):
if(ls[i] != 0 and ls[i] != 1 and ls[i+1] != 0 and ls[i+1] != 1 and mul):
ans += str(ls[i])
ans += "*"
elif add:
ans += str(ls[i])
ans += "+"
else:
ans = str(ls[i])
ans += "-"
ans += str(ls[-1])
print(ans)
``` | instruction | 0 | 8,568 | 5 | 17,136 |
No | output | 1 | 8,568 | 5 | 17,137 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
def solve(x, a, b):
x.sort()
output = [0] * len(x)
output2 = [0] * len(x)
i, j = 0, len(x)-1
while i - j <= 0:
if x[i] + x[j] >= a:
output[j] = i
j -= 1
else:
output[i] = j + 1
i += 1
i, j = 0, len(x) - 1
while i-j <= 0:
if x[i] + x[j] <= b:
output2[i] = j
i += 1
else:
output2[j] = i-1
j -=1
answer = [o2 - o + 1 - (o <= i <= o2) for i, (o, o2) in enumerate(zip(output, output2))]
return sum(answer)//2
for _ in range(int(input())):
n,l,r=map(int,input().split())
a=list(map(int,input().split()))
ans=solve(a,l,r)
print(ans)
``` | instruction | 0 | 8,600 | 5 | 17,200 |
Yes | output | 1 | 8,600 | 5 | 17,201 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
from collections import defaultdict, Counter
from bisect import bisect, bisect_left
from math import sqrt, gcd, ceil, factorial
from heapq import heapify, heappush, heappop
MOD = 10**9 + 7
inf = float("inf")
ans_ = []
def nin():return int(input())
def ninf():return int(file.readline())
def st():return (input().strip())
def stf():return (file.readline().strip())
def read(): return list(map(int, input().strip().split()))
def readf():return list(map(int, file.readline().strip().split()))
# ans_ = ""
def f(arr, x):
n = len(arr)
i, j = 0, n-1
ans = 0
while i < j:
if arr[i]+arr[j] < x:
i += 1
ans += j-i+1
else:
j -= 1
return(ans)
# file = open("input.txt", "r")
def solve():
for _ in range(nin()):
n, l, r = read(); arr = read()
arr.sort()
ans_.append(f(arr, r+1) - f(arr, l))
# file.close()
solve()
for i in ans_:print(i)
``` | instruction | 0 | 8,601 | 5 | 17,202 |
Yes | output | 1 | 8,601 | 5 | 17,203 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
from sys import stdin, stdout
case = int(stdin.readline())
for c in range(case):
n, l, r = map(int, stdin.readline().split())
arr = list(map(int, stdin.readline().split()))
arr.sort()
if n == 1:
print(0)
continue
if arr[-1] + arr[-2] < l:
print(0)
continue
if arr[0] + arr[1] > r:
print(0)
continue
cnt1 = 0
lp = 0
rp = n-1
while 1:
if lp >= rp:
break
if arr[lp] + arr[rp] > r:
rp -= 1
else:
if rp == n-1:
cnt1 += (rp - lp)
lp += 1
elif arr[lp] + arr[rp+1] > r:
cnt1 += (rp - lp)
lp += 1
else:
rp += 1
cnt2 = 0
lp = 0
rp = n-1
while 1:
if lp >= rp:
break
if arr[lp] + arr[rp] >= l:
rp -= 1
else:
if rp == n-1:
cnt2 += (rp - lp)
lp += 1
elif arr[lp] + arr[rp+1] >= l:
cnt2 += (rp - lp)
lp += 1
else:
rp += 1
print(cnt1 - cnt2)
``` | instruction | 0 | 8,602 | 5 | 17,204 |
Yes | output | 1 | 8,602 | 5 | 17,205 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
t = int(input())
def do():
n, l, r = map(int, input().split())
nums = sorted(map(int, input().split()))
#print(nums)
ans = 0
for i in range(n - 1):
lmin = 0
start = i + 1
end = n - 1
mid = (start + end)//2
while start < end:
if nums[i] + nums[mid] < l :
start = mid + 1
else :
end = mid
mid = (start + end)//2
lmin = mid
if nums[lmin] + nums[i] < l:
continue
rmax = 0
start = i + 1
end = n - 1
mid = (start + end)//2
while start < end:
if nums[i] + nums[mid] > r:
end = mid - 1
else:
start = mid + 1
mid = (start + end)//2
rmax = mid
if nums[i] + nums[rmax] > r:
continue
#print( nums[i], lmin, rmax, "|", l, r, "|" )
ans += rmax - lmin + 1
print(ans)
for _ in range(t):
do()
``` | instruction | 0 | 8,603 | 5 | 17,206 |
No | output | 1 | 8,603 | 5 | 17,207 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
import array as arr
t = int(input())
def solve():
n,l,r = list(map(int,input().split()))
n = int(n)
l = int(l)
r = int(r)
a = arr.array('i')
a.extend(list(map(int,input().split())))
a = sorted(a)
i = len(a)-1
j = 0
pos = -1
flag = True
while(i>=j and flag):
mid = (i+j)//2
if(a[mid] == r):
pos = mid
flag = False
elif(a[mid] > r):
i = mid-1
else :
j = mid+1
if(flag):
pos = i
ctr = 0
while pos>=0 and a[pos] >= l//2:
for k in range(pos,-1,-1):
if (a[pos]+a[k] >= l and a[pos]+a[k]<=r):
ctr = ctr + 1
elif(a[pos]+a[k] < l):
break
pos = pos - 1
print(ctr)
for i in range(t):
solve()
``` | instruction | 0 | 8,604 | 5 | 17,208 |
No | output | 1 | 8,604 | 5 | 17,209 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s)
def invr():
return(map(int,input().split()))
x = inp()
for _ in range(x):
[n,l,r] = inlt()
a = inlt()
a.sort()
ans = 0
lp = 0
rp = n - 1
#print(a)
while(lp < rp):
#print(lp,rp, a[lp], a[rp])
if(a[lp] + a[rp] < l):
lp += 1
elif(a[lp] + a[rp] > r):
rp -= 1
else:
lower = lp
upper = rp
flag = 1
while(lower < upper):
mid = (lower+upper)//2
#print(lower,upper, mid)
if(a[mid + 1] + a[rp] > r and a[mid] + a[rp] <= r):
ans += mid - lp
flag = 0
break
elif(a[mid] + a[rp] > r):
upper = mid - 1
else:
lower = mid + 1
if(a[lower] + a[upper]< l):
flag = 0
if(flag):
ans += rp - lp
else:
ans += 1
rp -= 1
#print(ans)
#print("ans" + str(ans))
print(ans)
``` | instruction | 0 | 8,605 | 5 | 17,210 |
No | output | 1 | 8,605 | 5 | 17,211 |
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 of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
* i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.
Example
Input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
Output
2
7
0
1
Submitted Solution:
```
import sys
t = int(sys.stdin.readline())
while t:
t -= 1
n, l, r = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
arr.sort()
ans, A, B = 0, 0, 0
cnt = 0
for i in range(n):
lo, hi = i + 1, n - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] + arr[i] <= r:
ans = mid
lo = mid + 1
else:
hi = mid - 1
if ans != 0:
A += (ans - i)
ans = 0
lo, hi = i + 1, n - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] + arr[i] <= l - 1:
ans = mid
lo = mid + 1
else:
hi = mid - 1
if ans != 0:
B += (ans - i)
cnt += (A - B)
A, B = 0, 0
print(cnt)
``` | instruction | 0 | 8,606 | 5 | 17,212 |
No | output | 1 | 8,606 | 5 | 17,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++- | instruction | 0 | 8,610 | 5 | 17,220 |
Tags: greedy, math
Correct Solution:
```
n=int(input())
b=list(map(int,input().split()))
s=0
res=[]
j=n-1
while(j>=0):
if s<=0:
s+=b[j]
res.append(1)
else:
s-=b[j]
res.append(0)
j+=-1
res.reverse()
if s>=0:
for j in res:
if j:
print("+",end="")
else:
print("-",end="")
else:
for j in res:
if j:
print("-",end="")
else:
print("+",end="")
``` | output | 1 | 8,610 | 5 | 17,221 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++- | instruction | 0 | 8,612 | 5 | 17,224 |
Tags: greedy, math
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
if n == 1:
print('+')
elif n == 2:
print('-+')
else:
ans = ['+']
cur = arr[-1]
for i in range(n - 2, -1, -1):
if cur > 0:
cur -= arr[i]
ans.append('-')
else:
cur += arr[i]
ans.append('+')
ans.reverse()
if cur < 0:
for i in range(n):
if ans[i] == '-':
ans[i] = '+'
else:
ans[i] = '-'
print(''.join(ans))
``` | output | 1 | 8,612 | 5 | 17,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++- | instruction | 0 | 8,613 | 5 | 17,226 |
Tags: greedy, math
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, 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)
# -------------------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 binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
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------------------------------------
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
ans=['+']*n
for i in range(n-1,-1,-1):
if abs(s)<=l[0]:
break
if s-2*l[i]>=-l[0]:
s-=2*l[i]
ans[i]='-'
s=0
for i in range(n):
if ans[i]=='+':
s+=l[i]
else:
s-=l[i]
if s>0:
print(*ans,sep="")
else:
for i in range(n):
if ans[i]=='+':
ans[i]='-'
else:
ans[i]='+'
print(*ans,sep="")
``` | output | 1 | 8,613 | 5 | 17,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++- | instruction | 0 | 8,614 | 5 | 17,228 |
Tags: greedy, math
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
r = [0] * n
s = 0
for i in range(n - 1, -1, -1):
if abs(s + a[i]) <= a[i]:
s += a[i]
else:
s -= a[i]
r[i] = 1
if s<0:
print(''.join(['-', '+'][i] for i in r))
else:
print(''.join(['+', '-'][i] for i in r))
``` | output | 1 | 8,614 | 5 | 17,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++- | instruction | 0 | 8,616 | 5 | 17,232 |
Tags: greedy, math
Correct Solution:
```
def invert(s):
t = ''
for i in s:
if(i =='+'):
t += '-'
else:
t += '+'
#print(s,t)
return t
n = int(input())
if(n==1):
print('+')
exit()
a=list(map(int,input().split()))
cur = a[-1]
s = '+'
for i in range(n-2,0,-1):
if(cur > 0):
cur -= a[i]
s += '-'
else:
cur += a[i]
s += '+'
#print(s[::-1])
if(cur >= a[0]):
s += '-'
elif(abs(cur) <= a[0] and cur <= 0):
s += '+'
elif( 0 < cur < a[0]):
s=invert(s)
s += '+'
else:
s=invert(s)
s += '-'
print(s[::-1])
``` | output | 1 | 8,616 | 5 | 17,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(50001)]
pp=[]
def SieveOfEratosthenes(n=50000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(50001):
if prime[i]:
pp.append(i)
#---------------------------------running code------------------------------------------
n=int(input())
a=list(map(int,input().split()))
if n==1:
print('+')
sys.exit(0)
s=a[-1]
d=[0]*n
d[-1]=1
for i in range (n-2,-1,-1):
if s+a[i]>=-a[0] and s+a[i]<=a[0]:
d[i]=1
s+=a[i]
elif s-a[i]>=-a[0] and s-a[i]<=a[0]:
d[i]=-1
s-=a[i]
elif s+a[i]<-a[0]:
d[i]=1
s+=a[i]
elif s-a[i]>a[0]:
d[i]=-1
s-=a[i]
elif s>a[i]:
d[i]=-1
s-=a[i]
elif s<-a[i]:
d[i]=1
s+=a[i]
else:
m1=s+a[i]-a[0]
m2=abs(s-a[i])-a[0]
m=min(m1,m2)
if m==m1:
s+=a[i]
d[i]=1
else:
s-=a[i]
d[i]=-1
if s<0:
for i in range (n):
d[i]=-1*d[i]
for i in d:
if i>0:
print('+',end='')
else:
print('-',end='')
``` | instruction | 0 | 8,617 | 5 | 17,234 |
Yes | output | 1 | 8,617 | 5 | 17,235 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n=in_num()
l=in_arr()
ans=[]
sm=0
for i in range(n-1,-1,-1):
if sm<=0:
sm+=l[i]
ans.append('+')
else:
sm-=l[i]
ans.append('-')
if sm<0:
for i in range(n):
ans[i]='+'*(ans[i]=='-')+'-'*(ans[i]=='+')
pr(''.join(reversed(ans)))
``` | instruction | 0 | 8,618 | 5 | 17,236 |
Yes | output | 1 | 8,618 | 5 | 17,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
#!/usr/bin/python3
n = int(input())
a = list(map(int, input().split()))
s = a[-1]
ans = ['+']
for v in reversed(a[:-1]):
if s > 0:
s -= v
ans.append('-')
else:
s += v
ans.append('+')
if 0 <= s <= a[-1]:
print(''.join(reversed(ans)))
else:
s = -a[-1]
ans = ['-']
for v in reversed(a[:-1]):
if s > 0:
s -= v
ans.append('-')
else:
s += v
ans.append('+')
print(''.join(reversed(ans)))
``` | instruction | 0 | 8,619 | 5 | 17,238 |
No | output | 1 | 8,619 | 5 | 17,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
if __name__ == "__main__":
n = int(input())
array = input()
if n == 1:
print('+')
print('+'*(n-1) + '-')
``` | instruction | 0 | 8,620 | 5 | 17,240 |
No | output | 1 | 8,620 | 5 | 17,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
s=-1*sum(a)
str=['-']*n
k=0
while(s<0 and k<n):
if(s+2*a[k]<=a[0]):
s=s+2*a[k]
str[k]='+'
k=k+1
if(s>=0 and s<=a[0]):
for i in range(0,n):
print(str[i],end='')
else:
print(-1)
``` | instruction | 0 | 8,621 | 5 | 17,242 |
No | output | 1 | 8,621 | 5 | 17,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.
It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).
Output
In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
4
1 2 3 5
Output
+++-
Input
3
3 3 5
Output
++-
Submitted Solution:
```
def invert(s):
t = ''
for i in s:
if(i =='+'):
t += '-'
else:
t += '+'
#print(s,t)
return t
n = int(input())
a=list(map(int,input().split()))
cur = a[-1]
s = '+'
for i in range(n-2,0,-1):
if(cur > 0):
cur -= a[i]
s += '-'
else:
cur += a[i]
s += '+'
#print(s[::-1])
if(cur >= a[0]):
s += '-'
elif(abs(cur) <= a[0] and cur <= 0):
s += '+'
elif( 0 < cur < a[0]):
s=invert(s)
s += '+'
else:
s=invert(s)
s += '-'
print(s[::-1])
``` | instruction | 0 | 8,622 | 5 | 17,244 |
No | output | 1 | 8,622 | 5 | 17,245 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
3
3 0 1
Output
2 | instruction | 0 | 9,005 | 5 | 18,010 |
"Correct Solution:
```
n=int(input())
d=''.join(''.join(input().split())for i in[0]*(n//19+(n%19!=0)))
i=0
while 1:
if d.find(str(i))==-1:
print(i)
exit()
i+=1
``` | output | 1 | 9,005 | 5 | 18,011 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.