message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Input The first line contains one integer number n (2 ≤ n ≤ 5000). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet. Output Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Examples Input 4 1 2 4 5 Output 4 Input 6 62 22 60 61 48 49 Output 5 Note In the first example subsequences [1, 2] and [4, 5] give length 4 in total. In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal. Submitted Solution: ``` import sys from collections import Counter n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] dp = [[0]*n for _ in range(n)] maxnum = [0]*(10**5+10) ans = 0 for i in range(n): maxmod = [0]*7 for j in range(i): maxnum[a[j]] = max(maxnum[a[j]], dp[j][i]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[j][i]) for j in range(i+1, n): dp[i][j] = max( maxnum[a[j]-1], maxnum[a[j]+1], maxmod[mod7[j]], dp[0][i] ) + 1 maxnum[a[j]] = max(maxnum[a[j]], dp[i][j]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[i][j]) ans = max(ans, dp[i][j]) for j in range(i+1, n): maxnum[a[j]] = 0 print(ans) ```
instruction
0
34,835
12
69,670
No
output
1
34,835
12
69,671
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,897
12
69,794
"Correct Solution: ``` class LazySegmentTree(): def __init__(self,n,init,merge,merge_unit,operate,merge_operate,operate_unit): self.merge=merge self.merge_unit=merge_unit self.operate=operate self.merge_operate=merge_operate self.operate_unit=operate_unit self.n=(n-1).bit_length() self.num = 1<<self.n self.data=[merge_unit for i in range(1<<(self.n+1))] self.lazy=[operate_unit for i in range(1<<(self.n+1))] if init: for i in range(n): self.data[2**self.n+i]=init[i] for i in range(2**self.n-1,0,-1): self.data[i]=self.merge(self.data[2*i],self.data[2*i+1]) def propagate(self,v): ope = self.lazy[v] if ope == self.operate_unit: return self.lazy[v]=self.operate_unit self.data[2*v]=self.operate(self.data[2*v],ope) self.data[2*v+1]=self.operate(self.data[2*v+1],ope) self.lazy[2*v]=self.merge_operate(self.lazy[2*v],ope) self.lazy[2*v+1]=self.merge_operate(self.lazy[2*v+1],ope) def propagate_above(self,i): m=i.bit_length()-1 for bit in range(m,0,-1): v=i>>bit self.propagate(v) def remerge_above(self,i): while i: i>>=1 self.data[i]=self.operate(self.merge(self.data[2*i],self.data[2*i+1]),self.lazy[i]) def update(self,l,r,x): l+=1<<self.n r+=1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 while l<r: if l&1: self.data[l]=self.operate(self.data[l],x) self.lazy[l]=self.merge_operate(self.lazy[l],x) l+=1 if r&1: self.data[r-1]=self.operate(self.data[r-1],x) self.lazy[r-1]=self.merge_operate(self.lazy[r-1],x) l>>=1 r>>=1 self.remerge_above(l0) self.remerge_above(r0) def query(self,l,r): l+=1<<self.n r+=1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 self.propagate_above(l0) self.propagate_above(r0) res=self.merge_unit L = [] R = [] while l<r: if l&1: L.append(l) l+=1 if r&1: R.append(r-1) l>>=1 r>>=1 if L and R and R[-1]==L[-1]: R.pop() R=R[::-1] m = L+R for idx in m: res = self.merge(res,self.data[idx]) return res def bisect_l(self,l,r,x): l += 1<<self.n r += 1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 self.propagate_above(l0) self.propagate_above(r0) Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.data[l][0] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.data[r-1][0] <=x: Rmin = r-1 l >>= 1 r >>= 1 res = -1 if Lmin != -1: pos = Lmin while pos<self.num: self.propagate(pos) if self.data[2 * pos][0] <=x: pos = 2 * pos else: pos = 2 * pos +1 res = pos-self.num if Rmin != -1: pos = Rmin while pos<self.num: self.propagate(pos) if self.data[2 * pos][0] <=x: pos = 2 * pos else: pos = 2 * pos +1 if res==-1: res = pos-self.num else: res = min(res,pos-self.num) return res import sys input = sys.stdin.readline merge = lambda x,y:(x[0]+y[0]+x[2]*y[1],x[1]+y[1],x[2]+y[2]) merge_unit = (0,0,0) def operate(x,y): if y: return (x[1]*x[2]-x[0],x[2],x[1]) else: return x merge_operate = lambda x,y: (x+y)%2 operate_unit = 0 N,Q = map(int,input().split()) A = list(map(int,input().split())) for i in range(N): if A[i]==0: A[i]=(0,1,0) else: A[i]=(0,0,1) LST = LazySegmentTree(N,A,merge,merge_unit,operate,merge_operate,operate_unit) for i in range(Q): t,l,r = map(int,input().split()) l = l-1 if t==1: LST.update(l,r,1) else: print(LST.query(l,r)[0]) ```
output
1
34,897
12
69,795
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,898
12
69,796
"Correct Solution: ``` # エラーチェックを入れるなど class LazySegmentTree: __slots__ = ["n", "original_size", "log", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, length_or_list, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator): self.me = monoid_identity self.oe = operator_identity self.fmm = func_monoid_monoid self.fmo = func_monoid_operator self.foo = func_operator_operator if isinstance(length_or_list, int): self.original_size = length_or_list self.log = (self.original_size - 1).bit_length() self.n = 1 << self.log self.data = [self.me] * (self.n * 2) self.lazy = [self.oe] * (self.n * 2) elif isinstance(length_or_list, list): self.original_size = len(length_or_list) self.log = (self.original_size - 1).bit_length() self.n = 1 << self.log self.data = [self.me] * self.n + length_or_list + [self.me] * (self.n - self.original_size) for i in range(self.n-1, 0, -1): self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1]) self.lazy = [self.oe] * (self.n * 2) else: raise TypeError(f"The argument 'length_or_list' must be an integer or a list, not {type(length_or_list).__name__}") def replace(self, index, value): if index < -self.original_size or self.original_size <= index: raise IndexError("LazySegmentTree index out of range") if index < 0: index += self.original_size index += self.n # propagation for shift in range(self.log, 0, -1): i = index >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # update self.data[index] = value self.lazy[index] = self.oe # recalculation i = index while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def __getitem__(self, index): if index < -self.original_size or self.original_size <= index: raise IndexError("LazySegmentTree index out of range") if index < 0: index += self.original_size index += self.n # propagation for shift in range(self.log, 0, -1): i = index >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # self.data[index] = self.fmo(self.data[index], self.lazy[index]) # self.lazy[index] = self.oe return self.data[index] def effect(self, l, r, operator): if l < 0: l += self.original_size if r < 0: r += self.original_size if not 0 <= l < r <= self.original_size: raise IndexError("LazySegmentTree index out of range") l += self.n r += self.n # preparing indices indices = [] l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 l0 //= 2 r0 //= 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # effect while l < r: if l % 2: self.lazy[l] = self.foo(self.lazy[l], operator) l += 1 if r % 2: r -= 1 self.lazy[r] = self.foo(self.lazy[r], operator) l //= 2 r //= 2 # recalculation for i in indices: self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def folded(self, l, r): if l < 0: l += self.original_size if r < 0: r += self.original_size if not 0 <= l < r <= self.original_size: raise IndexError("LazySegmentTree index out of range") l += self.n r += self.n # preparing indices indices = [] l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 l0 //= 2 r0 //= 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # fold left_folded = self.me right_folded = self.me while l < r: if l % 2: left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l])) l += 1 if r % 2: r -= 1 right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded) l //= 2 r //= 2 return self.fmm(left_folded, right_folded) def atc2(): # Monoid: ((0の数), (1の数), (転倒数)) # Operator: 反転するか? (1 or 0) import sys input = sys.stdin.buffer.readline N, Q = map(int, input().split()) monoid_data = [(0, 1, 0) if A == b'1' else (1, 0, 0) for A in input().split()] def fmm(m1, m2): return (m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2] + m1[1] * m2[0]) def fmo(m1, o1): if o1: return (m1[1], m1[0], m1[0] * m1[1] - m1[2]) else: return m1 def foo(o1, o2): return o1 ^ o2 lst = LazySegmentTree(monoid_data, (0, 0, 0), 0, fmm, fmo, foo) ans = [] for _ in range(Q): T, L, R = map(int, input().split()) if T == 1: lst.effect(L-1, R, 1) else: ans.append(lst.folded(L-1, R)[2]) print('\n'.join(map(str, ans))) if __name__ == "__main__": atc2() ```
output
1
34,898
12
69,797
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,899
12
69,798
"Correct Solution: ``` # 同じインデックスの重複を除くので、関数の呼び出し回数が少し少ないはず。 # ただ、重複を除く分のオーバーヘッドがあるので、 # fmm, fmo, fooが軽い関数だと、スピードはそこまで出ない。 MOD = 998244353 mask = (1 << 32) - 1 mask20 = (1 << 20) - 1 mask40 = (1 << 40) - 1 class LazySegmentTree: __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator): self.me = monoid_identity self.oe = operator_identity self.fmm = func_monoid_monoid self.fmo = func_monoid_operator self.foo = func_operator_operator self.n = len(monoid_data) self.data = monoid_data * 2 for i in range(self.n-1, 0, -1): self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1]) self.lazy = [self.oe] * (self.n * 2) def replace(self, index, value): index += self.n # propagation for shift in range(index.bit_length()-1, 0, -1): i = index >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # update self.data[index] = value self.lazy[index] = self.oe # recalculation i = index while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def effect(self, l, r, operator): l += self.n r += self.n # preparing indices indices = [] l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 l0 //= 2 r0 //= 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 if l0 == r0: break indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # effect while l < r: if l % 2: self.lazy[l] = self.foo(self.lazy[l], operator) l += 1 if r % 2: r -= 1 self.lazy[r] = self.foo(self.lazy[r], operator) l //= 2 r //= 2 # recalculation for i in indices: self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def folded(self, l, r): l += self.n r += self.n # preparing indices indices = [] l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 l0 //= 2 r0 //= 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 if l0 == r0: break indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # fold left_folded = self.me right_folded = self.me while l < r: if l % 2: left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l])) l += 1 if r % 2: r -= 1 right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded) l //= 2 r //= 2 return self.fmm(left_folded, right_folded) # Monoid は (値 << 32) + 要素数 にする。 # Operator も (b << 32) + c def main(): import sys input = sys.stdin.buffer.readline def fmm(m1, m2): m = m1 + m2 return (((m >> 32) % MOD) << 32) + (m & mask) def fmo(m1, o1): val = m1 >> 32 cnt = m1 & mask b = o1 >> 32 c = o1 & mask return (((b * val + c * cnt) % MOD) << 32) + cnt def foo(o1, o2): b1 = o1 >> 32 c1 = o1 & mask b2 = o2 >> 32 c2 = o2 & mask b = b1 * b2 % MOD c = (c1 * b2 + c2) % MOD return (b << 32) + c N, Q = map(int, input().split()) monoid_data = [(A << 32) + 1 for A in map(int, input().split())] lst = LazySegmentTree(monoid_data, 1, 1 << 32, fmm, fmo, foo) for _ in range(Q): q, *k = map(int, input().split()) if q == 0: o = (k[2] << 32) + k[3] lst.effect(k[0], k[1], o) else: print(lst.folded(k[0], k[1]) >> 32) def test(): import random def madd(a, b): return (a + b) % MOD def mmul(a, b): return a * b % MOD lst = LazySegmentTree([0] * 10, 0, 1, madd, mmul, mmul) ls = [0] * 10 for _ in range(10000000): if random.randint(0, 1): # effect l = random.randint(0, 9) r = random.randint(l+1, 10) e = random.randint(1, 782) lst.effect(l, r, e) for i in range(l, r): ls[i] *= e ls[i] %= MOD else: l = random.randint(0, 9) r = random.randint(l+1, 10) if lst.folded(l, r) != sum(ls[l:r]): print(ls) print(l, r) print(lst.folded(l, r)) def atc(): # Monoid: ((0の数) << 60) + ((1の数) << 40) + (転倒数) # Operator: 反転するか? (1 or 0) import sys input = sys.stdin.buffer.readline N, Q = map(int, input().split()) monoid_data = [1099511627776 if A == b'1' else 1152921504606846976 for A in input().split()] def fmm(m1, m2): return m1 + m2 + ((m1 >> 40) & mask20) * (m2 >> 60) def fmo(m1, o1): if o1: cnt = m1 & mask40 c1 = (m1 >> 40) & mask20 c0 = m1 >> 60 return (c1 << 60) + (c0 << 40) + ((c0 * c1) - cnt) else: return m1 def foo(o1, o2): return o1 ^ o2 lst = LazySegmentTree(monoid_data, 0, 0, fmm, fmo, foo) for _ in range(Q): T, L, R = map(int, input().split()) if T == 1: lst.effect(L-1, R, 1) else: print(lst.folded(L-1, R) & mask40) def atc2(): # Monoid: ((0の数), (1の数), (転倒数)) # Operator: 反転するか? (1 or 0) import sys input = sys.stdin.buffer.readline N, Q = map(int, input().split()) monoid_data = [(0, 1, 0) if A == b'1' else (1, 0, 0) for A in input().split()] def fmm(m1, m2): return (m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2] + m1[1] * m2[0]) def fmo(m1, o1): if o1: return (m1[1], m1[0], m1[0] * m1[1] - m1[2]) else: return m1 def foo(o1, o2): return o1 ^ o2 lst = LazySegmentTree(monoid_data, (0, 0, 0), 0, fmm, fmo, foo) for _ in range(Q): T, L, R = map(int, input().split()) if T == 1: lst.effect(L-1, R, 1) else: print(lst.folded(L-1, R)[2]) def mainbignum(): import sys input = sys.stdin.buffer.readline bignum = 10 ** 9 def fmm(m1, m2): m = m1 + m2 q, r = divmod(m, bignum) return (q % MOD * bignum) + r def fmo(m1, o1): val, cnt = divmod(m1, bignum) b, c = divmod(o1, bignum) return (((b * val + c * cnt) % MOD) * bignum) + cnt def foo(o1, o2): b1, c1 = divmod(o1, bignum) b2, c2 = divmod(o2, bignum) b = b1 * b2 % MOD c = (c1 * b2 + c2) % MOD return (b * bignum) + c N, Q = map(int, input().split()) monoid_data = [(A *bignum) + 1 for A in map(int, input().split())] lst = LazySegmentTree(monoid_data, 1, bignum, fmm, fmo, foo) for _ in range(Q): q, *k = map(int, input().split()) if q == 0: o = (k[2] * bignum) + k[3] lst.effect(k[0], k[1], o) else: print(lst.folded(k[0], k[1]) // bignum) if __name__ == "__main__": atc2() ```
output
1
34,899
12
69,799
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,900
12
69,800
"Correct Solution: ``` # 2冪 # 同じインデックスの重複を除くので、関数の呼び出し回数が少し少ないはず。 # ただ、重複を除く分のオーバーヘッドがあるので、 # fmm, fmo, fooが軽い関数だと、スピードはそこまで出ない。 class LazySegmentTree: __slots__ = ["n", "original_size", "log", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator): self.me = monoid_identity self.oe = operator_identity self.fmm = func_monoid_monoid self.fmo = func_monoid_operator self.foo = func_operator_operator self.original_size = len(monoid_data) self.log = (self.original_size - 1).bit_length() self.n = 1 << self.log self.data = [self.me] * self.n + monoid_data + [self.me] * (self.n - self.original_size) for i in range(self.n-1, 0, -1): self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1]) self.lazy = [self.oe] * (self.n * 2) def replace(self, index, value): index += self.n # propagation for shift in range(self.log, 0, -1): i = index >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # update self.data[index] = value self.lazy[index] = self.oe # recalculation i = index while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def effect(self, l, r, operator): l += self.n r += self.n # preparing indices (参考: http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3561258#1) indices = [] L = l // 2 R = r // 2 lc = 0 if l % 2 else (L & -L).bit_length() rc = 0 if r % 2 else (R & -R).bit_length() for i in range(self.log): if rc <= i: indices.append(R) if L < R and lc <= i: indices.append(L) L //= 2 R //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # effect while l < r: if l % 2: self.lazy[l] = self.foo(self.lazy[l], operator) l += 1 if r % 2: r -= 1 self.lazy[r] = self.foo(self.lazy[r], operator) l //= 2 r //= 2 # recalculation for i in indices: self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def folded(self, l, r): l += self.n r += self.n # preparing indices indices = [] L = l // 2 R = r // 2 lc = 0 if l % 2 else (L & -L).bit_length() rc = 0 if r % 2 else (R & -R).bit_length() for i in range(self.log): if rc <= i: indices.append(R) if L < R and lc <= i: indices.append(L) L //= 2 R //= 2 # propagation for i in reversed(indices): self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # fold left_folded = self.me right_folded = self.me while l < r: if l % 2: left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l])) l += 1 if r % 2: r -= 1 right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded) l //= 2 r //= 2 return self.fmm(left_folded, right_folded) def atc2(): # Monoid: ((0の数), (1の数), (転倒数)) # Operator: 反転するか? (1 or 0) import sys input = sys.stdin.buffer.readline N, Q = map(int, input().split()) monoid_data = [(0, 1, 0) if A == b'1' else (1, 0, 0) for A in input().split()] def fmm(m1, m2): return (m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2] + m1[1] * m2[0]) def fmo(m1, o1): if o1: return (m1[1], m1[0], m1[0] * m1[1] - m1[2]) else: return m1 def foo(o1, o2): return o1 ^ o2 lst = LazySegmentTree(monoid_data, (0, 0, 0), 0, fmm, fmo, foo) ans = [] for _ in range(Q): T, L, R = map(int, input().split()) if T == 1: lst.effect(L-1, R, 1) else: ans.append(lst.folded(L-1, R)[2]) print('\n'.join(map(str, ans))) if __name__ == "__main__": atc2() ```
output
1
34,900
12
69,801
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,901
12
69,802
"Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() class LazySegmentTree(): def __init__(self, init, unitX, unitA, f, g, h): self.f = f # (X, X) -> X self.g = g # (X, A, size) -> X self.h = h # (A, A) -> A self.unitX = unitX self.unitA = unitA self.f = f if type(init) == int: self.n = init # self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) self.size = [1] * (self.n * 2) else: self.n = len(init) # self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) self.size = [0] * self.n + [1] * len(init) + [0] * (self.n - len(init)) for i in range(self.n-1, 0, -1): self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) for i in range(self.n - 1, 0, -1): self.size[i] = self.size[i*2] + self.size[i*2|1] self.A = [unitA] * (self.n * 2) def update(self, i, x): i += self.n self.X[i] = x i >>= 1 while i: self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) i >>= 1 def calc(self, i): return self.g(self.X[i], self.A[i], self.size[i]) def calc_above(self, i): i >>= 1 while i: self.X[i] = self.f(self.calc(i*2), self.calc(i*2|1)) i >>= 1 def propagate(self, i): self.X[i] = self.g(self.X[i], self.A[i], self.size[i]) self.A[i*2] = self.h(self.A[i*2], self.A[i]) self.A[i*2|1] = self.h(self.A[i*2|1], self.A[i]) self.A[i] = self.unitA def propagate_above(self, i): H = i.bit_length() for h in range(H, 0, -1): self.propagate(i >> h) def propagate_all(self): for i in range(1, self.n): self.propagate(i) def getrange(self, l, r): l += self.n r += self.n l0, r0 = l // (l & -l), r // (r & -r) - 1 self.propagate_above(l0) self.propagate_above(r0) al = self.unitX ar = self.unitX while l < r: if l & 1: al = self.f(al, self.calc(l)) l += 1 if r & 1: r -= 1 ar = self.f(self.calc(r), ar) l >>= 1 r >>= 1 return self.f(al, ar) def getvalue(self, i): i += self.n self.propagate_above(i) return self.calc(i) def operate_range(self, l, r, a): l += self.n r += self.n l0, r0 = l // (l & -l), r // (r & -r) - 1 self.propagate_above(l0) self.propagate_above(r0) while l < r: if l & 1: self.A[l] = self.h(self.A[l], a) l += 1 if r & 1: r -= 1 self.A[r] = self.h(self.A[r], a) l >>= 1 r >>= 1 self.calc_above(l0) self.calc_above(r0) # Find r s.t. calc(l, ..., r-1) = True and calc(l, ..., r) = False def max_right(self, l, z): if l >= self.n: return self.n l += self.n s = self.unitX while 1: while l % 2 == 0: l >>= 1 if not z(self.f(s, self.calc(l))): while l < self.n: l *= 2 if z(self.f(s, self.calc(l))): s = self.f(s, self.calc(l)) l += 1 return l - self.n s = self.f(s, self.calc(l)) l += 1 if l & -l == l: break return self.n # Find l s.t. calc(l, ..., r-1) = True and calc(l-1, ..., r-1) = False def min_left(self, r, z): if r <= 0: return 0 r += self.n s = self.unitX while 1: r -= 1 while r > 1 and r % 2: r >>= 1 if not z(self.f(self.calc(r), s)): while r < self.n: r = r * 2 + 1 if z(self.f(self.calc(r), s)): s = self.f(self.calc(r), s) r -= 1 return r + 1 - self.n s = self.f(self.calc(r), s) if r & -r == r: break return 0 def debug(self): X = self.X print("X =", [self.calc(i) for i in range(self.n, self.n * 2)]) if False: f = lambda x, y: (x[0] + y[0] + x[2] * y[1], x[1] + y[1], x[2] + y[2]) g = lambda x, a, s: (x[1] * x[2] - x[0], x[2], x[1]) if a else x h = lambda a, b: a ^ b unitX = (0, 0, 0) unitA = 0 # (inversion, number of zeros, number of ones) mm = 262143 mmm = 68719214592 def f(x, y): return x + y + ((x & mm) * (y & mmm) << 18) def g(x, a, s): x0, x1, x2 = x >> 36, (x >> 18) & mm, x & mm return (x1 * x2 - x0 << 36) + (x2 << 18) + x1 if a else x def h(a, b): return a ^ b unitX = 0 unitA = 0 N, Q = map(int, input().split()) A = [(1 << 18) if int(a) == 0 else 1 for a in input().split()] st = LazySegmentTree(A, unitX, unitA, f, g, h) for _ in range(Q): t, l, r = map(int, input().split()) if t == 1: st.operate_range(l - 1, r, 1) else: print(st.getrange(l - 1, r) >> 36) ```
output
1
34,901
12
69,803
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,902
12
69,804
"Correct Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") ### 遅延評価セグメント木 class LazySegmentTree: def __init__(self, n, a=None): """初期化 num : n以上の最小の2のべき乗 """ num = 1 while num<=n: num *= 2 self.num = num self.seg = [ninf] * (2*self.num-1) self.lazy = [f0] * (2*self.num-1) self.ls = [0]*(2*self.num-1) self.rs = [0]*(2*self.num-1) self.ls[0] = 0 self.rs[0] = self.num for i in range(self.num-1): self.ls[2*i+1] = self.ls[i] self.rs[2*i+1] = (self.ls[i] + self.rs[i])//2 self.ls[2*i+2] = (self.ls[i] + self.rs[i])//2 self.rs[2*i+2] = self.rs[i] if a is not None: # O(n)で初期化 assert len(a)==n for i in range(n): self.seg[num-1+i] = a[i] for k in range(num-2, -1, -1): self.seg[k] = op(self.seg[2*k+1], self.seg[2*k+2]) def eval(self, k): if self.lazy[k]==f0: return if k<self.num-1: self.lazy[k*2+1] = composition(self.lazy[k], self.lazy[k*2+1]) self.lazy[k*2+2] = composition(self.lazy[k], self.lazy[k*2+2]) self.seg[k] = mapping(self.lazy[k], self.seg[k]) self.lazy[k] = f0 def eval_all(self): for i in range(2*self.num-1): self.eval(i) def update(self,a,b,x=None,f=None): """A[a]...A[b-1]をxに更新する """ if f is None: # 更新クエリ f = lambda y: x k = 0 q = [k] # k>=0なら行きがけ順 # 重なる区間を深さ優先探索 while q: k = q.pop() l,r = self.ls[k], self.rs[k] if k>=0: self.eval(k) if r<=a or b<=l: continue elif a<=l and r<=b: self.lazy[k] = composition(f, self.lazy[k]) self.eval(k) else: q.append(~k) q.append(2*k+1) q.append(2*k+2) else: k = ~k self.seg[k] = op(self.seg[2*k+1], self.seg[2*k+2]) def query(self,a,b): k = 0 l = 0 r = self.num q = [k] ans = ninf # 重なる区間を深さ優先探索 while q: k = q.pop() l,r = self.ls[k], self.rs[k] self.eval(k) if r<=a or b<=l: continue elif a<=l and r<=b: ans = op(ans, self.seg[k]) else: q.append(2*k+2) q.append(2*k+1) # print(q, ans, l,r,a,b, self.seg[k]) return ans n,q = list(map(int, input().split())) a = list(map(int, input().split())) # ninf = -10**9 # op = max # mapping = lambda f,x: f(x) # composition = lambda f1, f2: f1 if f1 is not None else f2 ninf = (0,0,0) # (転倒数, #0, #1) op = lambda x,y: (x[0]+y[0]+x[2]*y[1], x[1]+y[1], x[2]+y[2]) mapping = lambda f,x: ((x[1]+x[2])*(x[1]+x[2]-1)//2 - (x[1]*(x[1]-1)//2) - (x[2]*(x[2]-1)//2) - x[0], x[2], x[1]) if f else x composition = lambda f1, f2: f1^f2 f0 = False sg = LazySegmentTree(n, [((0,1,0) if item==0 else (0,0,1)) for item in a]) ans = [] for _ in range(q): t = tuple(map(int, input().split())) if t[0]==1: _, l,r = t sg.update(l-1,r,f=True) else: _,l,r = t ans.append(sg.query(l-1,r)[0]) # break write("\n".join(map(str, ans))) ```
output
1
34,902
12
69,805
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,903
12
69,806
"Correct Solution: ``` I = [int(_) for _ in open(0).read().split()] N, Q = I[:2] A = I[2:2 + N] T = I[2 + N::3] L = I[3 + N::3] R = I[4 + N::3] class LazySegmentTree(): def __init__(self, array, f, g, h, ti, ei): """ Parameters ---------- array : list to construct segment tree from f : func binary operation of the monoid T x T -> T T is dat g : func binary operation of the monoid T x E -> T T is dat, E is laz h : func binary operation of the monoid E x E -> T E is laz ti : T identity element of T ei : E identity element of E """ self.f = f self.g = g self.h = h self.ti = ti self.ei = ei self.height = height = len(array).bit_length() self.n = n = 2**height self.dat = dat = [ti] * n + array + [ti] * (n - len(array)) self.laz = [ei] * (2 * n) for i in range(n - 1, 0, -1): # build dat[i] = f(dat[i << 1], dat[i << 1 | 1]) def reflect(self, k): dat = self.dat ei = self.ei laz = self.laz g = self.g return self.dat[k] if laz[k] is ei else g(dat[k], laz[k]) def evaluate(self, k): laz = self.laz ei = self.ei reflect = self.reflect dat = self.dat h = self.h if laz[k] is ei: return laz[(k << 1) | 0] = h(laz[(k << 1) | 0], laz[k]) laz[(k << 1) | 1] = h(laz[(k << 1) | 1], laz[k]) dat[k] = reflect(k) laz[k] = ei def thrust(self, k): height = self.height evaluate = self.evaluate for i in range(height, 0, -1): evaluate(k >> i) def recalc(self, k): dat = self.dat reflect = self.reflect f = self.f while k: k >>= 1 dat[k] = f(reflect((k << 1) | 0), reflect((k << 1) | 1)) def update(self, a, b, x): # set value at position [a, b) (0-indexed) thrust = self.thrust n = self.n h = self.h laz = self.laz recalc = self.recalc a += n b += n - 1 l = a r = b + 1 thrust(a) thrust(b) while l < r: if l & 1: laz[l] = h(laz[l], x) l += 1 if r & 1: r -= 1 laz[r] = h(laz[r], x) l >>= 1 r >>= 1 recalc(a) recalc(b) def set_val(self, a, x): n = self.n thrust = self.thrust dat = self.dat laz = self.laz recalc = self.recalc ei = self.ei a += n thrust(a) dat[a] = x laz[a] = ei recalc(a) def query(self, a, b): # result on interval [a, b) (0-indexed) f = self.f ti = self.ti n = self.n thrust = self.thrust reflect = self.reflect a += n b += n - 1 thrust(a) thrust(b) l = a r = b + 1 vl = vr = ti while l < r: if l & 1: vl = f(vl, reflect(l)) l += 1 if r & 1: r -= 1 vr = f(reflect(r), vr) l >>= 1 r >>= 1 return f(vl, vr) #general linear functions array = [(0, 0, 0)] + [(0, 1, 0) if a else (1, 0, 0) for a in A] f = lambda a, b: (a[0] + b[0], a[1] + b[1], a[2] + b[2] + a[1] * b[0]) def g(a, b): if b == -1: x = a[1] y = a[0] z = (x + y) * (x + y - 1) // 2 - x * (x - 1) // 2 - y * ( y - 1) // 2 - a[2] return (x, y, z) else: return a h = lambda a, b: a * b ti = (0, 0, 0) ei = 1 # b[0] * (a[0] * x + a[1]) + b[1] # = b[0] * a[0] * x + (b[0] * a[1] + b[1]) LST = LazySegmentTree(array=array, ti=ti, ei=ei, f=f, g=g, h=h) for t, l, r in zip(T, L, R): r += 1 if t == 1: LST.update(l, r, -1) else: print(LST.query(l, r)[2]) ```
output
1
34,903
12
69,807
Provide a correct Python 3 solution for this coding contest problem. You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j. Constraints * 1 \leq N \leq 2 \times 10^5 * 0 \leq A_i \leq 1 * 1 \leq Q \leq 2 \times 10^5 * 1 \leq T_i \leq 2 * 1 \leq L_i \leq R_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q Output For each query with T_i=2, print the answer. Example Input 5 5 0 1 0 0 1 2 1 5 1 3 4 2 2 5 1 1 3 2 1 2 Output 2 0 1
instruction
0
34,904
12
69,808
"Correct Solution: ``` class lazy_segtree: #遅延評価セグメント木 def __init__(s, op, e, mapping, composition, id, v): if type(v) is int: v = [e()] * v s._n = len(v) s.log = s.ceil_pow2(s._n) s.size = 1 << s.log s.d = [e()] * (2 * s.size) s.lz = [id()] * s.size s.e = e s.op = op s.mapping = mapping s.composition = composition s.id = id for i in range(s._n): s.d[s.size + i] = v[i] for i in range(s.size - 1, 0, -1): s.update(i) # 1点更新 def set(s, p, x): p += s.size for i in range(s.log, 0, -1): s.push(p >> i) s.d[p] = x for i in range(1, s.log + 1): s.update(p >> i) # 1点取得 def get(s, p): p += s.size for i in range(s.log, 0, -1): s.push(p >> i) return s.d[p] # 区間演算 def prod(s, l, r): if l == r: return s.e() l += s.size r += s.size for i in range(s.log, 0, -1): if (((l >> i) << i) != l): s.push(l >> i) if (((r >> i) << i) != r): s.push(r >> i) sml, smr = s.e(), s.e() while (l < r): if l & 1: sml = s.op(sml, s.d[l]) l += 1 if r & 1: r -= 1 smr = s.op(s.d[r], smr) l >>= 1 r >>= 1 return s.op(sml, smr) # 全体演算 def all_prod(s): return s.d[1] # 1点写像 def apply(s, p, f): p += s.size for i in range(s.log, 0, -1): s.push(p >> i) s.d[p] = s.mapping(f, s.d[p]) for i in range(1, s.log + 1): s.update(p >> i) # 区間写像 def apply(s, l, r, f): if l == r: return l += s.size r += s.size for i in range(s.log, 0, -1): if (((l >> i) << i) != l): s.push(l >> i) if (((r >> i) << i) != r): s.push((r - 1) >> i) l2, r2 = l, r while l < r: if l & 1: sml = s.all_apply(l, f) l += 1 if r & 1: r -= 1 smr = s.all_apply(r, f) l >>= 1 r >>= 1 l, r = l2, r2 for i in range(1, s.log + 1): if (((l >> i) << i) != l): s.update(l >> i) if (((r >> i) << i) != r): s.update((r - 1) >> i) # L固定時の最長区間のR def max_right(s, l, g): if l == s._n: return s._n l += s.size for i in range(s.log, 0, -1): s.push(l >> i) sm = s.e() while True: while (l % 2 == 0): l >>= 1 if not g(s.op(sm, s.d[l])): while l < s.size: s.push(l) l = 2 * l if g(s.op(sm, s.d[l])): sm = s.op(sm, s.d[l]) l += 1 return l - s.size sm = s.op(sm, s.d[l]) l += 1 if (l & -l) == l: break return s._n # R固定時の最長区間のL def min_left(s, r, g): if r == 0: return 0 r += s.size for i in range(s.log, 0, -1): s.push((r - 1) >> i) sm = s.e() while True: r -= 1 while r > 1 and (r % 2): r >>= 1 if not g(s.op(s.d[r], sm)): while r < s.size: s.push(r) r = 2 * r + 1 if g(s.op(s.d[r], sm)): sm = s.op(s.d[r], sm) r -= 1 return r + 1 - s.size sm = s.op(s.d[r], sm) if (r & - r) == r: break return 0 def update(s, k): s.d[k] = s.op(s.d[2 * k], s.d[2 * k + 1]) def all_apply(s, k, f): s.d[k] = s.mapping(f, s.d[k]) if k < s.size: s.lz[k] = s.composition(f, s.lz[k]) def push(s, k): s.all_apply(2 * k, s.lz[k]) s.all_apply(2 * k + 1, s.lz[k]) s.lz[k] = s.id() def ceil_pow2(s, n): x = 0 while (1 << x) < n: x += 1 return x def op(l, r): return [l[0] + r[0], l[1] + r[1], l[2] + r[2] + l[1] * r[0]] def e(): return [0, 0, 0] def mapping(l, r): if (not l): return r return [r[1], r[0], r[1] * r[0] - r[2]] def composition(l, r): return (l and not r) or (not l and r) def id(): return False def g(x): return x[2] <= 1 import sys input = sys.stdin.readline N, Q = list(map(int, input().split())) a = [(0, 1, 0) if A == "1" else (1, 0, 0) for A in input().split()] seg = lazy_segtree(op, e, mapping, composition, id, a) ans = [] for i in range(Q): t, l, r = map(int, input().split()) l -= 1 if t == 1: seg.apply(l, r, True) else: ans.append(seg.prod(l, r)[2]) for i in ans: print(i) ```
output
1
34,904
12
69,809
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,397
12
70,794
Tags: constructive algorithms, greedy Correct Solution: ``` t=int(input()) for i in range(t): n,k=[int(w) for w in input().split()] m=[] s='' if k%2!=0 or k==1: print(int(n-int(k/2)-1)) else: print(int(n-int(k/2))) for j in range(k+1,n+1): s+=str(j)+' ' for p in range(int((k+1)/2),k): s+=str(p)+' ' print(s) ```
output
1
35,397
12
70,795
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,398
12
70,796
Tags: constructive algorithms, greedy Correct Solution: ``` import sys input=sys.stdin.readline for _ in range(int(input().strip())): n,k=map(int,input().strip().split(" "))#3 4 #s=input().strip() #n=int(input().strip()) #a=list(map(int,input().strip().split(" "))) o=[] while n>k: o.append(n) n-=1 n-=1 while 2*(n)>k-1: o.append(n) n-=1 print(len(o)) print(" ".join(map(str,o))) ```
output
1
35,398
12
70,797
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,399
12
70,798
Tags: constructive algorithms, greedy Correct Solution: ``` t = int(input()) for hg in range(t) : n , k = map(int , input().split()) l = [] for i in range(k + 1 , n + 1): l.append(i) for i in reversed(range(1 , k)): d = k - i if d not in l: l.append(i) print(len(l)) for i in l: print(int(i) , end = " ") print() ```
output
1
35,399
12
70,799
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,400
12
70,800
Tags: constructive algorithms, greedy Correct Solution: ``` T = int(input()) for _ in range(T): N, K = map(int, input().split()) ans = [] for i in range((K + 1) // 2, K): ans.append(str(i)) for i in range(K + 1, N + 1, 1): ans.append(str(i)) print(len(ans)) if ans: print((" ").join(ans)) ```
output
1
35,400
12
70,801
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,401
12
70,802
Tags: constructive algorithms, greedy Correct Solution: ``` #!/usr/bin/python import sys #use ./ex1.py < input_ex1.py def solve(N, K): print(N - K + int(K/2)) out_string = "" for i in range (K+1, N+1): out_string += str(i) out_string += " " for i in range (int((K+1)/2), K): out_string += str(i) out_string += " " print(out_string) def run(): out = "" T = int(input()) for i in range(T): N, K = [int(x) for x in input().split()] solve(N, K) run() ```
output
1
35,401
12
70,803
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,402
12
70,804
Tags: constructive algorithms, greedy Correct Solution: ``` for i in range(int(input())): n,k=list(map(int,input().split())) a=k-1 b=k-2 if a>0: c=[a] else: c=[] while a>0 and b>0 and a+b>k: c.append(b) a-=1 b-=1 c+=list(range(k+1,n+1)) print(len(c)) print(*c) ```
output
1
35,402
12
70,805
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,403
12
70,806
Tags: constructive algorithms, greedy Correct Solution: ``` for _ in range(int(input())): n,k=map(int,input().split()) ans=[] for i in range((k+1)//2,k): ans.append(i) for i in range(k+1,n+1): ans.append(i) print(len(ans)) print(*ans) ```
output
1
35,403
12
70,807
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
instruction
0
35,404
12
70,808
Tags: constructive algorithms, greedy Correct Solution: ``` import sys t = int(sys.stdin.readline().strip()) for _ in range(t): n, k = map(int, sys.stdin.readline().split()) a = [] for j in range((k+1)//2, n+1): if j != k: a.append(j) print(len(a)) for _ in a: print(_, end=' ') print(" ") ```
output
1
35,404
12
70,809
Provide tags and a correct Python 3 solution for this coding contest problem. Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much. The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message. Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers. Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj). Input The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array. Output Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 2 1 2 1 2 Output 3 Input 5 3 1 2 1 1 3 Output 2 Input 3 1 1 1 1 Output 6 Note In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2). In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1). In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
instruction
0
35,439
12
70,878
Tags: two pointers Correct Solution: ``` n, k = map(int, input().split()) a = [int(_) for _ in input().split()] mp = {} res = 0 pos = 0 t = 0 for i in range(0, n): if a[i] in mp: mp[a[i]] += 1 else: mp[a[i]] = 1 while pos <= i and k <= mp[a[i]]: mp[a[pos]] -= 1 res += n - i pos += 1 print(res) ```
output
1
35,439
12
70,879
Provide tags and a correct Python 3 solution for this coding contest problem. Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much. The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message. Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers. Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj). Input The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array. Output Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 2 1 2 1 2 Output 3 Input 5 3 1 2 1 1 3 Output 2 Input 3 1 1 1 1 Output 6 Note In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2). In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1). In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
instruction
0
35,440
12
70,880
Tags: two pointers Correct Solution: ``` def answer(): ans,count,j=0,0,0 d=dict() for i in range(n): while(j==0 or d[a[j-1]] < k): if(j==n): j+=1 break try:d[a[j]]+=1 except:d[a[j]]=1 count += 1 m=n-count+1 j+=1 if(j > n):break ans+=m d[a[i]] -= 1 return ans n,k=map(int,input().split()) a=list(map(int,input().split())) print(answer()) ```
output
1
35,440
12
70,881
Provide tags and a correct Python 3 solution for this coding contest problem. Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much. The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message. Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers. Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj). Input The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array. Output Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 2 1 2 1 2 Output 3 Input 5 3 1 2 1 1 3 Output 2 Input 3 1 1 1 1 Output 6 Note In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2). In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1). In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
instruction
0
35,441
12
70,882
Tags: two pointers Correct Solution: ``` from collections import defaultdict n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] window = defaultdict(lambda : 0) window[a[0]] += 1 i, j, ans = 0, 0, 0 while i < n and j < n: if window[a[j]] >= k: ans += n-j window[a[i]] -= 1 i += 1 elif j < n-1: window[a[j+1]] += 1 j += 1 else: break print(ans) ```
output
1
35,441
12
70,883
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,524
12
71,048
Tags: implementation, sortings Correct Solution: ``` n=int(input()) a=list(map(int,input().strip().split(" "))) l=0 while (l<n-1 and a[l]<a[l+1]): l+=1 r=l+1 while(r<n and a[r]<a[r-1]): r+=1 a=a[:l]+a[l:r][::-1]+a[r:] k=0 for i in range(1,n): if a[i]<a[i-1]: k=1 break if k==0: print("yes") print(l+1,r) elif k==1: print("no") ```
output
1
35,524
12
71,049
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,525
12
71,050
Tags: implementation, sortings Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) b=sorted(a) i=0 while i<n and a[i]==b[i]: i+=1 j=n-1 while j>-1 and a[j]==b[j]: j-=1 if i>j: print("yes") print(1,1) else: c = a[:i]+a[i:j+1][::-1]+a[j+1:] if c==b: print("yes") print(i+1,j+1) else: print("no") ```
output
1
35,525
12
71,051
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,526
12
71,052
Tags: implementation, sortings Correct Solution: ``` def sortthearray(): par1 = int(input()) par2 = list(map(int,input().split())) sortedpar2 = sorted(par2) if (par2 == sortedpar2): return "yes\n1 1" lr = [] for i in range(par1): if(par2[i] != sortedpar2[i]): lr.append(i) rvs = par2[lr[0]:lr[-1]+1] rvs.reverse() if(rvs == sortedpar2[lr[0]:lr[-1]+1]): return "yes\n"+str(lr[0]+1)+" "+str(lr[-1]+1) else:return "no" print(sortthearray()) ```
output
1
35,526
12
71,053
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,527
12
71,054
Tags: implementation, sortings Correct Solution: ``` n = int(input()) s = list(map(int, input().split())) l, r = 0, 0 while l+1<n and s[l]<s[l+1]: l+=1 r = l while r+1<n and s[r]>s[r+1]: r+=1 a = s[:l]+s[l:r+1][::-1]+s[r+1:] s.sort() if a == s: print('yes') print(l+1, r+1) else: print('no') ```
output
1
35,527
12
71,055
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,528
12
71,056
Tags: implementation, sortings Correct Solution: ``` n = int(input()) array = list(map(int, input().split())) pos = [1] for i in range(1, n): if array[i] >= array[i - 1]: pos.append(1) else: pos.append(-1) c = 0 for i in range(1, n): if pos[i] != pos[i - 1]: c += 1 if c > 2: print("no") elif c == 0: print("yes") print("1 1") else: first = pos.index(-1) second = n - pos[::-1].index(-1) - 1 if sorted(array) == array[:first - 1] + array[first - 1:second + 1][::-1] + array[second + 1:]: print("yes") print(first, second + 1) else: print("no") """2 1 3 4 1 -1 1 1 1 2 3 6 5 4 7 1 1 1 1 -1 -1 1""" ```
output
1
35,528
12
71,057
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,529
12
71,058
Tags: implementation, sortings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().strip("\r\n") n = int(input()) l = list(map(int, input().split())) i = 1 while i < n: if l[i] < l[i - 1]: break i += 1 j = i while j < n: if l[j] > l[j - 1]: break j += 1 s = l[:i - 1] + l[i - 1:j][::-1] + l[j:] l.sort() if s == l: print("yes") print(i, j) else: print("no") ```
output
1
35,529
12
71,059
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,530
12
71,060
Tags: implementation, sortings Correct Solution: ``` n=int(input()) a=list(map(int,input().split(" "))) i=0 idx1=[] idx2=-1 while i<=len(a)-1: if (i+1<len(a) and a[i]>a[i+1] ) and (i-1<0 or a[i-1]<a[i]) : idx1.append(i) idx2=i if i-1>=0 and a[i-1]>a[i]: idx2=i i+=1 if len(idx1)==0 or (idx1[0]==idx2 and len(idx1)==1): print("yes") print("1 1") elif len(idx1)>1 or (idx1[0]-1>=0 and a[idx2]<a[idx1[0]-1]) or( idx2+1<len(a) and a[idx1[0]]>a[idx2+1]):# or ( idx2+1>=len(a) and a[idx1[0]]>a[idx2+1] ): print("no") else: print("yes") print(idx1[0]+1,idx2+1) ```
output
1
35,530
12
71,061
Provide tags and a correct Python 3 solution for this coding contest problem. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
instruction
0
35,531
12
71,062
Tags: implementation, sortings Correct Solution: ``` n=int(input()) a=[int(x) for x in input().split()] b=sorted(a,key=int) l,r=0,n-1 if a==b: print("yes") print("1 1") else: while a[l]==b[l]:l+=1 while a[r]==b[r]:r-=1 if a[l:r+1]==b[l:r+1][::-1]: print("yes") print(1+min(l,r),1+max(l,r)) else: print("no") ```
output
1
35,531
12
71,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` #Sort the array #http://codeforces.com/problemset/problem/451/B #Is is possible to sort the array in increasing order by reversing 1 segment #1 2 5 4 3 6 7 n = int(input()) ls = list(map(int,input().split())) l = 0 r = 0 start = False sub_ls = [] for i in range(n-1): if ls[i+1] < ls[i]: if start == False: start = True l = i sub_ls.append(ls[i]) if i == n-2: sub_ls.append(ls[i+1]) r = i+1 elif start == True and ls[i+1] > ls[i]: sub_ls.append(ls[i]) r = i break sub_ls.reverse() if len(sub_ls) == 0: new_ls = ls else: new_ls = ls[0:l] + sub_ls + ls[r+1:] # print(sub_ls) # print(l,r) # print(new_ls) flag = True for j in range(n-1): if new_ls[j+1] < new_ls[j]: flag = False break if flag: print('yes') print(l+1,r+1) else: print('no') ```
instruction
0
35,532
12
71,064
Yes
output
1
35,532
12
71,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` if __name__ == '__main__': n = int(input()) arr = [int(x) for x in input().split()] # print(arr) m = 0 start = 0 end = 0 # for i in range(0,n): # for j in range(0,i+1): # # print(arr[j:i+1]) # new_arr.append(arr[:j]) # new_arr.append(arr[j:i+1:-1] # print(new_arr) # break for i in range(0,n-1): if(arr[i+1]<arr[i]): if(m==0): start = i m = 1 if((i+1)==(n-1)): end = n-1 elif(arr[i+1]>arr[i]): if(m==1): end = i break part = arr[start:end+1] part = part[::-1] new_arr = arr[:start] + part + arr[end+1:] if((start==0)&(end==0)): start = 1 end = 1 else: start = start + 1 end = end + 1 if(new_arr == sorted(arr)): print("yes") print(start,end) else: print("no") ```
instruction
0
35,533
12
71,066
Yes
output
1
35,533
12
71,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` n = int(input()) a = list(map(int,input().split())) x=y=0 for i in range(n-1): if a[i+1]<a[i]: x=i+1 break for i in range(n-1,0,-1): if a[i-1]>a[i]: y=i break if x==0 and y==0: print("yes") print('1 1') else: f=0 for i in range(max(x-1,0),y): if a[i]<a[i+1]: f=1 print("no") break if f==0 and (x==1 or y==n-1): if x==1: if y!=n-1: if a[0]<a[y+1]: print("yes") print(x,y+1) else: print("no") else: print("yes") print(x,y+1) else: if a[x-2]<a[n-1]: print("yes") print(x,y+1) else: print("no") elif f==0 and a[x-2]<a[y] and a[x-1]<a[y+1]: print("yes") print(x,y+1) elif f==0: print("no") ```
instruction
0
35,534
12
71,068
Yes
output
1
35,534
12
71,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` def process(a, n): reverse = [] b = sorted(a) for i in range(n): if a[i] != b[i]: reverse.append(i) if len(reverse) == 0: print("yes") print(1, 1) else: c = a[:] t = 0 for i in range(reverse[0], reverse[-1] + 1): c[i] = a[reverse[-1] - t] t += 1 for i in range(n): if c[i] != b[i]: print("no") return print("yes") print(reverse[0] + 1, reverse[-1] + 1) n = int(input()) a = list(map(int, input().split())) process(a, n) ```
instruction
0
35,535
12
71,070
Yes
output
1
35,535
12
71,071
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` import copy n=int(input()) li=list(map(int,input().split())) a=copy.deepcopy(li) li.sort() li1=[] c=0 for i in range(n): if(a[i]!=li[i]): c=c+1 li1.append(i+1) if(c==2): print("yes") print(li1[0],li1[1]) else: print("no") ```
instruction
0
35,536
12
71,072
No
output
1
35,536
12
71,073
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` n=int(input()) a=list(map(int,input().split(" "))) b=sorted(a) c=0 d=0 e=0 x=0 if len(a)>2: while x<n: if a[x]!=b[x]: d=x e=a[x] if e-1<len(a) and a[e-1]==d+1: f=a[e-1] pass else: print("no") c=1 break x+=1 if a==b: print("yes") print("1 1") elif len(a)==2: print("yes") print(f"{a[0]} {a[1]}") elif c==0: print("yes") print(f"{e} {f}") else: exit() ```
instruction
0
35,537
12
71,074
No
output
1
35,537
12
71,075
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` n=int(input()) a=[] a=[int(x) for x in input().split()] count=0 d=1 start=0 end=0 for i in range(1,len(a)): if a[i]<a[i-1]: if count==0: start=i-1 end=i count=1 else: end=end+1 elif count>0: if a[start]<a[i]: d=1 else: d=0 break if not start==0: if(a[start-1]<a[end]): d=1 else: d=0 for i in range(end,len(a)): if a[i]<a[i-1]: d=0 break if d==1 : print('yes') print(start+1,' ',end+1) else: print('no') ```
instruction
0
35,538
12
71,076
No
output
1
35,538
12
71,077
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n]. Submitted Solution: ``` import sys n = int(input()) a = list(map(int, input().split())) def findif(a, n): #if not a: # print('no') prev = a[n-1] i=n-2 reverse_left = 0 reverse_right = 0 is_true = True comparable = sys.maxsize while i>=0: cur = a[i] if cur<prev: if reverse_right and not reverse_left: reverse_left = i+1 elif cur>prev: if reverse_left: is_true = False break if not reverse_right: if i+2<n: comparable = a[i+2] reverse_right = i+1 if cur>comparable: is_true = False break prev = cur i-=1 return is_true, reverse_left, reverse_right is_true, reverse_left, reverse_right = findif(a, n) if is_true: print('yes') print(reverse_left+1, " ", reverse_right+1) else: print('no') ```
instruction
0
35,539
12
71,078
No
output
1
35,539
12
71,079
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains integers n, m and k (1 ≤ n, m ≤ 100 000, 0 ≤ k ≤ 1 000 000) — the length of the array, the number of queries and Bob's favorite number respectively. The second line contains n integers ai (0 ≤ ai ≤ 1 000 000) — Bob's array. Then m lines follow. The i-th line contains integers li and ri (1 ≤ li ≤ ri ≤ n) — the parameters of the i-th query. Output Print m lines, answer the queries in the order they appear in the input. Examples Input 6 2 3 1 2 1 1 0 3 1 6 3 5 Output 7 0 Input 5 3 1 1 1 1 1 1 1 5 2 4 1 3 Output 9 4 4 Note In the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query. In the second sample xor equals 1 for all subarrays of an odd length.
instruction
0
35,588
12
71,176
Tags: data structures Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): #n = int(input()) n, m, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() pre = [0] for i in range(n): pre += [a[i] ^ pre[-1]] BLOCK_SIZE = 320 queries = [[] for __ in range(BLOCK_SIZE)] ans = [0]*m for i in range(m): l, r = map(int, input().split()) queries[l // BLOCK_SIZE] += [[l - 1, r, i]] count = [0] * (1 << 20) for i in range(len(queries)): queries[i] = sorted(queries[i], key=lambda x: x[1]) if not queries[i]: continue left = right = BLOCK_SIZE * i count[pre[left]] += 1 res = 0 for l, r, index in queries[i]: while right < r: right += 1 res += count[pre[right] ^ k] count[pre[right]] += 1 while left < l: left += 1 count[pre[left - 1]] -= 1 res -= count[pre[left - 1] ^ k] while left > l: left -= 1 res += count[pre[left] ^ k] count[pre[left]] += 1 ans[index] = res while left <= right: left += 1 count[pre[left - 1]] -= 1 res -= count[pre[left - 1] ^ k] assert res == 0 for each in ans: print(each) ```
output
1
35,588
12
71,177
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains integers n, m and k (1 ≤ n, m ≤ 100 000, 0 ≤ k ≤ 1 000 000) — the length of the array, the number of queries and Bob's favorite number respectively. The second line contains n integers ai (0 ≤ ai ≤ 1 000 000) — Bob's array. Then m lines follow. The i-th line contains integers li and ri (1 ≤ li ≤ ri ≤ n) — the parameters of the i-th query. Output Print m lines, answer the queries in the order they appear in the input. Examples Input 6 2 3 1 2 1 1 0 3 1 6 3 5 Output 7 0 Input 5 3 1 1 1 1 1 1 1 5 2 4 1 3 Output 9 4 4 Note In the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query. In the second sample xor equals 1 for all subarrays of an odd length.
instruction
0
35,589
12
71,178
Tags: data structures Correct Solution: ``` # [https://codeforces.com/contest/617/submission/15550846 <- https://codeforces.com/blog/entry/22971 <- https://codeforces.com/problemset/problem/617/E <- https://algoprog.ru/material/pc617pE] BLOCK_SIZE = 316 #sqrt(1e5) class Query: def __init__(self, left, right, number): self.left = left self.right = right self.number = number def __lt__(self, other): return self.right < other.right cnt = [0] * (1 << 20) result = 0 favourite = 0 def add(v): global result result += cnt[v ^ favourite] cnt[v] += 1 def delv(v): global result cnt[v] -= 1 result -= cnt[v ^ favourite] (n, m, favourite) = map(int, input().split()) a = list(map(int, input().split())) pref = [0] * (n + 1) for i in range(1, n + 1): pref[i] = pref[i - 1] ^ a[i - 1] blocks = [[] for i in range(n // BLOCK_SIZE + 2)] for i in range(m): (left, right) = map(int, input().split()) left -= 1 right += 1 blocks[left // BLOCK_SIZE].append(Query(left, right, i)) for b in blocks: b.sort() answer = [0] * m for i in range(len(blocks)): left = i * BLOCK_SIZE right = left for q in blocks[i]: while right < q.right: add(pref[right]) right += 1 while left < q.left: delv(pref[left]) left += 1 while left > q.left: left -= 1 add(pref[left]) answer[q.number] = result for j in range(left, right): delv(pref[j]) print(*answer, sep = "\n") ```
output
1
35,589
12
71,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of t given subarrays. Input First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly. Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array. Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray. Output Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Examples Input 3 2 1 2 1 1 2 1 3 Output 3 6 Input 8 3 1 1 2 2 1 3 1 1 2 7 1 6 2 7 Output 20 20 20 Note Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): <image> Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20. Submitted Solution: ``` n, t = input().split() n = int(n) t = int(t) mas = [int(i) for i in input().split()] i=0 diap = [[0 for i in range(2)]for j in range(t)] while i<t: a,b = input().split() a= int(a) b= int(b) diap[i][0]=a diap[i][1]=b i+=1 otv=0 for i in diap: tmp = [mas[i] for i in range(i[0]-1,i[1])] ma=max(tmp) while(ma!=0): otv= otv + tmp.count(ma)*(ma**2) for j in range(len(tmp)): if(tmp[j] == ma): tmp[j]=0 ma=max(tmp) print(otv) otv=0 ```
instruction
0
35,709
12
71,418
No
output
1
35,709
12
71,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of t given subarrays. Input First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly. Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array. Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray. Output Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Examples Input 3 2 1 2 1 1 2 1 3 Output 3 6 Input 8 3 1 1 2 2 1 3 1 1 2 7 1 6 2 7 Output 20 20 20 Note Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): <image> Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20. Submitted Solution: ``` # n=int(input()) # n,k=map(int,input().split()) # arr=list(map(int,input().split())) #ls=list(map(int,input().split())) #for i in range(m): # for _ in range(int(input())): from collections import Counter #from fractions import Fraction #n=int(input()) #arr=list(map(int,input().split())) #ls = [list(map(int, input().split())) for i in range(n)] from math import log2 #for _ in range(int(input())): #n, m = map(int, input().split()) # for _ in range(int(input())): from math import gcd #n=int(input()) #def fxn(l_ptr,r_ptr,l,r,p): l_ptr=0 r_ptr=0 p=0 n, m = map(int, input().split()) arr=list(map(int,input().split())) q=[] for i in range(m): u,v=map(int, input().split()) q.append((u,v)) q.sort(key=lambda x : x[1] ) f=[0]*(10**6+1) for i in range(m): var=q[i] l=var[0] r=var[1] while l_ptr<l-1: f1=f[arr[l_ptr]] f[arr[l_ptr]]-=1 p-=f1*f1*arr[l_ptr] p+=f[arr[l_ptr]]*f[arr[l_ptr]]*arr[l_ptr] l_ptr+=1 while l_ptr>=l: ### f1 = f[arr[l_ptr]] f[arr[l_ptr]]-=1 p-= f1 * f1 * arr[l_ptr] p += f[arr[l_ptr]] * f[arr[l_ptr]] * arr[l_ptr] l_ptr -= 1 while r_ptr<=r-1: f1 = f[arr[r_ptr]] f[arr[r_ptr]]+=1 p-= f1 * f1 * arr[r_ptr] p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr] r_ptr +=1 while r_ptr>r: r_ptr -= 1 f1 = f[arr[r_ptr]] f[arr[r_ptr]] -= 1 p -= f1 * f1 * arr[l_ptr] p += f[arr[r_ptr]] * f[arr[r_ptr]] * arr[r_ptr] #t=fxn(l_ptr,r_ptr,var[0],var[1],p) print(p) ```
instruction
0
35,710
12
71,420
No
output
1
35,710
12
71,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of t given subarrays. Input First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly. Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array. Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray. Output Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Examples Input 3 2 1 2 1 1 2 1 3 Output 3 6 Input 8 3 1 1 2 2 1 3 1 1 2 7 1 6 2 7 Output 20 20 20 Note Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): <image> Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20. Submitted Solution: ``` # from debug import debug import sys; input = sys.stdin.readline n, q = map(int, input().split()) lis = list(map(int, input().split())) querry = [] for i in range(q): a,b = map(int, input().split()) querry.append((i, a, b)) D = int(n**0.5) querry.sort(key=lambda x: (x[1]/D, x[2])) cnt = [0]*int(1e6) ans = [0]*q ml, mr = 0, -1 cur = 0 for i, l, r in querry: l-=1; r-=1 while ml<l: p = cnt[lis[ml]] cnt[lis[ml]] -= 1 # cur += (cnt[lis[ml]]**2 - p**2)*lis[ml] cur -= (2*p -1)*lis[ml] ml+=1 while ml>l: ml-=1 p = cnt[lis[ml]] cnt[lis[ml]] += 1 # cur += (cnt[lis[ml]]**2 - p**2)*lis[ml] cur += (2*p+1)*lis[ml] while mr<r: mr+=1 p = cnt[lis[mr]] cnt[lis[mr]] += 1 # cur += (cnt[lis[mr]]**2 - p**2)*lis[mr] cur += (2*p+1)*lis[mr] ans[i] = cur for i in ans: print(i) ```
instruction
0
35,711
12
71,422
No
output
1
35,711
12
71,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of t given subarrays. Input First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly. Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array. Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray. Output Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Examples Input 3 2 1 2 1 1 2 1 3 Output 3 6 Input 8 3 1 1 2 2 1 3 1 1 2 7 1 6 2 7 Output 20 20 20 Note Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): <image> Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20. Submitted Solution: ``` def main(): n, t = map(int, input().split()) aa = list(map(int, input().split())) max_a = max(aa) + 1 p = int(n ** .5 + .4) qq = [[] for i in range((n + p - 1) // p)] for i in range(t): lo, hi = map(int, input().split()) lo -= 1 qq[lo // p].append((hi, lo, i)) res = [0] * t left = [0] * max_a leftpos = 0 for chank in qq: if not chank: continue chank.sort() hi, lo, i = chank[0] while leftpos < lo: left[aa[leftpos]] += 1 leftpos += 1 right = left[:] tot = 0 rightpos = lo while rightpos < hi: a = aa[rightpos] v = right[a] - left[a] right[a] += 1 tot += (v * 2 + 1) * a rightpos += 1 for hi, lo, i in chank: while leftpos < lo: a = aa[leftpos] v = right[a] - left[a] left[a] += 1 tot -= (v * 2 - 1) * a leftpos += 1 while leftpos > lo: a = aa[leftpos] v = right[a] - left[a] left[a] = v - 1 v tot += (v * 2 + 1) * a leftpos -= 1 while rightpos < hi: a = aa[rightpos] v = right[a] - left[a] right[a] = v + 1 tot += (v * 2 + 1) * a rightpos += 1 res[i] = tot for a in aa: right[a] += 1 print('\n'.join(map(str, res))) if __name__ == '__main__': main() ```
instruction
0
35,712
12
71,424
No
output
1
35,712
12
71,425
Provide a correct Python 3 solution for this coding contest problem. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050
instruction
0
35,889
12
71,778
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) import itertools MOD = 10**9 + 7 # 右側に自身より低い数値をいくつ残せているか N,*A = map(int,read().split()) A_rev = A[::-1] class BIT(): def __init__(self, max_n): self.size = max_n + 1 self.tree = [0] * self.size def get_sum(self,i): s = 0 while i: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i < self.size: self.tree[i] += x i += i & -i right_zero = [0] * (N+1) for i,x in enumerate(A_rev): right_zero[i+1] = right_zero[i] if x == 0: right_zero[i+1] += 1 zero_cnt = right_zero[-1] inv = pow(zero_cnt,MOD-2,MOD) rest_smaller = [1] * (N+1) for x in A: rest_smaller[x] = 0 rest_smaller = list(itertools.accumulate(rest_smaller)) right_smaller_prob = [(MOD+1)//2] * N for i,x in enumerate(A_rev): if x != 0: right_smaller_prob[i] = rest_smaller[x] * inv right_smaller_filled = [0] * N bit = BIT(max_n = N) p = 0 for i,x in enumerate(A_rev): if x != 0: right_smaller_filled[i] = bit.get_sum(x) bit.add(x,1) p += zero_cnt-rest_smaller[x] else: right_smaller_filled[i] = p * inv fact = [1] * (N+1) for n in range(1,N+1): fact[n] = fact[n-1] * n % MOD answer = (1+sum(y*(x*p+z) for x,p,y,z in zip(right_zero,right_smaller_prob,fact,right_smaller_filled))) * fact[zero_cnt] % MOD print(answer) ```
output
1
35,889
12
71,779
Provide a correct Python 3 solution for this coding contest problem. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050
instruction
0
35,890
12
71,780
"Correct Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") M = 10**9+7 n = int(input()) p = list(map(int, input().split())) g1 = [None]*(n+10) v = 1 g1[0] = 1 for i in range(1,len(g1)): v *= i v %= M g1[i] = v def init(bit, values): for i,v in enumerate(values): add(bit,i+1,v) #a1 ~ aiまでの和 O(logn) def query(bit,i): res = 0 while i > 0: res += bit[i] i -= i&(-i) return res #ai += x(logN) def add(bit,i,x): if i==0: raise RuntimeError while i <= len(bit)-1: bit[i] += x i += i&(-i) return index = [i for i,num in enumerate(p) if num==0] used = [False]*n for i in range(n): if p[i]>0: used[p[i]-1] = True nl = [] for i in range(n): if not used[i]: nl.append(i+1) nl.sort() scores = [0]*(n+1) # scores[i]: nlのうちiより大きいものの個数 v = len(nl) cur = 0 for i in range(1,n+1): if nl and cur<len(nl) and nl[cur]<i: # if nl and nl[cur]<i: cur += 1 v -= 1 scores[i] = v ans = 0 bit = [0]*(n+1) s = set(index) val = 0 pp = len(index) # 欠損の個数 ss = sum(nl) num = 0 inv2 = pow(2, M-2, M) for i in range(n): if p[i]==0: ans += (g1[pp-1] * (ss - pp - val - pp*(num)*inv2)) * g1[n-i-1] num += 1 else: ans += (g1[pp] * (p[i]-query(bit, p[i])-1) - g1[pp-1]*num*(len(nl)-scores[p[i]])) * g1[n-i-1] add(bit, p[i], 1) val += scores[p[i]] ans %= M # print(ans, val) print((ans + g1[pp])%M) ```
output
1
35,890
12
71,781
Provide a correct Python 3 solution for this coding contest problem. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050
instruction
0
35,891
12
71,782
"Correct Solution: ``` """ https://atcoder.jp/contests/code-festival-2016-qualc/tasks/codefestival_2016_qualC_e ページの合計に与える寄与を考えればよい ある位置iにある数字の与える寄与は (自分より右にある数字の数)! * 自分より右にあるより小さい数字の数 元からおかれている数字同士に関しての寄与はBITで終わり 元からおかれている数字 & 自由な数字の寄与は 順列の総数 * 自由な数字の中で自分より小さいものの数 * 右にある空欄の数 / 全ての空欄の数 * fac[N-1-i] 順列の総数 * 自由な数字の中で自分より大きいものの数 * 左にある空欄の数 / 全ての空欄の数 * fac[N-1-i] で求まる 自由同士は、半分になるはずなので fac[N-1-i] * 右にある0の数 // 2 それより左にあるfacの平均を出す?→avrage 順列の総数 * 自由な数字の中で自分より大きいものの数 * 左にある空欄の数 / 全ての空欄の数 * average """ mod = 10**9+7 #逆元 def inverse(a,mod): #aのmodを法にした逆元を返す return pow(a,mod-2,mod) #modのn!と、n!の逆元を格納したリストを返す(拾いもの) #factorialsには[1, 1!%mod , 2!%mod , 6!%mod… , n!%mod] が入っている #invsには↑の逆元が入っている def modfac(n, MOD): f = 1 factorials = [1] for m in range(1, n + 1): f *= m f %= MOD factorials.append(f) inv = pow(f, MOD - 2, MOD) invs = [1] * (n + 1) invs[n] = inv for m in range(n, 1, -1): inv *= m inv %= MOD invs[m - 1] = inv return factorials, invs def modnCr(n,r,mod,fac,inv): #上で求めたfacとinvsを引数に入れるべし(上の関数で与えたnが計算できる最大のnになる) return fac[n] * inv[n-r] * inv[r] % mod def bitadd(a,w,bit): #aにwを加える(1-origin) x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): #ind 1~aまでの和を求める ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret import sys from sys import stdin N = int(stdin.readline()) a = list(map(int,stdin.readline().split())) BIT = [0] * (N+1) fac,inv = modfac(N+10,mod) zeronum = 0 ans1 = 0 RZ = [0] * N app = [False] * (N+1) app[0] = True for i in range(N-1,-1,-1): if a[i] != 0: ans1 += fac[N-1-i] * ( bitsum(a[i],BIT) ) ans1 %= mod bitadd(a[i],1,BIT) app[a[i]] = True else: zeronum += 1 RZ[i] = zeronum mEX = [0] * (N+1) #数字x以下の数がいくつあるか for i in range(1,N+1): if app[i] == False: mEX[i] = mEX[i-1] + 1 else: mEX[i] = mEX[i-1] ans1 *= fac[zeronum] ans2 = 0 ans3 = 0 tmpinv = inverse(zeronum,mod) tmpsum = 0 for i in range(N): if a[i] != 0: ans2 += fac[zeronum] * mEX[a[i]] * RZ[i] * tmpinv * fac[N-1-i] ans2 += fac[zeronum] * (zeronum-mEX[a[i]]) * tmpinv * tmpsum ans2 %= mod else: ans3 += fac[N-1-i] * fac[zeronum] * (RZ[i]-1) * inverse(2,mod) tmpsum += fac[N-1-i] print (ans1 , ans2 , ans3 , fac[zeronum],file=sys.stderr) print ((ans1 + ans2 + ans3 + fac[zeronum]) % mod) ```
output
1
35,891
12
71,783
Provide a correct Python 3 solution for this coding contest problem. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050
instruction
0
35,892
12
71,784
"Correct Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") M = 10**9+7 n = int(input()) p = list(map(int, input().split())) g1 = [None]*(n+10) v = 1 g1[0] = 1 for i in range(1,len(g1)): v *= i v %= M g1[i] = v def init(bit, values): for i,v in enumerate(values): add(bit,i+1,v) #a1 ~ aiまでの和 O(logn) def query(bit,i): res = 0 while i > 0: res += bit[i] i -= i&(-i) return res #ai += x(logN) def add(bit,i,x): if i==0: raise RuntimeError while i <= len(bit)-1: bit[i] += x i += i&(-i) return index = [i for i,num in enumerate(p) if num==0] used = [False]*n for i in range(n): if p[i]>0: used[p[i]-1] = True nl = [] for i in range(n): if not used[i]: nl.append(i+1) nl.sort() scores = [0]*(n+1) # scores[i]: nlのうちiより大きいものの個数 v = len(nl) cur = 0 for i in range(1,n+1): if nl and cur<len(nl) and nl[cur]<i: # if nl and nl[cur]<i: cur += 1 v -= 1 scores[i] = v ans = 0 bit = [0]*(n+1) s = set(index) val = 0 pp = len(index) # 欠損の個数 ss = sum(nl) num = 0 inv2 = pow(2, M-2, M) for i in range(n): if i in s: ans += (g1[pp-1] * (ss - pp - val - pp*(num)*inv2)) * g1[n-i-1] num += 1 else: ans += (g1[pp] * (p[i]-query(bit, p[i])-1) - g1[pp-1]*num*(len(nl)-scores[p[i]])) * g1[n-i-1] add(bit, p[i], 1) val += scores[p[i]] ans %= M # print(ans, val) print((ans + g1[pp])%M) ```
output
1
35,892
12
71,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050 Submitted Solution: ``` N = int(input()) P = list(map(lambda x: int(x), input().split())) if 0 not in P: print(2) ```
instruction
0
35,893
12
71,786
No
output
1
35,893
12
71,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050 Submitted Solution: ``` """ https://atcoder.jp/contests/code-festival-2016-qualc/tasks/codefestival_2016_qualC_e ページの合計に与える寄与を考えればよい ある位置iにある数字の与える寄与は (自分より右にある数字の数)! * 自分より右にあるより小さい数字の数 元からおかれている数字同士に関しての寄与はBITで終わり 元からおかれている数字 & 自由な数字の寄与は 順列の総数 * 自由な数字の中で自分より小さいものの数 * 右にある空欄の数 / 全ての空欄の数 * fac[N-1-i] 順列の総数 * 自由な数字の中で自分より大きいものの数 * 左にある空欄の数 / 全ての空欄の数 * fac[N-1-i] で求まる 自由同士は、半分になるはずなので fac[N-1-i] * 右にある0の数 // 2 それより左にあるfacの平均を出す?→avrage 順列の総数 * 自由な数字の中で自分より大きいものの数 * 左にある空欄の数 / 全ての空欄の数 * average """ mod = 10**9+7 #逆元 def inverse(a,mod): #aのmodを法にした逆元を返す return pow(a,mod-2,mod) #modのn!と、n!の逆元を格納したリストを返す(拾いもの) #factorialsには[1, 1!%mod , 2!%mod , 6!%mod… , n!%mod] が入っている #invsには↑の逆元が入っている def modfac(n, MOD): f = 1 factorials = [1] for m in range(1, n + 1): f *= m f %= MOD factorials.append(f) inv = pow(f, MOD - 2, MOD) invs = [1] * (n + 1) invs[n] = inv for m in range(n, 1, -1): inv *= m inv %= MOD invs[m - 1] = inv return factorials, invs def modnCr(n,r,mod,fac,inv): #上で求めたfacとinvsを引数に入れるべし(上の関数で与えたnが計算できる最大のnになる) return fac[n] * inv[n-r] * inv[r] % mod def bitadd(a,w,bit): #aにwを加える(1-origin) x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): #ind 1~aまでの和を求める ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret import sys from sys import stdin N = int(stdin.readline()) a = list(map(int,stdin.readline().split())) BIT = [0] * (N+1) fac,inv = modfac(N+10,mod) zeronum = 0 ans1 = 0 RZ = [0] * N app = [False] * (N+1) app[0] = True for i in range(N-1,-1,-1): if a[i] != 0: ans1 += fac[N-1-i] * ( bitsum(a[i],BIT) ) ans1 %= mod bitadd(a[i],1,BIT) app[a[i]] = True else: zeronum += 1 RZ[i] = zeronum mEX = [0] * (N+1) #数字x以下の数がいくつあるか for i in range(1,N+1): if app[i] == False: mEX[i] = mEX[i-1] + 1 else: mEX[i] = mEX[i-1] ans1 *= fac[zeronum] ans2 = 0 ans3 = 0 tmpinv = inverse(zeronum,mod) tmpsum = 0 for i in range(N): if a[i] != 0: ans2 += fac[zeronum] * mEX[a[i]] * RZ[i] * tmpinv * fac[N-1-i] ans2 += fac[zeronum] * (zeronum-mEX[a[i]]) * tmpinv * tmpsum ans2 %= mod else: ans3 += fac[N-1-i] * fac[zeronum] * (RZ[i]-1) // 2 tmpsum += fac[N-1-i] print (ans1 , ans2 , ans3 , fac[zeronum],file=sys.stderr) print ((ans1 + ans2 + ans3 + fac[zeronum]) % mod) ```
instruction
0
35,894
12
71,788
No
output
1
35,894
12
71,789
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050 Submitted Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n = int(input()) p = list(map(int, input().split())) g1 = [None]*(n+10) v = 1 g1[0] = 1 for i in range(1,len(g1)): v *= i v %= M g1[i] = v def init(bit, values): for i,v in enumerate(values): add(bit,i+1,v) #a1 ~ aiまでの和 O(logn) def query(bit,i): res = 0 while i > 0: res += bit[i] i -= i&(-i) return res #ai += x(logN) def add(bit,i,x): if i==0: raise RuntimeError while i <= len(bit)-1: bit[i] += x i += i&(-i) return index = [i for i,num in enumerate(p) if num==0] used = [False]*n for i in range(n): if p[i]>0: used[p[i]-1] = True nl = [] for i in range(n): if not used[i]: nl.append(i+1) nl.sort() scores = [0]*(n+1) # scores[i]: nlのうちiより大きいものの個数 v = len(nl) cur = 0 for i in range(1,n+1): if nl and nl[cur]<i: cur += 1 v -= 1 scores[i] = v ans = 0 bit = [0]*(n+1) s = set(index) val = 0 pp = len(index) # 欠損の個数 ss = sum(nl) num = 0 inv2 = pow(2, M-2, M) for i in range(n): if i in s: ans += (g1[pp-1] * (ss - pp - val - pp*(num)*inv2)) * g1[n-i-1] num += 1 else: ans += (g1[pp] * (p[i]-query(bit, p[i])-1) - g1[pp-1]*num*(len(nl)-scores[p[i]])) * g1[n-i-1] add(bit, p[i], 1) val += scores[p[i]] ans %= M # print(ans, val) print((ans + g1[pp])%M) ```
instruction
0
35,895
12
71,790
No
output
1
35,895
12
71,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050 Submitted Solution: ``` import math import itertools def page(p): c = 1 lenp = len(p) ref = list(range(1, lenp + 1)) for i, n in enumerate(p[:-1], start=1): c += ref.index(n) * math.factorial(lenp - i) ref.remove(n) return c def gen(p): nums = set(range(1, len(p) + 1)) - set(p) indices = [i for i, x in enumerate(p) if x == 0] if not nums: yield p raise StopIteration for perm in itertools.permutations(nums): for i, n in zip(indices, perm): p[i] = n yield p def main(): n = int(input()) p = [int(n) for n in input().split()] c = 0 for l in gen(p): c += page(l) print(c % (10 ** 9 + 7)) if __name__ == '__main__': main() ```
instruction
0
35,896
12
71,792
No
output
1
35,896
12
71,793