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. You are given an array a_1, a_2, ... , a_n and two integers m and k. You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x. The cost of empty subarray is equal to zero. For example, if m = 3, k = 10 and a = [2, -4, 15, -3, 4, 8, 3], then the cost of some subarrays are: * a_3 ... a_3: 15 - k ⌈ 1/3 ⌉ = 15 - 10 = 5; * a_3 ... a_4: (15 - 3) - k ⌈ 2/3 ⌉ = 12 - 10 = 2; * a_3 ... a_5: (15 - 3 + 4) - k ⌈ 3/3 ⌉ = 16 - 10 = 6; * a_3 ... a_6: (15 - 3 + 4 + 8) - k ⌈ 4/3 ⌉ = 24 - 20 = 4; * a_3 ... a_7: (15 - 3 + 4 + 8 + 3) - k ⌈ 5/3 ⌉ = 27 - 20 = 7. Your task is to find the maximum cost of some subarray (possibly empty) of array a. Input The first line contains three integers n, m, and k (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 10, 1 ≤ k ≤ 10^9). The second line contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9). Output Print the maximum cost of some subarray of array a. Examples Input 7 3 10 2 -4 15 -3 4 8 3 Output 7 Input 5 2 1000 -13 -4 -9 -20 -11 Output 0 Submitted Solution: ``` def naiveSolve(n): return from collections import defaultdict def main(): # A solution will be 0 or include a maximal subarray sum # Kadane's to find maximal subarray sums maxSum=defaultdict(lambda:-inf) # {length:sum} n,m,k=readIntArr() a=readIntArr() l=0 t=0 for x in a: t+=x l+=1 if t<0: # restart t=0 l=0 else: maxSum[l]=max(maxSum[l],t) ans=0 for l,summ in maxSum.items(): ans=max(ans,summ-k*((l+m-1)//m)) print(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(l,r): print('? {} {}'.format(l,r)) sys.stdout.flush() return int(input()) def answerInteractive(x): print('! {}'.format(x)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil for _abc in range(1): main() ```
instruction
0
95,363
12
190,726
No
output
1
95,363
12
190,727
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n and two integers m and k. You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x. The cost of empty subarray is equal to zero. For example, if m = 3, k = 10 and a = [2, -4, 15, -3, 4, 8, 3], then the cost of some subarrays are: * a_3 ... a_3: 15 - k ⌈ 1/3 ⌉ = 15 - 10 = 5; * a_3 ... a_4: (15 - 3) - k ⌈ 2/3 ⌉ = 12 - 10 = 2; * a_3 ... a_5: (15 - 3 + 4) - k ⌈ 3/3 ⌉ = 16 - 10 = 6; * a_3 ... a_6: (15 - 3 + 4 + 8) - k ⌈ 4/3 ⌉ = 24 - 20 = 4; * a_3 ... a_7: (15 - 3 + 4 + 8 + 3) - k ⌈ 5/3 ⌉ = 27 - 20 = 7. Your task is to find the maximum cost of some subarray (possibly empty) of array a. Input The first line contains three integers n, m, and k (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 10, 1 ≤ k ≤ 10^9). The second line contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9). Output Print the maximum cost of some subarray of array a. Examples Input 7 3 10 2 -4 15 -3 4 8 3 Output 7 Input 5 2 1000 -13 -4 -9 -20 -11 Output 0 Submitted Solution: ``` n,m,k=map(int,input().split()) a=list(map(int,input().split())) c=[0] for i in range(n): c.append(c[-1]+a[i]) r=n l=0 ans=0 while r>l: ans=max(ans,c[r]-c[l]+k*(-(r-l)//m)) if a[l]<=a[r-1]: l+=1 else: r-=1 print(ans) ```
instruction
0
95,364
12
190,728
No
output
1
95,364
12
190,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n and two integers m and k. You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x. The cost of empty subarray is equal to zero. For example, if m = 3, k = 10 and a = [2, -4, 15, -3, 4, 8, 3], then the cost of some subarrays are: * a_3 ... a_3: 15 - k ⌈ 1/3 ⌉ = 15 - 10 = 5; * a_3 ... a_4: (15 - 3) - k ⌈ 2/3 ⌉ = 12 - 10 = 2; * a_3 ... a_5: (15 - 3 + 4) - k ⌈ 3/3 ⌉ = 16 - 10 = 6; * a_3 ... a_6: (15 - 3 + 4 + 8) - k ⌈ 4/3 ⌉ = 24 - 20 = 4; * a_3 ... a_7: (15 - 3 + 4 + 8 + 3) - k ⌈ 5/3 ⌉ = 27 - 20 = 7. Your task is to find the maximum cost of some subarray (possibly empty) of array a. Input The first line contains three integers n, m, and k (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 10, 1 ≤ k ≤ 10^9). The second line contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9). Output Print the maximum cost of some subarray of array a. Examples Input 7 3 10 2 -4 15 -3 4 8 3 Output 7 Input 5 2 1000 -13 -4 -9 -20 -11 Output 0 Submitted Solution: ``` from math import ceil n, m, k = map(int, input().split()) a = list(map(int, input().split())) s = 0 res = 0 l = -1 for i in range(n): if s <= 0: l = i s = a[i] else: s += a[i] res = max(res, s - k * ceil((i-l+1)/m)) print(res) ```
instruction
0
95,365
12
190,730
No
output
1
95,365
12
190,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n and two integers m and k. You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x. The cost of empty subarray is equal to zero. For example, if m = 3, k = 10 and a = [2, -4, 15, -3, 4, 8, 3], then the cost of some subarrays are: * a_3 ... a_3: 15 - k ⌈ 1/3 ⌉ = 15 - 10 = 5; * a_3 ... a_4: (15 - 3) - k ⌈ 2/3 ⌉ = 12 - 10 = 2; * a_3 ... a_5: (15 - 3 + 4) - k ⌈ 3/3 ⌉ = 16 - 10 = 6; * a_3 ... a_6: (15 - 3 + 4 + 8) - k ⌈ 4/3 ⌉ = 24 - 20 = 4; * a_3 ... a_7: (15 - 3 + 4 + 8 + 3) - k ⌈ 5/3 ⌉ = 27 - 20 = 7. Your task is to find the maximum cost of some subarray (possibly empty) of array a. Input The first line contains three integers n, m, and k (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 10, 1 ≤ k ≤ 10^9). The second line contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9). Output Print the maximum cost of some subarray of array a. Examples Input 7 3 10 2 -4 15 -3 4 8 3 Output 7 Input 5 2 1000 -13 -4 -9 -20 -11 Output 0 Submitted Solution: ``` import sys n, m, k = list(map(int, sys.stdin.readline().strip().split())) a = list(map(int, sys.stdin.readline().strip().split())) b = [0] * n b[0] = m * a[0] - k for i in range (1, n): b[i] = b[i-1] + m * a[i] - k M = [10 ** 20] * m ans = 0 for i in range (0, n): M[b[i] % m] = min([M[b[i] % m], b[i]]) for j in range (0, m): ans = max([ans, b[i]-M[j]-k*((m-(i-j))%m)]) #print(M, ans) print(ans // m) ```
instruction
0
95,366
12
190,732
No
output
1
95,366
12
190,733
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,393
12
190,786
Tags: brute force, dp, greedy, implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = (list(map(int, input().split()))) l = len(a) if(l == 1): if(a[0]%2 == 0): print(1) print(1) else: print(-1) else: if(a[0]%2 == 0): print(1) print(1) elif((a[1])%2==0): print(1) print(2) else: print(2) print(1,2) ```
output
1
95,393
12
190,787
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,394
12
190,788
Tags: brute force, dp, greedy, implementation Correct Solution: ``` n = int(input()) for i in range(n): m = int(input()) l = list(map(int,input().split())) count = 0 flag = 0 for i in range(len(l)): if l[i]%2==0: flag = 1 count += 1 print(count) print(l.index(l[i])+1) break if flag==0: if len(l)==1: print(-1) elif len(l)>1: print(2) print(1,2) ```
output
1
95,394
12
190,789
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,395
12
190,790
Tags: brute force, dp, greedy, implementation Correct Solution: ``` from sys import stdin from collections import deque from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin, tan def ii(): return int(stdin.readline()) def fi(): return float(stdin.readline()) def mi(): return map(int, stdin.readline().split()) def fmi(): return map(float, stdin.readline().split()) def li(): return list(mi()) def lsi(): x=list(stdin.readline()) x.pop() return x def si(): return stdin.readline() ############# CODE STARTS HERE ############# for _ in range(ii()): n=ii() a=li() f=-1 for i in range(n): if not a[i]%2: f=i+1 if f==-1: if n>1: print(2) print(1, 2) else: print(f) else: print(1) print(f) ```
output
1
95,395
12
190,791
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,396
12
190,792
Tags: brute force, dp, greedy, implementation Correct Solution: ``` #!/bin/python3 t = int(input()) while t > 0: n = int(input()) array = list(map(int, input().split())) if n == 1: # 1 is 00000001 in binary , and 2 is 00000010 # for future reference 1 bitwise AND 2 is false # that's a fancy way to say array[0] == 1 if array[0] & 1: print(-1) else: print("1\n1") else: # nb: every fucking odd number has 1 in the # very right digit in binary i.e. 3 is 00000011 # 5 is 00000101 and so on.... if (array[0] & 1) and (array[1] & 1): print("2\n1 2\n") else: print(1) if array[0] & 1: print(2) else: print(1) t -= 1 ```
output
1
95,396
12
190,793
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,397
12
190,794
Tags: brute force, dp, greedy, implementation Correct Solution: ``` #!/usr/bin/env python3 t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) odd = [] even = [] for k in range(n): if a[k] & 1: odd.append(k) else: even.append(k) if len(even): print(1) print(even[0] + 1) elif len(odd) >= 2: print(2) print(odd[0] + 1, odd[1] + 1) else: print(-1) ```
output
1
95,397
12
190,795
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,398
12
190,796
Tags: brute force, dp, greedy, implementation Correct Solution: ``` t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) result1 = [] flag = False for s in range(len(arr)): if arr[s] % 2 == 0: print(1) print(s+1) flag = True break else: result1.append(s+1) if len(result1) == 2: break if flag: continue elif len(result1) == 2: print(2) for j in result1: print(j, end=' ') else: print(-1) ```
output
1
95,398
12
190,797
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,399
12
190,798
Tags: brute force, dp, greedy, implementation Correct Solution: ``` for case in range(int(input())): n = int(input()) a = list(map(int, input().split())) odd = -1 for i in range(n): if a[i] & 1 and odd == -1: odd = i elif a[i] & 1: print(2) print(odd + 1, i + 1) break else: print(1) print(i + 1) break else: print(-1) ```
output
1
95,399
12
190,799
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum.
instruction
0
95,400
12
190,800
Tags: brute force, dp, greedy, implementation Correct Solution: ``` # coding: utf-8 # Your code here! # coding: utf-8 # Your code here! q=int(input()) for _ in range(q): N=int(input()) A=list(map(int,input().split())) even=[] odd=[] for i in range(len(A)): if A[i]%2==0: even.append(i+1) break else: odd.append(i+1) if even: print(1) print(even[0]) else: if len(odd)>1: print(2) print(odd[0],odd[1]) else: print(-1) ```
output
1
95,400
12
190,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` import sys, os.path if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') test=int(input()) for _ in range(test): n=int(input()) arr=input().split() flag=1 if n>1: for i in range(n): if int(arr[i])%2==0 and flag==1: print(1) print(i+1) flag=0 if flag!=0: print(2) print(1,end=" ") print(2) elif n==1: if int(arr[0])%2==0: print(1) print(1) else: print(-1) ```
instruction
0
95,402
12
190,804
Yes
output
1
95,402
12
190,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) for i in range(n): if a[i] % 2 == 0: print(1) print(i + 1) break if i > 0: print(2) print(1, 2) break else: print(-1) ```
instruction
0
95,403
12
190,806
Yes
output
1
95,403
12
190,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` from sys import stdin, stdout input = stdin.readline print = stdout.write def main(): t = int(input()) for _ in [0] * t: n = int(input()) odd = [] even = [] a = list(map(int, input().strip().split())) for i in range(n): if a[i] % 2: odd.append(i) if len(odd) == 2: break else: even.append(i) break if not even and len(odd) == 2: print(str(2) + '\n') for i in odd: print(str(i + 1) + ' ') elif even: print(str(1) + '\n') print(str(even[0] + 1)) else: print(str(-1)) print('\n') main() ```
instruction
0
95,404
12
190,808
Yes
output
1
95,404
12
190,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` from sys import stdin,stdout t=int(stdin.readline().strip()) for _ in range(t): n=int(stdin.readline().strip()) a=list(map(int,stdin.readline().strip().split())) f=0 for i in range(n): if a[i]%2==0: ans=i+1 stdout.write("1"+"\n") stdout.write(str(ans)+"\n") f=1 if f==0: if n==1: stdout.write("-1"+"\n") else: stdout.write("2"+"\n"+str(1)+" "+str(2)+"\n") ```
instruction
0
95,405
12
190,810
No
output
1
95,405
12
190,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` def rs(): return input().rstrip() def ri(): return int(rs()) def ra(): return list(map(int, rs().split())) def is_odd(a): return (a % 2) == 1 def is_even(a): return (a % 2) == 0 t = ri() for _ in range(t): n = ri() arr = ra() if len(arr) == 1: if is_odd(arr[0]): print(-1) else: print("1\n1") elif len(arr) > 1: f = arr[0] s = arr[1] if is_even(f): print("1\n1") elif is_even(s): print("1\n2") else: print(1) print(1, 2) ```
instruction
0
95,406
12
190,812
No
output
1
95,406
12
190,813
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` def rs(): return input().rstrip() def ri(): return int(rs()) def ra(): return list(map(int, rs().split())) def is_odd(a): return (a % 2) == 1 def is_even(a): return (a % 2) == 0 t = ri() for _ in range(t): n = ri() arr = ra() if len(arr) == 1: if is_odd(arr[0]): print(-1) else: print("1\n1") elif len(arr) > 1: f = arr[0] s = arr[1] if is_even(f): print("1\n1") elif is_even(s): print("1\n2") else: print("1\n1 2") ```
instruction
0
95,407
12
190,814
No
output
1
95,407
12
190,815
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≤ t ≤ 100), number of test cases to solve. Descriptions of t test cases follow. A description of each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 100), length of array a. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100), elements of a. The given array a can contain equal values (duplicates). Output For each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 ≤ p_i ≤ n), indexes of the chosen elements. If there are multiple solutions output any of them. Example Input 3 3 1 4 3 1 15 2 3 5 Output 1 2 -1 2 1 2 Note There are three test cases in the example. In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even. In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution. In the third test case, the subset consisting of all array's elements has even sum. Submitted Solution: ``` t=int(input()) for test in range(t): n=int(input()) a = list(map(int,input().split())) if (n==1) and (a[0]%2)!=0: print(-1) elif (n==1) and (a[0]%2)==0: print(1) print(a[0]) else: flag=False for i in range(n): if a[i]%2==0: print(1) print(i+1) flag=True ee=0 aa,b,x,y=0,1,0,0 count=0 if not(flag): for i in range(n): if a[i]%2==1: aa=a[i] ai = i+1 break flag2=False for i in range(n): if a[i]%2==1 and a[i]!=aa: b=a[i] bi = i+1 flag2=True break if flag2: print(2) print(ai,bi) else: print(-1) ```
instruction
0
95,408
12
190,816
No
output
1
95,408
12
190,817
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,485
12
190,970
Tags: data structures, dp, implementation, strings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip("\r\n") for _ in range(int(input())): n,m=map(int,input().split()) op=input() pre=[[0,0,0]] suf=[[0,0,0]] out=0 for i in op: if i=='-': out-=1 else: out+=1 pre.append([out,min(pre[-1][1],out),max(pre[-1][2],out)]) out=0 for i in reversed(op): if i=='+': out-=1 else: out+=1 suf.append([out,min(suf[-1][1],out),max(suf[-1][2],out)]) for i in range(m): l,r=map(int,input().split()) l-=1 minpre=pre[l][1] maxpre=pre[l][2] minsuf=-suf[n-r][0]+suf[n-r][1]+pre[l][0] #potential minimum candidate maxsuf=-suf[n-r][0]+suf[n-r][2]+pre[l][0] #potential maximum candidate print(max(maxpre,maxsuf)-min(minpre,minsuf)+1) ```
output
1
95,485
12
190,971
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,486
12
190,972
Tags: data structures, dp, implementation, strings Correct Solution: ``` import sys input=sys.stdin.readline for z in range(int(input())): n,m=map(int,input().split()) s=input() a=[0] for i in range(n): if s[i]=="+": a.append(a[-1]+1) else: a.append(a[-1]-1) nminl=[0] nmaxl=[0] nminr=[a[-1]]*(n+1) nmaxr=[a[-1]]*(n+1) for i in range(1,n+1): nminl.append(min(nminl[-1],a[i])) nmaxl.append(max(nmaxl[-1],a[i])) for i in range(n-1,-1,-1): nminr[i]=min(nminr[i+1],a[i]) nmaxr[i]=max(nmaxr[i+1],a[i]) for i in range(m): l,r=map(int,input().split()) num2=a[l-1]-a[r] if r!=n: ni=min(nminl[l-1],num2+nminr[min(n,r+1)]) na=max(nmaxl[l-1],num2+nmaxr[min(n,r+1)]) else: ni=nminl[l-1] na=nmaxl[l-1] print(na-ni+1) ```
output
1
95,486
12
190,973
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,487
12
190,974
Tags: data structures, dp, implementation, strings Correct Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") ans = [] t, = gil() for _ in range(t): n, m = gil() a = [] for v in g(): if v == "+": a.append(1) else: a.append(-1) l, r = a[:], a[:] for i in range(1, n): l[i] += l[i-1] lstack = [] mi, ma = 0, 0 for i in range(n): mi = min(mi, l[i]) ma = max(ma, l[i]) lstack.append((mi, ma)) r[-1] *= -1 for i in reversed(range(n-1)): r[i] *= -1 r[i] += r[i+1] rstack = [None for _ in range(n)] mi, ma = 0, 0 # if a[i] == 1: # mi, ma = -1, -1 # else: # mi, ma = 1, 1 # stack[-1] = (mi, ma) for i in reversed(range(n)): mi = min(mi, r[i]) ma = max(ma, r[i]) rstack[i] = (mi-r[i], ma-r[i]) # print(l) # print(lstack) # print() # print(r) # print(rstack) # exit() # print() for _ in range(m): li, ri = gil() li -= 1 x = 0 var = 0 mi, ma = 0, 0 if li: x += l[li-1] mi = min(mi, lstack[li-1][0]) ma = max(ma, lstack[li-1][1]) if ri < n: mi = min(mi, x+rstack[ri][0]) ma = max(ma, x+rstack[ri][1]) ans.append(str(ma-mi+1)) # print(mi, ma, ma-mi+1) # print(ma-mi+1) print("\n".join(ans)) ```
output
1
95,487
12
190,975
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,488
12
190,976
Tags: data structures, dp, implementation, strings Correct Solution: ``` from itertools import accumulate from sys import stdin, stdout readline = stdin.readline write = stdout.write def read_ints(): return map(int, readline().split()) def read_string(): return readline()[:-1] def write_int(x): write(str(x) + '\n') def find_prefix_ranges(op_seq): x = 0 min_x = max_x = x result = [(min_x, max_x)] for op in op_seq: x += op if x < min_x: min_x = x if x > max_x: max_x = x result.append((min_x, max_x)) return result def find_suffix_ranges(op_seq): min_x = max_x = 0 result = [(min_x, max_x)] for op in op_seq[::-1]: min_x += op max_x += op if op < min_x: min_x = op if op > max_x: max_x = op result.append((min_x, max_x)) return result[::-1] t_n, = read_ints() for i_t in range(t_n): n, q_n = read_ints() s = read_string() op_seq = [+1 if char == '+' else -1 for char in s] prefix_sums = [0] + list(accumulate(op_seq)) prefix_ranges = find_prefix_ranges(op_seq) suffix_ranges = find_suffix_ranges(op_seq) for i_q in range(q_n): l, r = read_ints() range_before = prefix_ranges[l-1] range_after = suffix_ranges[r] delta_for_after = prefix_sums[l-1] min_x, max_x = range_after min_x += delta_for_after max_x += delta_for_after range_after = (min_x, max_x) a, b = range_before, range_after if a > b: a, b = b, a assert a <= b if a[1] < b[0]: result = a[1] - a[0] + 1 + b[1] - b[0] + 1 else: final_range = (a[0], max(a[1], b[1])) result = final_range[1] - final_range[0] + 1 write_int(result) ```
output
1
95,488
12
190,977
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,489
12
190,978
Tags: data structures, dp, implementation, strings Correct Solution: ``` from sys import stdin t=int(stdin.readline()) for _ in range(t): n,m=map(int,stdin.readline().split()) s=stdin.readline()[:-1] maxt=0 mint=0 maxil=[0]*(n+1) minil=[0]*(n+1) val=[0]*(n+1) x=0 for i in range(n): if s[i]=='+': x+=1 else: x-=1 val[i+1]=x maxt=max(maxt,x) mint=min(mint,x) maxil[i+1]=maxt minil[i+1]=mint maxt=0 mint=0 maxir=[0]*(n+1) minir=[0]*(n+1) var=[0]*(n+1) x=0 for i in range(n-1,-1,-1): if s[i]=='+': x-=1 else: x+=1 var[i]=x maxt=max(maxt,x) mint=min(mint,x) maxir[i]=maxt minir[i]=mint for i in range(m): l,r=map(int,stdin.readline().split()) lrange=min(minil[l-1],val[l-1]-(var[r]-minir[r])) rrange=max(maxil[l-1],val[l-1]+(maxir[r]-var[r])) print(rrange-lrange+1) ```
output
1
95,489
12
190,979
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,490
12
190,980
Tags: data structures, dp, implementation, strings Correct Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): n, m = list(map(int, input().split())) s = input() sums = [0] * (n + 1) pref_mins = [0] * (n + 1) pref_maxs = [0] * (n + 1) for i in range(n): sums[i + 1] = sums[i] + (1 if s[i] == '+' else -1) pref_mins[i + 1] = min(pref_mins[i], sums[i + 1]) pref_maxs[i + 1] = max(pref_maxs[i], sums[i + 1]) suf_mins = [0] * (n + 1) suf_maxs = [0] * (n + 1) suf_maxs[n] = sums[n] suf_mins[n] = sums[n] for i in reversed(range(n)): suf_maxs[i] = max(sums[i], suf_maxs[i + 1]) suf_mins[i] = min(sums[i], suf_mins[i + 1]) for i in range(m): l, r = list(map(int, input().split())) sum = sums[r] - sums[l - 1] ans = max(pref_maxs[l - 1], suf_maxs[r] - sum) - min(pref_mins[l - 1], suf_mins[r] - sum) + 1 print(ans) ```
output
1
95,490
12
190,981
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,491
12
190,982
Tags: data structures, dp, implementation, strings Correct Solution: ``` 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") import typing def _ceil_pow2(n: int) -> int: x = 0 while (1 << x) < n: x += 1 return x def _bsf(n: int) -> int: x = 0 while n % 2 == 0: x += 1 n //= 2 return x class SegTree: def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None: self._op = op self._e = e if isinstance(v, int): v = [e] * v self._n = len(v) self._log = _ceil_pow2(self._n) self._size = 1 << self._log self._d = [e] * (2 * self._size) for i in range(self._n): self._d[self._size + i] = v[i] for i in range(self._size - 1, 0, -1): self._update(i) def set(self, p: int, x: typing.Any) -> None: assert 0 <= p < self._n p += self._size self._d[p] = x for i in range(1, self._log + 1): self._update(p >> i) def get(self, p: int) -> typing.Any: assert 0 <= p < self._n return self._d[p + self._size] def prod(self, left: int, right: int) -> typing.Any: assert 0 <= left <= right <= self._n sml = self._e smr = self._e left += self._size right += self._size while left < right: if left & 1: sml = self._op(sml, self._d[left]) left += 1 if right & 1: right -= 1 smr = self._op(self._d[right], smr) left >>= 1 right >>= 1 return self._op(sml, smr) def all_prod(self) -> typing.Any: return self._d[1] def max_right(self, left: int, f: typing.Callable[[typing.Any], bool]) -> int: assert 0 <= left <= self._n assert f(self._e) if left == self._n: return self._n left += self._size sm = self._e first = True while first or (left & -left) != left: first = False while left % 2 == 0: left >>= 1 if not f(self._op(sm, self._d[left])): while left < self._size: left *= 2 if f(self._op(sm, self._d[left])): sm = self._op(sm, self._d[left]) left += 1 return left - self._size sm = self._op(sm, self._d[left]) left += 1 return self._n def min_left(self, right: int, f: typing.Callable[[typing.Any], bool]) -> int: assert 0 <= right <= self._n assert f(self._e) if right == 0: return 0 right += self._size sm = self._e first = True while first or (right & -right) != right: first = False right -= 1 while right > 1 and right % 2: right >>= 1 if not f(self._op(self._d[right], sm)): while right < self._size: right = 2 * right + 1 if f(self._op(self._d[right], sm)): sm = self._op(self._d[right], sm) right -= 1 return right + 1 - self._size sm = self._op(self._d[right], sm) return 0 def _update(self, k: int) -> None: self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1]) sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") t=int(input()) for _ in range(t): n,m=map(int,input().split()) s=input() a=[0] curr=0 for i in range(n): if s[i]=='+': curr+=1 else: curr-=1 a.append(curr) segtreemax=SegTree(max,-10**9,a) segtreemin=SegTree(min,10**9,a) for i in range(m): l,r=map(int,input().split()) max1=segtreemax.prod(0,l) min1=segtreemin.prod(0,l) if r<n: max1=max(max1,a[l-1]+segtreemax.prod(r+1,n+1)-a[r]) min1=min(min1,a[l-1]+segtreemin.prod(r+1,n+1)-a[r]) print(max1-min1+1) ```
output
1
95,491
12
190,983
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,492
12
190,984
Tags: data structures, dp, implementation, strings Correct Solution: ``` from collections import defaultdict,deque import sys import bisect import math input=sys.stdin.readline mod=1000000007 def check(base, higher, lower): return higher - base, lower - base for t in range(int(input())): n, m = map(int, input().split()) st = input() store = [0 for i in range(n + 2)] add = 0 for i in range(n): if (st[i] == "-"): add -= 1 else: add += 1 store[i + 1] = add add = 0 f_mini_store = [0] * (n + 2) f_maxi_store = [0] * (n + 2) b_mini_store = [0] * (n + 2) b_maxi_store = [0] * (n + 2) maxi = -9999999999 mini = 99999999999 for i in range(1, n + 1): maxi = max(maxi, store[i]) mini = min(mini, store[i]) f_mini_store[i] = mini f_maxi_store[i] = maxi maxi, mini = -99999999999, 99999999999 for i in range(n, 0, -1): maxi = max(maxi, store[i]) mini = min(mini, store[i]) b_mini_store[i] = mini b_maxi_store[i] = maxi set1 = [0, 0] set2 = [0, 0] count = 0 for i in range(m): set1, set2 = [0, 0], [0, 0] count = 0 l, r = map(int, input().split()) add = 0 if (l > 1): set2[0], set2[1] = f_maxi_store[l - 1], f_mini_store[l - 1] add += 3 if (r < n): set1[0], set1[1] = check(store[r], b_maxi_store[r + 1], b_mini_store[r + 1]) add += 2 set1[0] = store[l - 1] + set1[0] set1[1] = store[l - 1] + set1[1] upper = max(set1[0], set2[0]) down = min(set1[1], set2[1]) if (add == 0): print(1) elif (add == 3): if (set2[0] >= 0 and set2[1] <= 0): print(set2[0] - set2[1] + 1) else: print(set2[0] - set2[1] + 2) elif (add == 2): if (set1[0] >= 0 and set1[1] <= 0): print(set1[0] - set1[1] + 1) else: print(set1[0] - set1[1] + 2) else: if (upper >= 0 and down <= 0): print(upper - down + 1) else: print(upper - down + 2) ```
output
1
95,492
12
190,985
Provide tags and a correct Python 2 solution for this coding contest problem. You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: * increase x by 1; * decrease x by 1. You are given m queries of the following format: * query l r — how many distinct values is x assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the description of t testcases follows. The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of n characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the description of the query. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5. The sum of m over all testcases doesn't exceed 2 ⋅ 10^5. Output For each testcase print m integers — for each query l, r print the number of distinct values variable x is assigned to if all the instructions between the l-th one and the r-th one inclusive are ignored and the rest are executed without changing the order. Example Input 2 8 4 -+--+--+ 1 8 2 8 2 5 1 1 4 10 +-++ 1 1 1 2 2 2 1 3 2 3 3 3 1 4 2 4 3 4 4 4 Output 1 2 4 4 3 3 4 2 3 2 1 2 2 2 Note The instructions that remain for each query of the first testcase are: 1. empty program — x was only equal to 0; 2. "-" — x had values 0 and -1; 3. "---+" — x had values 0, -1, -2, -3, -2 — there are 4 distinct values among them; 4. "+--+--+" — the distinct values are 1, 0, -1, -2.
instruction
0
95,493
12
190,986
Tags: data structures, dp, implementation, strings Correct Solution: ``` """ Python 3 compatibility tools. """ from __future__ import division, print_function import itertools import sys if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip import os from atexit import register from io import BytesIO sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') cases = int(input()) for _ in range(cases): n, q = map(int, input().split()) instructions = input() minA = [0] * (n + 1) maxA = [0] * (n + 1) prefix = [0] current = 0 for i, s in enumerate(instructions): if s == "+": current += 1 else: current -= 1 index = i + 1 minA[index] = min(minA[index - 1], current) maxA[index] = max(current, maxA[index - 1]) prefix.append(current) current = 0 minD = [prefix[-1]] * (n + 1) maxD = [prefix[-1]] * (n + 1) for index in range(n - 1, 0, -1): minD[index] = min(minD[index + 1], prefix[index]) maxD[index] = max(prefix[index], maxD[index + 1]) for _ in range(q): start, end = map(int, input().split()) rangeStart = [minA[start - 1], maxA[start - 1]] ignored = prefix[end] - prefix[start - 1] rangeEnd = [minD[end] - ignored, maxD[end] - ignored] maxComb = max(rangeEnd[1], rangeStart[1]) minComb = min(rangeEnd[0], rangeStart[0]) print(maxComb - minComb + 1) ```
output
1
95,493
12
190,987
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,520
12
191,040
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import sys input = sys.stdin.readline mod = 10 ** 9 + 7 for t in range(int(input())): n, l, r = map(int, input().split()) F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = (i + 1) * iF[i + 1] % mod def comb(n, m): if m < 0 or m > n: return 0 return F[n] * iF[m] * iF[n - m] % mod a, b = l - 1, r - n c = min(-a, b) ans = comb(n, n // 2) * (1 + n % 2) * c d = c + 1 while True: x = min(n, n - (l - 1 + d)) y = min(n, r - d) if x < n // 2 or y < n // 2: break ans += comb(x + y - n, n // 2 - (n - y)) if n % 2: # ans += comb(x + y - n, n // 2 - (n - x)) ans += comb(x + y - n, (n + 1) // 2 - (n - y)) ans %= mod d += 1 print(ans) ```
output
1
95,520
12
191,041
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,521
12
191,042
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline M = 10**9+7 MAX = 10**6+1 factor = [1]*MAX for i in range(1,MAX): factor[i] = (factor[i-1]*i)%M def fastfrac(a,b,M): numb = pow(b,M-2,M) return ((a%M)*(numb%M))%M def comb(m,n): if n<0 or m<0: return 0 num1 = factor[m] num2 = factor[n] num3 = factor[m-n] num = fastfrac(num1,num2,M) num = fastfrac(num,num3,M) return num def getnum(n,mustl,mustr): if mustl>mustr: mustl,mustr = mustr,mustl if mustr>n//2+1: return 0 output = 0 freedom = n - mustl - mustr if n%2==0: pick = n//2 - mustr output += comb(freedom,pick) output = output %M else: pick1 = n//2 - mustr pick2 = n//2 - mustr + 1 output += comb(freedom,pick1) output = output %M output += comb(freedom,pick2) output = output %M return output T = int(input()) t = 1 while t<=T: n,l,r = map(int,input().split()) lleft = l - 1 rleft = r - 1 lright = l - n rright = r - n ans = min(-lleft,rright) * getnum(n,0,0) ans = ans%M diff = abs(-lleft-rright) mustl = 0 mustr = 0 while diff>0: mustr += 1 ans += getnum(n,mustl,mustr) if mustr>n: break ans = ans%M diff -= 1 while mustr<n: mustl += 1 mustr += 1 ans += getnum(n,mustl,mustr) ans = ans%M print(ans) t += 1 ```
output
1
95,521
12
191,043
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,522
12
191,044
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 from bisect import bisect_left 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") import math N = 200001 # array to store inverse of 1 to N factorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N! naturalNumInverse = [None] * (N + 1) # array to store factorial of # first N numbers fact = [None] * (N + 1) # Function to precompute inverse of numbers def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse # of factorials def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to N def factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) time def Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p return ans p=10**9+7 InverseofNumber(p) InverseofFactorial(p) factorial(p) t=int(input()) for _ in range(t): n,l,r=map(int,input().split()) mi=min(1-l,r-n) ma=max(1-l,r-n) ans=0 if (n%2==0): cmi=n//2 cma=n//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cmi]))%p val=mi+1 while(cmi>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 else: cmi=(n-1)//2 cma=(n+1)//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p val=mi+1 while(cmi>0 and cma>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 cmi=(n+1)//2 cma=(n-1)//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p val=mi+1 while(cmi>0 and cma>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 print(ans%p) #a=list(map(int,input().split())) ```
output
1
95,522
12
191,045
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,523
12
191,046
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` def main(): from sys import stdin, setrecursionlimit #from io import BytesIO #from os import read, fstat #from math import gcd #from random import randint, choice, shuffle #from itertools import combinations, product #from functools import lru_cache #from re import search, finditer input = stdin.buffer.readline #input = BytesIO(read(0, fstat(0).st_size)).readline #setrecursionlimit(100000000) def c(n, k): if n < k or k < 0: return 0 return f[n] * rev[k] * rev[n - k] % mod mod = 10**9 + 7 f = [1] for i in range(1, 200001): f.append(f[-1] * i % mod) rev = [pow(f[-1], mod - 2, mod)] for i in range(200000, 0, -1): rev.append(rev[-1] * i % mod) rev = rev[::-1] for _ in range(int(input())): n, l, r = map(int, input().split()) h = n >> 1 s = min(1 - l, r - n) ans = s * (c(n, h) + [0, c(n, h + 1)][n & 1]) x = s + 1 while 1: ll = max(1, l + x) rr = min(n, r - x) if rr - ll + 1 < 0: break ans += c(rr - ll + 1, h - (ll - 1)) + [0, c(rr - ll + 1, h + 1 - (ll - 1))][n & 1] x += 1 print(ans % mod) main() ```
output
1
95,523
12
191,047
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,524
12
191,048
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import sys input = sys.stdin.readline mod = 10 ** 9 + 7 for t in range(int(input())): n, l, r = map(int, input().split()) F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = (i + 1) * iF[i + 1] % mod def comb(n, m): if m < 0 or m > n: return 0 return F[n] * iF[m] * iF[n - m] % mod a, b = l - 1, r - n c = min(-a, b) ans = comb(n, n // 2) * (1 + n % 2) * c d = c + 1 while True: x = min(n, n - (l - 1 + d)) y = min(n, r - d) if x < 0 or y < 0: break ans += comb(x + y - n, n // 2 - (n - y)) if n % 2: # ans += comb(x + y - n, n // 2 - (n - x)) ans += comb(x + y - n, (n + 1) // 2 - (n - y)) ans %= mod d += 1 print(ans) ```
output
1
95,524
12
191,049
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,525
12
191,050
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) """ l <= -c+1 <= r l <= -c+k <= r l <= c+k+1 <= r l <= c+2*k <= r l <= -c+1 < c+n <= r l <= 0 < 1+n <=r l <= c+1 <= r l <= c+k <= r l <= -c+k+1 <= r l <= -c+2*k <= r l-1 <= c <= r-k 2*k - r <= c <= k+1-l l <= 0 < 1+n <=r l <= -c+x <= r l <= -c+y <= r l <= c+z <= r l <= c+w <= r max(y-r,l-z) <= c <= min(r-w,x-l) for c in range(1,(r-l+1)//2+1): #1 <= i <= c+l-1 +c 確定 #r+1-c <= i <= n -c 確定 # c+l <= i <= r-c どっちでも if n%2==0: res += cmb(r-l+1-2*c,k-(c+l-1)) else: res += cmb(r-l+1-2*c,k-(c+l-1)) + cmb(r-l+1-2*c,k+1-(c+l-1)) for c in range(1,-l): """ def cmb(n, r, mod): if ( r<0 or r>n ): return 0 r = min(r, n-r) return (g1[n] * g2[r] % mod) * g2[n-r] % mod mod = 10**9 + 7 N = 2*10**5 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 for _ in range(int(input())): n,l,r = mi() k = n//2 res = 0 #l<=-c-1 and c+n <= r <-> 1 <= c <= min(r-n,-l-1) if 1 <= min(r-n,-l-1): if n&1: tmp = cmb(n,k,mod) + cmb(n,k+1,mod) tmp %= mod else: tmp = cmb(n,k,mod) res += tmp * (min(r-n,-l-1)) % mod res %= mod s = min(r-n,-l-1) + 1 else: s = 1 for c in range(s,s+n+2): # -c+i <= l-1 <-> 1 <= i <= l-1+c plus = max(0,l-1+c) # r+1 <= c+i <-> max(1,r+1-c) <= i <= n minus = max(0,n-max(1,r+1-c)+1) if plus + minus > n: break if n&1: res += cmb(n-plus-minus,k-plus,mod) + cmb(n-plus-minus,k+1-plus,mod) res %= mod else: res += cmb(n-plus-minus,k-plus,mod) res %= mod print(res) ```
output
1
95,525
12
191,051
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,526
12
191,052
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import sys input = sys.stdin.readline mod = 10 ** 9 + 7 for t in range(int(input())): n, l, r = map(int, input().split()) F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = (i + 1) * iF[i + 1] % mod def comb(n, m): if m < 0 or m > n: return 0 return F[n] * iF[m] * iF[n - m] % mod a, b = l - 1, r - n c = min(-a, b) ans = comb(n, n // 2) * (1 + n % 2) * c d = c + 1 while True: x = min(n, n - (l - 1 + d)) y = min(n, r - d) if x < 0 or y < 0: break ans += comb(x + y - n, n // 2 - (n - y)) if n % 2: ans += comb(x + y - n, n // 2 - (n - x)) ans %= mod d += 1 print(ans) ```
output
1
95,526
12
191,053
Provide tags and a correct Python 3 solution for this coding contest problem. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1].
instruction
0
95,527
12
191,054
Tags: binary search, combinatorics, constructive algorithms, implementation, math, sortings, two pointers Correct Solution: ``` import sys from sys import stdin 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): return fac[n] * inv[n-r] * inv[r] % mod mod = 10**9+7 fac,inv = modfac(300000,mod) tt = int(stdin.readline()) ANS = [] for loop in range(tt): n,l,r = map(int,stdin.readline().split()) ans = 0 #dont dmax = min(1-l,r-n) if dmax >= 0: if n % 2 == 0: ans += dmax * modnCr(n,n//2) % mod else: ans += 2 * dmax * modnCr(n,n//2) % mod #print (ans % mod,file=sys.stderr) #rest nd = dmax + 1 while True: lrist = max(0,l+nd-1) rrist = max(0,n-(r-nd)) #print (nd,lrist,rrist) if lrist + rrist > n or min(lrist,rrist) > (n+1)//2: break if n%2 == 1: #l is min uprem = n//2 - lrist downrem = (n+1)//2 - rrist if min(uprem,downrem) >= 0: ans += modnCr(uprem+downrem,uprem) #other uprem = (n+1)//2 - lrist downrem = n//2 - rrist if min(uprem,downrem) >= 0: ans += modnCr(uprem+downrem,uprem) else: uprem = n//2 - lrist downrem = n//2 - rrist if min(uprem,downrem) >= 0: ans += modnCr(uprem+downrem,uprem) nd += 1 ANS.append(str(ans % mod)) print ("\n".join(ANS)) ```
output
1
95,527
12
191,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() P = 10 ** 9 + 7 nn = 505050 fa = [1] * (nn+1) fainv = [1] * (nn+1) for i in range(nn): fa[i+1] = fa[i] * (i+1) % P fainv[-1] = pow(fa[-1], P-2, P) for i in range(nn)[::-1]: fainv[i] = fainv[i+1] * (i+1) % P C = lambda a, b: fa[a] * fainv[b] % P * fainv[a-b] % P if 0 <= b <= a else 0 def calc(n, l, r): a, b = 1 - l, r - n aa, bb = r - 1, n - l if a > b: a, b = b, a aa, bb = bb, aa re = 0 if n % 2 == 0: re += C(n, n // 2) * a else: re += (C(n, n // 2) + C(n, n // 2 + 1)) * a if 0: for k in range(a + 1, min(aa, bb, b) + 1): if n % 2 == 0: re += C(n - (k - a), n // 2 - (k - a)) else: re += C(n - (k - a), n // 2 - (k - a)) + C(n - (k - a), n // 2 + 1 - (k - a)) elif 0: for k in range(1, min(aa, bb, b) - a + 1): if n % 2 == 0: re += C(n - k, n // 2 - k) else: re += C(n - k, n // 2 - k) + C(n - k, n // 2 + 1 - k) else: kk = min(aa, bb, b) - a m = n - kk mm = n // 2 - kk if n % 2 == 0: re += C(m + kk, mm + kk - 1) re -= C(m, mm - 1) else: re += C(m + kk, mm + kk - 1) re -= C(m, mm - 1) re += C(m + kk, mm + 1 + kk - 1) re -= C(m, mm) if 0: for k in range(b + 1, min(aa, bb) + 1): if n % 2 == 0: re += C(n - (k - a) - (k - b), n // 2 - (k - a)) else: re += C(n - (k - a) - (k - b), n // 2 - (k - a)) + C(n - (k - a) - (k - b), n // 2 + 1 - (k - a)) else: kk = min(aa, bb) - b m = n - (kk - a + b) if n % 2 == 0: for k in range(1, kk + 1): re += C(n - (k - a + b) - k, n // 2 - (k - a + b)) else: for k in range(1, kk + 1): re += C(n - (k - a + b) - k, n // 2 - (k - a + b)) + C(n - (k - a + b) - k, n // 2 + 1 - (k - a + b)) return re % P if 1: T = int(input()) for _ in range(T): n, l, r = map(int, input().split()) print(calc(n, l, r)) else: from random import randrange T = 100 for _ in range(T): n = randrange(4, 20) a = randrange(20) b = randrange(20) l, r = l - a, r + b c1 = calc1(n, l, r) c2 = calc(n, l, r) if c1 != c2: print("Error !") print("n, l, r =", n, l, r) print("c1, c2 =", c1, c2) print("END") ```
instruction
0
95,528
12
191,056
Yes
output
1
95,528
12
191,057
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import sys input = sys.stdin.readline mod = 10 ** 9 + 7 for t in range(int(input())): n, l, r = map(int, input().split()) F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = (i + 1) * iF[i + 1] % mod def comb(n, m): if m < 0 or m > n: return 0 return F[n] * iF[m] * iF[n - m] % mod a, b = l - 1, r - n c = min(-a, b) ans = comb(n, n // 2) * (1 + n % 2) * c d = c + 1 m = n // 2 while True: x = min(n, n - (l - 1 + d)) y = min(n, r - d) if x < m or y < m: break ans += comb(x + y - n, m - (n - y)) if n % 2: # ans += comb(x + y - n, m - (n - x)) ans += comb(x + y - n, m + 1 - (n - y)) ans %= mod d += 1 print(ans) ```
instruction
0
95,529
12
191,058
Yes
output
1
95,529
12
191,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import sys # sys.setrecursionlimit(200005) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def SI(): return sys.stdin.readline().rstrip() inf = 10**16 md = 10**9+7 # md = 998244353 def nCr(com_n, com_r): if com_r < 0: return 0 if com_n < com_r: return 0 return fac[com_n]*ifac[com_r]%md*ifac[com_n-com_r]%md # 準備 n_max = 200005 fac = [1] for i in range(1, n_max+1): fac.append(fac[-1]*i%md) ifac = [1]*(n_max+1) ifac[n_max] = pow(fac[n_max], md-2, md) for i in range(n_max-1, 1, -1): ifac[i] = ifac[i+1]*(i+1)%md def solve(): n, l, r = LI() ans = 0 mn = max(1, 1-r, l-n) mx = min(1-l, r-n) if mn <= mx: if n & 1: ans += nCr(n, n//2)*2*(mx-mn+1-(mn <= 0 <= mx))%md else: ans += nCr(n, n//2)*(mx-mn+1-(mn <= 0 <= mx))%md s = mn-1 # print(mn, mx, ans) while s > 0: # (-sにできる)[L(どちらにもできる)R](sにできる) L = max(1, l+s) R = min(n, r-s) # print(s, L, R) ans += nCr(R-L+1, n//2-L+1) if n & 1: ans += nCr(R-L+1, n//2-L+2) s -= 1 s = mx+1 while 1: L = max(1, l+s) R = min(n, r-s) # print(s, L, R) if L > R+1: break ans += nCr(R-L+1, n//2-L+1) if n & 1: ans += nCr(R-L+1, n//2-L+2) s += 1 ans %= md print(ans) for testcase in range(II()): solve() ```
instruction
0
95,530
12
191,060
Yes
output
1
95,530
12
191,061
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import sys read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip() import bisect,string,math,time,functools,random,fractions from bisect import* from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby rep=range;R=range def I():return int(input()) def LI():return [int(i) for i in input().split()] def LI_():return [int(i)-1 for i in input().split()] def AI():return map(int,open(0).read().split()) def S_():return input() def IS():return input().split() def LS():return [i for i in input().split()] def NI(n):return [int(input()) for i in range(n)] def NI_(n):return [int(input())-1 for i in range(n)] def NLI(n):return [[int(i) for i in input().split()] for i in range(n)] def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)] def StoLI():return [ord(i)-97 for i in input()] def ItoS(n):return chr(n+97) def LtoS(ls):return ''.join([chr(i+97) for i in ls]) def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)] def RI(a=1,b=10):return random.randint(a,b) def INP(): N=10 n=random.randint(1,N) a=RLI(n,1,n) return n,a def Rtest(T): case,err=0,0 for i in range(T): inp=INP() a1=naive(*inp) a2=solve(*inp) if a1!=a2: print(inp) print('naive',a1) print('solve',a2) err+=1 case+=1 print('Tested',case,'case with',err,'errors') def GI(V,E,ls=None,Directed=False,index=1): org_inp=[];g=[[] for i in range(V)] FromStdin=True if ls==None else False for i in range(E): if FromStdin: inp=LI() org_inp.append(inp) else: inp=ls[i] if len(inp)==2:a,b=inp;c=1 else:a,b,c=inp if index==1:a-=1;b-=1 aa=(a,c);bb=(b,c);g[a].append(bb) if not Directed:g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage mp=[boundary]*(w+2);found={} for i in R(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[boundary]+[mp_def[j] for j in s]+[boundary] mp+=[boundary]*(w+2) return h+2,w+2,mp,found def TI(n):return GI(n,n-1) def accum(ls): rt=[0] for i in ls:rt+=[rt[-1]+i] return rt def bit_combination(n,base=2): rt=[] for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s] return rt def gcd(x,y): if y==0:return x if x%y==0:return y while x%y!=0:x,y=y,x%y return y def YN(x):print(['NO','YES'][x]) def Yn(x):print('YNeos'[not x::2]) def show(*inp,end='\n'): if show_flg:print(*inp,end=end) def showf(inp,length=3,end='\n'): if show_flg:print([' '*(length-len(str(i)))+str(i)for i in inp],end=end) mo=10**9+7 #mo=998244353 inf=float('inf') FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb)) alp=[chr(ord('a')+i)for i in range(26)] #sys.setrecursionlimit(10**7) def gcj(c,x): print("Case #{0}:".format(c+1),x) show_flg=False show_flg=True class Comb: def __init__(self,n,mo=10**9+7): self.fac=[0]*(n+1) self.inv=[1]*(n+1) self.fac[0]=1 self.fact(n) for i in range(1,n+1): self.fac[i]=i*self.fac[i-1]%mo self.inv[n]*=i self.inv[n]%=mo self.inv[n]=pow(self.inv[n],mo-2,mo) for i in range(1,n): self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo return def fact(self,n): return self.fac[n] def invf(self,n): return self.inv[n] def comb(self,x,y): if y<0 or y>x: return 0 return self.fac[x]*self.inv[x-y]*self.inv[y]%mo def cat(self,x): if x<0: return 0 return self.fac[2*x]*self.inv[x]*self.inv[x+1]%mo ans=0 for _ in range(I()): n,l,r=LI() cm=Comb(n+10) #show(n,l,r) if abs(l-n)<=abs(r-1):l,r=n+1-r,-l+n+1 #show(n,l,r) m=n//2 a=0 for x in range(r-n,r-1+1): if x==0: continue cr=r-x cl=min(n,max(0,n-(l+x-1))) if cl>=n and cr>=n and False: a+=cm.comb(n,m) #show((n,m),x,a) if n%2==1:a+=cm.comb(n,m+1) else: s=n-cl t=n-cr a+=cm.comb(n-s-t,m-s) #show((n-s-t,m-s),x,a,(cl,cr),(s,t)) if n%2==1:a+=cm.comb(n-s-t,m+1-s) if r-n-1>0: a+=cm.comb(n,m)*(r-n-1) if n%2==1:a+=cm.comb(n,m+1)*(r-n-1) #show(x,(cr,cl)) print(a%mo) ```
instruction
0
95,531
12
191,062
Yes
output
1
95,531
12
191,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 from bisect import bisect_left 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") import math N = 200001 # array to store inverse of 1 to N factorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N! naturalNumInverse = [None] * (N + 1) # array to store factorial of # first N numbers fact = [None] * (N + 1) # Function to precompute inverse of numbers def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse # of factorials def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to N def factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) time def Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p return ans p=10**9+7 InverseofNumber(p) InverseofFactorial(p) factorial(p) t=int(input()) for _ in range(t): n,l,r=map(int,input().split()) mi=min(1-l,r-n) ma=max(1-l,r-n) ans=0 if (n%2==0): cmi=n//2 cma=n//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cmi]))%p val=mi+1 while(cmi>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 else: cmi=(n-1)//2 cma=(n+1)//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p val=mi+1 while(cmi>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 cmi=(n+1)//2 cma=(n-1)//2 ans+=(mi*(fact[n]*factorialNumInverse[cmi]*factorialNumInverse[cma]))%p val=mi+1 while(cmi>0): if val>mi: cmi+=-1 if val>ma: cma+=-1 ans+=(fact[cmi+cma]*factorialNumInverse[cmi]*factorialNumInverse[cma])%p val+=1 print(ans%p) #a=list(map(int,input().split())) ```
instruction
0
95,532
12
191,064
No
output
1
95,532
12
191,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline M = 10**9+7 MAX = 10**6+1 factor = [1]*MAX for i in range(1,MAX): factor[i] = (factor[i-1]*i)%M def fastfrac(a,b,M): numb = pow(b,M-2,M) return ((a%M)*(numb%M))%M def comb(m,n): if n<0: return 0 num1 = factor[m] num2 = factor[n] num3 = factor[m-n] num = fastfrac(num1,num2,M) num = fastfrac(num,num3,M) return num def getnum(n,mustl,mustr): if mustl>mustr: mustl,mustr = mustr,mustl output = 0 freedom = n - mustl - mustr if n%2==0: pick = n//2 - mustr output += comb(freedom,pick) else: pick1 = n//2 - mustr pick2 = n//2 - mustr + 1 output += comb(freedom,pick1) output += comb(freedom,pick2) return output T = int(input()) t = 1 while t<=T: n,l,r = map(int,input().split()) lleft = l - 1 rleft = r - 1 lright = l - n rright = r - n ans = min(-lleft,rright) * getnum(n,0,0) ans = ans%M diff = abs(-lleft-rright) mustl = 0 mustr = 0 while diff>0: mustr += 1 ans += getnum(n,mustl,mustr) ans = ans%M diff -= 1 while mustr<n//2+2: mustl += 1 mustr += 1 ans += getnum(n,mustl,mustr) ans = ans%M print(ans) t += 1 ```
instruction
0
95,533
12
191,066
No
output
1
95,533
12
191,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` import sys input = sys.stdin.readline mod=10**9+7 FACT=[1] for i in range(1,4*10**5+1): FACT.append(FACT[-1]*i%mod) FACT_INV=[pow(FACT[-1],mod-2,mod)] for i in range(4*10**5,0,-1): FACT_INV.append(FACT_INV[-1]*i%mod) FACT_INV.reverse() def Combi(a,b): if 0<=b<=a: return FACT[a]*FACT_INV[b]%mod*FACT_INV[a-b]%mod else: return 0 """ ANS=Combi(42,21)*13 for i in range(1,42): ANS+=Combi(42-i,21-i) ANS%=mod print(ANS) """ t=int(input()) for tests in range(t): n,l,r=map(int,input().split()) x,y,z,w=1-r,1-l,n-r,n-l #print(x,y,z,w) """ if x>=0 or w<=0: ANS=1 for i in range(1,n+1): if l<=1<=r: ANS=ANS*(r-l)%mod else: ANS=ANS*(r-l+1)%mod print(ANS) continue """ k=min(-x,-z,y,w) if n%2==0: ANS=k*Combi(n,n//2) for i in range(1,n): ANS+=Combi(n-i,n//2-i) ANS%=mod print(ANS) else: ANS=k*Combi(n,n//2)*2 for i in range(1,n): ANS+=Combi(n-i,n//2+1-i)+Combi(n-i,n//2-i) ANS%=mod print(ANS) ```
instruction
0
95,534
12
191,068
No
output
1
95,534
12
191,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i. Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j. Let's say that an array a_1, a_2, ..., a_n is excellent if: * a is good; * l ≤ a_i ≤ r for each i; * F(a) is the maximum possible among all good arrays of size n. Given n, l and r, calculate the number of excellent arrays modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers n, l, and r (2 ≤ n ≤ 2 ⋅ 10^5; -10^9 ≤ l ≤ 1; n ≤ r ≤ 10^9). It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5. Output For each test case, print the number of excellent arrays modulo 10^9 + 7. Example Input 4 3 0 3 4 -3 5 42 -33 55 69 -42 146 Output 4 10 143922563 698570404 Note In the first test case, it can be proven that the maximum F(a) among all good arrays a is equal to 2. The excellent arrays are: 1. [2, 1, 2]; 2. [0, 3, 2]; 3. [2, 3, 2]; 4. [3, 0, 1]. Submitted Solution: ``` # # author: vongkh # created: Mon Dec 28 2020 # from sys import stdin, stdout # only need for big input from math import factorial, sqrt mxN = int(2e5+100) fact = [0] * mxN ifact = [0] * mxN MOD = int(1e9 + 7) def add(x, y): ret = x + y if ret >= MOD: ret = ret % MOD return ret def mul(x, y): ret = x * y if ret >= MOD: ret %= MOD return ret def pow_mod(a, p): ret = 1 if p > 0: ret = pow_mod(a, p//2) ret = mul(ret, ret) if p % 2: ret = mul(ret, a) return ret def inv(a): return pow_mod(a, MOD - 2) def init_fact(): fact[0] = 1 ifact[0] = 1 for i in range(1, mxN): fact[i] = mul(fact[i-1], i) ifact[i] = inv(fact[i]) def nCr(n , r): if n < r: return 0 ret = mul(fact[n], ifact[r]) ret = mul(ret, ifact[n-r]) return ret def choice(n, wants): ret = 0 for w in wants: ret = add(ret, nCr(n, w)) return ret def solve(): n, l, r = list(map(int, input().split())) wants = [n // 2] right = r - 1 left = n - l shortest = min(right, left) # print("shortest", shortest) if n % 2 : wants.append((n+1)//2) ans = 0 for i in range(1, n+1): if shortest > 0: ans = add(ans, choice(i, wants)) shortest -= 1 if shortest > 0: additional = mul(shortest , choice(n, wants)) ans = add(ans, additional) print(ans) def main(): init_fact() test = int(input()) for i in range(1, test + 1): # print(f"Case #{i}: ", end="") solve() if __name__ == "__main__": main() ```
instruction
0
95,535
12
191,070
No
output
1
95,535
12
191,071
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element. Help the Little Elephant and count the number of the described pairs. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output In a single line print a single number — the answer to the problem. Examples Input 3 1 1 3 2 Output 3 Input 5 2 1 3 2 1 7 Output 6
instruction
0
95,552
12
191,104
Tags: data structures, two pointers Correct Solution: ``` # 220E import sys from collections import defaultdict class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _get_sum(self, r): ''' sum on interval [0, r) ''' result = 0 while r > 0: result += self.tree[r-1] r = self._F(r-1) return result def get_sum(self, l, r): ''' sum on interval [l, r) ''' return self._get_sum(r) - self._get_sum(l) def _H(self, i): return i | (i + 1) def add(self, i, value=1): while i < self.n: self.tree[i] += value i = self._H(i) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n, k = map(int, input().split()) a = list(map(int, input().split())) pos = defaultdict(list) for i, val in enumerate(a): pos[val].append(i) i = 0 prev = -1 for val in sorted(a): if prev == val: continue for j in pos[val]: a[j] = i i += 1 prev = val left = BIT(n) right = BIT(n) total_inv = 0 left.add(a[0]) for t in range(1, n): i = a[t] total_inv += right.get_sum(i+1, n) right.add(i) if i < a[0]: total_inv += 1 if total_inv <= k: print((n*(n-1))>>1) sys.exit() l = 0 r = 1 while r < n and total_inv > k: total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 pairs = 0 while r < n: while True: add = left.get_sum(a[l+1]+1, n) + right.get_sum(0, a[l+1]) if total_inv + add > k: pairs += l + 1 break else: l += 1 total_inv += add left.add(a[l]) total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 print(pairs) ```
output
1
95,552
12
191,105
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element. Help the Little Elephant and count the number of the described pairs. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output In a single line print a single number — the answer to the problem. Examples Input 3 1 1 3 2 Output 3 Input 5 2 1 3 2 1 7 Output 6
instruction
0
95,553
12
191,106
Tags: data structures, two pointers Correct Solution: ``` ''' Created on 19/07/2018 @author: ernesto ''' # XXX: http://codeforces.com/problemset/problem/220/E #  XXX: https://practice.geeksforgeeks.org/problems/magic-triplets/0 # XXX: https://gist.github.com/robert-king/5660418 class RangeBit: def __init__(self, n): sz = 1 while n >= sz: sz *= 2 self.size = sz self.dataAdd = [0] * sz self.dataMul = [0] * sz def sum(self, i): r = 0 if i > 0: add = 0 mul = 0 start = i while i > 0: add += self.dataAdd[i] mul += self.dataMul[i] i -= i & -i r = mul * start + add return r def add(self, left, right, by): assert 0 < left <= right self._add(left, by, -by * (left - 1)) self._add(right, -by, by * right) def _add(self, i, mul, add): assert i > 0 while i < self.size: self.dataAdd[i] += add self.dataMul[i] += mul i += i & -i def sum_range(self, i, j): # print("j {} s {}".format(j, self.sum(j))) # print("i {} s {}".format(i, self.sum(i))) return self.sum(j) - self.sum(i - 1) def sum_back(self, i): return self.sum_range(i, self.size - 1) def add_point(self, i, by): self.add(i, i, by) class numero(): def __init__(self, valor, posicion_inicial): self.valor = valor self.posicion_inicial = posicion_inicial self.posicion_final = -1; def __lt__(self, other): if self.valor == other.valor: r = self.posicion_inicial < other.posicion_inicial else: r = self.valor < other.valor return r def __repr__(self): return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final) def swap(a, i, j): a[i], a[j] = a[j], a[i] def crea_arreglo_enriquecido(nums): numse = list(sorted(map(lambda t:numero(t[1], t[0]), enumerate(nums)))) r = [0] * len(nums) # print("numse {}".format(numse)) for i, n in enumerate(numse): r[n.posicion_inicial] = i + 1 return r def fuerza_bruta(a): a_len = len(a) r = 0 for i in range(a_len): for j in range(i): if a[i] < a[j]: r += 1 return r def quita(bi, bd, a, i): return modifica(bi, bd, a, i, False) def anade(bi, bd, a, i): return modifica(bi, bd, a, i, True) def modifica(bi, bd, a, i, anade): if anade: bc = bi fac = 1 else: bc = bd fac = -1 inv = bi.sum_back(a[i] + 1) + bd.sum(a[i] - 1) # print("num {} parte de i {} de d {} fact {}".format(a[i], bi.sum(a[i] + 1), bd.sum(a[i] - 1), fac)) bc.add_point(a[i], fac) return inv def core(nums, nmi): numse = crea_arreglo_enriquecido(nums) # print("numse {}".format(numse)) a = numse # print("a {}".format(list(map(lambda x:x - 1, a)))) i = 0 j = 0 ni = 0 r = 0 a_len = len(a) bitch_izq = RangeBit(a_len + 2) bitch_der = RangeBit(a_len + 2) nif = 0 for i, x in enumerate(a): nif += bitch_der.sum_range(x + 1, a_len) bitch_der.add(x, x, 1) # print("en x {} ({}) nif {}".format(x, numse[i].valor , nif)) j = 0 ni = nif # print("ni ini {}".format(ni)) ni += anade(bitch_izq, bitch_der, a, 0) for i in range(1, a_len): while j < a_len and (j < i or ni > nmi): ni -= quita(bitch_izq, bitch_der, a, j) # print("en j {} se kito {} {}".format(j, nums[j], ni)) j += 1 r += a_len - j # print("en i {} j {} anadido {} inv {}".format(i, j, a_len - j, ni)) ni += anade(bitch_izq, bitch_der, a, i) # print("en i {} se puso {}".format(i, ni)) # print("r f aora {}".format(r)) return r _, k = [int(x) for x in input().strip().split(" ")] nums = [int(x) for x in input().strip().split(" ")] # nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7] # nums = [1, 3, 2, 1, 7] # nums = [1, 3, 2] # k = 0 print(core(nums, k)) ```
output
1
95,553
12
191,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element. Help the Little Elephant and count the number of the described pairs. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output In a single line print a single number — the answer to the problem. Examples Input 3 1 1 3 2 Output 3 Input 5 2 1 3 2 1 7 Output 6 Submitted Solution: ``` # 220E import sys class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _get_sum(self, r): ''' sum on interval [0, r) ''' result = 0 while r > 0: result += self.tree[r-1] r = self._F(r-1) return result def get_sum(self, l, r): ''' sum on interval [l, r) ''' return self._get_sum(r) - self._get_sum(l) def _H(self, i): return i | (i + 1) def add(self, i, value=1): while i < self.n: self.tree[i] += value i = self._H(i) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n, k = map(int, input().split()) a = list(map(int, input().split())) pos = {val:i for i, val in enumerate(a)} for i, val in enumerate(sorted(a)): a[pos[val]] = i left = BIT(n) right = BIT(n) total_inv = 0 left.add(a[0]) for t in range(1, n): i = a[t] total_inv += right.get_sum(i, n) right.add(i) if i < a[0]: total_inv += 1 # print(total_inv, k) if total_inv <= k: print((n*(n-1))>>1) sys.exit() l = 0 r = 1 while r < n and total_inv > k: total_inv -= left.get_sum(a[r], n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 pairs = 0 while r < n: while True: add = left.get_sum(a[l+1], n) + right.get_sum(0, a[l+1]) if total_inv + add > k: pairs += l + 1 break else: l += 1 total_inv += add left.add(a[l]) total_inv -= left.get_sum(a[r], n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 print(pairs) ```
instruction
0
95,554
12
191,108
No
output
1
95,554
12
191,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element. Help the Little Elephant and count the number of the described pairs. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output In a single line print a single number — the answer to the problem. Examples Input 3 1 1 3 2 Output 3 Input 5 2 1 3 2 1 7 Output 6 Submitted Solution: ``` ''' Created on 19/07/2018 @author: ernesto ''' # XXX: http://codeforces.com/problemset/problem/220/E #  XXX: https://practice.geeksforgeeks.org/problems/magic-triplets/0 # XXX: https://gist.github.com/robert-king/5660418 class RangeBit: def __init__(self, n): sz = 1 while n >= sz: sz *= 2 self.size = sz self.dataAdd = [0] * sz self.dataMul = [0] * sz def sum(self, i): r = 0 if i > 0: add = 0 mul = 0 start = i while i > 0: add += self.dataAdd[i] mul += self.dataMul[i] i -= i & -i r = mul * start + add return r def add(self, left, right, by): assert 0 < left <= right self._add(left, by, -by * (left - 1)) self._add(right, -by, by * right) def _add(self, i, mul, add): assert i > 0 while i < self.size: self.dataAdd[i] += add self.dataMul[i] += mul i += i & -i def sum_range(self, i, j): # print("j {} s {}".format(j, self.sum(j))) # print("i {} s {}".format(i, self.sum(i))) return self.sum(j) - self.sum(i - 1) def sum_back(self, i): return self.sum_range(i, self.size - 1) def add_point(self, i, by): self.add(i, i, by) class numero(): def __init__(self, valor, posicion_inicial): self.valor = valor self.posicion_inicial = posicion_inicial self.posicion_final = -1; def __lt__(self, other): if self.valor == other.valor: r = self.posicion_inicial < other.posicion_inicial else: r = self.valor < other.valor return r def __repr__(self): return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final) def swap(a, i, j): a[i], a[j] = a[j], a[i] def crea_arreglo_enriquecido(nums): numso = list(sorted(nums)) numse = list(map(lambda t:numero(t[1], t[0]), enumerate(nums))) numseo = [] for i in range(len(nums)): if nums[i] != numso[i]: numseo.append(numse[i]) numseo = list(sorted(numseo)) j = 0 for i in range(len(nums)): if nums[i] != numso[i]: numse[i] = numseo[j] j += 1 numse[i].posicion_final = i for i in range(len(nums)): while i != numse[i].posicion_inicial: swap(numse, i, numse[i].posicion_inicial) return numse def fuerza_bruta(a): a_len = len(a) r = 0 for i in range(a_len): for j in range(i): if a[i] < a[j]: r += 1 return r def quita(bi, bd, a, i): return modifica(bi, bd, a, i, False) def anade(bi, bd, a, i): return modifica(bi, bd, a, i, True) def modifica(bi, bd, a, i, anade): if anade: bc = bi fac = 1 else: bc = bd fac = -1 inv = bi.sum(a[i] + 1) + bd.sum(a[i] - 1) bc.add_point(a[i], fac) return inv def core(nums, nmi): numse = crea_arreglo_enriquecido(nums) a = list(map(lambda x:x.posicion_final + 1, numse)) i = 0 j = 0 ni = 0 r = 0 a_len = len(a) bitch_izq = RangeBit(a_len + 2) bitch_der = RangeBit(a_len + 2) nif = 0 for x in a: nif += bitch_der.sum_range(x + 1, a_len) bitch_der.add(x, x, 1) j = 0 ni = nif # print("ni ini {}".format(ni)) for i in range(1, a_len): while j < a_len and (j < i or ni > nmi): ni -= quita(bitch_izq, bitch_der, a, j) # print("en j {} se kito {}".format(j, ni)) j += 1 r += a_len - j ni += anade(bitch_izq, bitch_der, a, i) # print("en i {} se puso {}".format(i, ni)) # print("r f aora {}".format(r)) return r _, k = [int(x) for x in input().strip().split(" ")] nums = [int(x) for x in input().strip().split(" ")] # nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7] # nums = [1, 3, 2, 1, 7] # nums = [1, 3, 2] # k = 0 print(core(nums, k)) ```
instruction
0
95,555
12
191,110
No
output
1
95,555
12
191,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≤ i < j ≤ |b| and bi > bj, where |b| is the length of sequence b, and bj is its j-th element. Help the Little Elephant and count the number of the described pairs. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 1018) — the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output In a single line print a single number — the answer to the problem. Examples Input 3 1 1 3 2 Output 3 Input 5 2 1 3 2 1 7 Output 6 Submitted Solution: ``` ''' Created on 19/07/2018 @author: ernesto ''' # XXX: http://codeforces.com/problemset/problem/220/E # XXX: https://gist.github.com/robert-king/5660418 class RangeBit: def __init__(self, n): sz = 1 while n >= sz: sz *= 2 self.size = sz self.dataAdd = [0] * sz self.dataMul = [0] * sz def sum(self, i): assert i > 0 add = 0 mul = 0 start = i while i > 0: add += self.dataAdd[i] mul += self.dataMul[i] i -= i & -i return mul * start + add def add(self, left, right, by): assert 0 < left <= right self._add(left, by, -by * (left - 1)) self._add(right, -by, by * right) def _add(self, i, mul, add): assert i > 0 while i < self.size: self.dataAdd[i] += add self.dataMul[i] += mul i += i & -i def sum_range(self, i, j): # print("j {} s {}".format(j, self.sum(j))) # print("i {} s {}".format(i, self.sum(i))) return self.sum(j) - self.sum(i - 1) class numero(): def __init__(self, valor, posicion_inicial): self.valor = valor self.posicion_inicial = posicion_inicial self.posicion_final = -1; def __lt__(self, other): if self.valor == other.valor: r = self.posicion_inicial < other.posicion_inicial else: r = self.valor < other.valor return r def __repr__(self): return "{}:{}:{}".format(self.valor, self.posicion_inicial, self.posicion_final) def swap(a, i, j): a[i], a[j] = a[j], a[i] def crea_arreglo_enriquecido(nums): numso = list(sorted(nums)) numse = list(map(lambda t:numero(t[1], t[0]), enumerate(nums))) numseo = [] for i in range(len(nums)): if nums[i] != numso[i]: numseo.append(numse[i]) numseo = list(sorted(numseo)) j = 0 for i in range(len(nums)): if nums[i] != numso[i]: numse[i] = numseo[j] j += 1 numse[i].posicion_final = i for i in range(len(nums)): while i != numse[i].posicion_inicial: swap(numse, i, numse[i].posicion_inicial) return numse def fuerza_bruta(a): a_len = len(a) r = 0 for i in range(a_len): for j in range(i): if a[i] < a[j]: r += 1 return r def core(nums, nmi): numse = crea_arreglo_enriquecido(nums) a = (list(map(lambda x:x.posicion_final + 1, numse))) i = 0 j = 0 ni = 0 r = 0 lmin = False a_len = len(a) bitch = RangeBit(a_len + 2) bitch.add(a[0], a[0], 1) while True: if ni <= nmi: j += 1 if j == a_len: break bitch.add(a[j], a[j], 1) ni += bitch.sum_range(a[j] + 1, a_len) # print("anadido {} aora {}".format(a[j], ni)) lmin = True else: bitch.add(a[i], a[i], -1) if a[i] - 1: ni -= bitch.sum(a[i] - 1) # print("kitado {} aora {}".format(a[i], ni)) if lmin and ni > nmi: n = j - i - 1 # print("la ventana es i {} j {} n {}".format(i, j, n)) r += (n * (n + 1)) >> 1 # print("r aora {}".format(r)) lmin = False i += 1 caca = fuerza_bruta(a[i:j + 1]) assert caca == ni, "caca {} ni {} en nums {}".format(caca, ni, a[i:j + 1]) j -= 1 while ni > nmi : assert i < j bitch.add(a[i], a[i], -1) if a[i] - 1: ni -= bitch.sum(a[i] - 1) i += 1 caca = fuerza_bruta(a[i:j + 1]) assert caca == ni, "caca f {} ni {} en nums {}".format(caca, ni, a[i:j + 1]) if i < j: assert ni <= nmi n = j - i # print("la ventana f es i {} j {} n {}".format(i, j, n)) r += (n * (n + 1)) >> 1 # print("r f aora {}".format(r)) return r _, k = [int(x) for x in input().strip().split(" ")] nums = [int(x) for x in input().strip().split(" ")] # nums = [6, 8, 6, 7, 2, 4, 2, 1, 7, 6, 2, 1, 2, 3, 2, 5, 3, 7, 1, 7, 7] # nums = [1, 3, 2, 1, 7] # nums = [1, 3, 2] # k = 0 print(core(nums, k)) ```
instruction
0
95,556
12
191,112
No
output
1
95,556
12
191,113
Provide tags and a correct Python 3 solution for this coding contest problem. Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array. Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number. More formally, you are required to calculate the number of pairs l, r (l ≤ r) such that a_l + a_{l+1} + ... + a_{r-1} + a_r < t. Input The first line contains two integers n and t (1 ≤ n ≤ 200 000, |t| ≤ 2⋅10^{14}). The second line contains a sequence of integers a_1, a_2, ..., a_n (|a_{i}| ≤ 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements. Output Print the number of segments in Petya's array with the sum of elements less than t. Examples Input 5 4 5 -1 3 4 -1 Output 5 Input 3 0 -1 2 -3 Output 4 Input 4 -1 -2 1 -2 3 Output 3 Note In the first example the following segments have sum less than 4: * [2, 2], sum of elements is -1 * [2, 3], sum of elements is 2 * [3, 3], sum of elements is 3 * [4, 5], sum of elements is 3 * [5, 5], sum of elements is -1
instruction
0
96,076
12
192,152
Tags: data structures, divide and conquer, two pointers Correct Solution: ``` def merge(l,r): global num if l>=r: return mid=(l+r)>>1 merge(l,mid) merge(mid+1,r) j=mid+1 for i in range(l,mid+1): while j<=r and arr[j]-arr[i]<t: j+=1 num+=j-mid-1 arr[l:r+1]=sorted(arr[l:r+1]) n,t=map(int,input().split()) List=list(map(int,input().split())) num=0 arr=[0]*(n+1) for i in range(1,n+1): arr[i]=arr[i-1]+List[i-1] merge(0,n) print(num) ```
output
1
96,076
12
192,153