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. This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Input 3 2 1000000000 1 999999999 Output 1 999999998 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. Submitted Solution: ``` from bisect import bisect_right as br import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] n, p = MI() aa = LI() aa.sort() def low(x): for i in range(n): if br(aa, i + x) - i < 1: return False return True l = min(aa) - 1 r = max(aa) + 1 while l + 1 < r: x = (l + r) // 2 if low(x): r = x else: l = x mn = r def high(x): for i in range(n): if br(aa, i + x) - i >= p: return False return True l = mn - 1 r = max(aa) + 1 while l + 1 < r: x = (l + r) // 2 if high(x): l = x else: r = x mx = l ans = list(range(mn, mx + 1)) print(len(ans)) print(*ans) ```
instruction
0
76,049
12
152,098
Yes
output
1
76,049
12
152,099
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Input 3 2 1000000000 1 999999999 Output 1 999999998 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. Submitted Solution: ``` import sys import collections def input(): return sys.stdin.readline().rstrip() def split_input(): return [int(i) for i in input().split()] n,p = split_input() a = split_input() start = max(a) - n + 1 x = [0 for i in range(n)] for i in a: ind = i - start if ind <= 0: x[0] += 1 else: x[ind] += 1 for i in range(1,n): x[i] += x[i-1] # print(x) zero_ind = -1 for i in range(n): zero_ind = max(i - x[i], zero_ind) s = set() for i in range(zero_ind + 1, p): if x[i] >= p: t = p while (x[i] >= t): s.add(i - (x[i] - t)) t += p # print(i,i - (x[i] - p),x[i]) # count = 0 if n == 100000 and p == 223: print(zero_ind, min(s), max(s)) ans = [] for i in range(zero_ind + 1, p): if i not in s: ans.append(i + start) print(len(ans)) print(*ans, sep = " ") ```
instruction
0
76,050
12
152,100
No
output
1
76,050
12
152,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Input 3 2 1000000000 1 999999999 Output 1 999999998 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. Submitted Solution: ``` n,p = map(int,input().split()) a = list(map(int,input().split())) a.sort() ans = 0 ansls = [] mx = max(a) mn = max([a[i]-i for i in range(n)]) ansmx = -1 for j in range(p,n)[::-1]: ansmx = max(ansmx,n-max(mn,a[j])+mn-(n-j-1)) while ansmx < p: ans += 1 ansls.append(mn) mn += 1 ansmx += 1 print(ans) print(*ansls) ```
instruction
0
76,051
12
152,102
No
output
1
76,051
12
152,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Input 3 2 1000000000 1 999999999 Output 1 999999998 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. Submitted Solution: ``` n, p = map(int, input().split()) a = list(map(int, input().split())) a = sorted(a) for i in range(n): a[i] -= i l = max(a) for i in range(n): a[i] += p - 1 r = min(a[p - 1:]) print(r - l) print(*[val for val in range(l, r)]) ```
instruction
0
76,052
12
152,104
No
output
1
76,052
12
152,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x candies. There are also n enemies numbered with integers from 1 to n. Enemy i has a_i candies. Yuzu is going to determine a permutation P. A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, \{2,3,1,5,4\} is a permutation, but \{1,2,2\} is not a permutation (2 appears twice in the array) and \{1,3,4\} is also not a permutation (because n=3 but there is the number 4 in the array). After that, she will do n duels with the enemies with the following rules: * If Yuzu has equal or more number of candies than enemy P_i, she wins the duel and gets 1 candy. Otherwise, she loses the duel and gets nothing. * The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations P exist? This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea: Let's define f(x) as the number of valid permutations for the integer x. You are given n, a and a prime number p ≤ n. Let's call a positive integer x good, if the value f(x) is not divisible by p. Find all good integers x. Your task is to solve this problem made by Akari. Input The first line contains two integers n, p (2 ≤ p ≤ n ≤ 10^5). It is guaranteed, that the number p is prime (it has exactly two divisors 1 and p). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). Output In the first line, print the number of good integers x. In the second line, output all good integers x in the ascending order. It is guaranteed that the number of good integers x does not exceed 10^5. Examples Input 3 2 3 4 5 Output 1 3 Input 4 3 2 3 5 6 Output 2 3 4 Input 4 3 9 1 1 1 Output 0 Input 3 2 1000000000 1 999999999 Output 1 999999998 Note In the first test, p=2. * If x ≤ 2, there are no valid permutations for Yuzu. So f(x)=0 for all x ≤ 2. The number 0 is divisible by 2, so all integers x ≤ 2 are not good. * If x = 3, \{1,2,3\} is the only valid permutation for Yuzu. So f(3)=1, so the number 3 is good. * If x = 4, \{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\} are all valid permutations for Yuzu. So f(4)=4, so the number 4 is not good. * If x ≥ 5, all 6 permutations are valid for Yuzu. So f(x)=6 for all x ≥ 5, so all integers x ≥ 5 are not good. So, the only good number is 3. In the third test, for all positive integers x the value f(x) is divisible by p = 3. Submitted Solution: ``` import bisect import sys input=sys.stdin.readline n,p=map(int,input().split()) arr1=list(map(int,input().split())) arr1=sorted(arr1) mins=0 for i in range(n): mins=max(mins,arr1[i]-i) maxs=arr1[p-1] arr2=[0]*n for i in range(n): arr2[i]=(p-(n-arr1[n-i-1]-i))%p arr2=arr2[::-1] can=set(range(p)) pos=bisect.bisect_right(arr1,maxs-1) for i in range(pos,n): can.discard(arr2[i]) ans=[] prev=pos for x in range(maxs-1,mins-1,-1): pos=bisect.bisect_right(arr1,x) if pos==prev: if x%p in can: ans.append(x) else: for i in range(pos,prev): can.discard(arr2[i]) if x%p in can: ans.append(x) prev=pos print(x,pos,can,ans) ans=ans[::-1] print(len(ans)) print(*ans) ```
instruction
0
76,053
12
152,106
No
output
1
76,053
12
152,107
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m). We will assume that the submatrix contains cells (i, j) (d ≤ i ≤ u; l ≤ j ≤ r). The area of the submatrix is the number of cells it contains. Input The first line contains two integers n and m (1 ≤ n, m ≤ 5000). Next n lines contain m characters each — matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines. Output Print a single integer — the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0. Examples Input 1 1 1 Output 1 Input 2 2 10 11 Output 2 Input 4 3 100 011 000 101 Output 2
instruction
0
76,201
12
152,402
Tags: data structures, dp, implementation, sortings Correct Solution: ``` ''' from bisect import bisect,bisect_left from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import *''' #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return flag def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue seen.add(u) for v,w in graph[u]: if v not in d or d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None t=1 for i in range(t): n,m=RL() res=[] for i in range(n): res.append(input()) dp=A2(n,m) for i in range(n): dp[i][0]=int(res[i][0]=='1') for j in range(1,m): if res[i][j]=='1': dp[i][j]=dp[i][j-1]+1 ans=0 for j in range(m): cnt=A(m+1) for i in range(n): cnt[dp[i][j]]+=1 res=0 #print(cnt) for i in range(m,0,-1): res+=cnt[i] ans=max(i*res,ans) print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ```
output
1
76,201
12
152,403
Provide tags and a correct Python 3 solution for this coding contest problem. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
instruction
0
76,267
12
152,534
Tags: binary search, data structures, implementation, sortings, trees Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) d=defaultdict(int) se=set() for i in range(n): a,b=map(int,input().split()) c=d[a] d1=d[b] if d[a]==0: c=a if d[b]==0: d1=b d[b]=c d[a]=d1 se.add(a) se.add(b) t=0 ind=defaultdict(int) indr=defaultdict(int) for i in sorted(se): ind[i]=t t+=1 for i in d: indr[d[i]]=i e=[0]*t s=SegmentTree(e) ans=0 for i in sorted(se,reverse=True): e[ind[indr[i]]]+=1 s.__setitem__(ind[indr[i]],e[ind[indr[i]]]) ans+=s.query(0,ind[indr[i]]-1) for i in sorted(se): if indr[i] > i: ans += indr[i] - i - s.query(ind[i], ind[indr[i]] - 1) if indr[i]<i: ans+=i-indr[i]-s.query(ind[indr[i]]+1,ind[i]) print(ans) ```
output
1
76,267
12
152,535
Provide tags and a correct Python 3 solution for this coding contest problem. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
instruction
0
76,268
12
152,536
Tags: binary search, data structures, implementation, sortings, trees Correct Solution: ``` """ Author - Satwik Tiwari . 28th NOV , 2020 - Saturday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) class FenwickTree: def __init__(self, x): """transform list into BIT""" self.bit = x for i in range(len(x)): j = i | (i + 1) if j < len(x): x[j] += x[i] def update(self, idx, x): """updates bit[idx] += x""" while idx < len(self.bit): self.bit[idx] += x idx |= idx + 1 def query(self, end): """calc sum(bit[:end])""" x = 0 while end: x += self.bit[end - 1] end &= end - 1 return x def findkth(self, k): """Find largest idx such that sum(bit[:idx]) <= k""" idx = -1 for d in reversed(range(len(self.bit).bit_length())): right_idx = idx + (1 << d) if right_idx < len(self.bit) and k >= self.bit[right_idx]: idx = right_idx k -= self.bit[idx] return idx + 1 def printpref(self): out = [] for i in range(len(self.bit) + 1): out.append(self.query(i)) print(out) def solve(case): n = int(inp()) op = [] have = {} for i in range(n): a,b = sep() have[a] = 1 have[b] = 1 op.append((a,b)) a = [] for i in have: a.append(i) a= sorted(a) # sora = deepcopy(a) # print(a) orpos = {} for i in have: orpos[i] = i pos = {} for i in range(len(a)): pos[a[i]] = i curr = 1 mapper = {} for i in range(len(a)): mapper[a[i]] = curr curr+=1 # print(mapper) for i,j in op: orpos[i],orpos[j] = orpos[j],orpos[i] a[pos[i]],a[pos[j]] = a[pos[j]],a[pos[i]] pos[i],pos[j] = pos[j],pos[i] # print(a) for i in range(len(a)): a[i] = mapper[a[i]] # print(a) mapp = {} for i in mapper: mapp[mapper[i]] = i # print(mapp) ans = 0 # bit = FenwickTree([0]*(len(a) + 1)) # print(orpos) bit = FenwickTree([0]*(len(a) + 1)) for i in range(len(a)): bit.update(a[i],1) ans+=i - bit.query(a[i]) ans+= abs(mapp[i+1] - mapp[a[i]]) - abs(i+1 - a[i]) # sorpos = {} # sora = sorted(a) # for i in range(len(sora)): # sorpos[sora[i]] = i # # # for i in range(len(a)): # ans print(ans) """ 2 5 3 4 2 """ testcase(1) # testcase(int(inp())) ```
output
1
76,268
12
152,537
Provide tags and a correct Python 3 solution for this coding contest problem. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
instruction
0
76,269
12
152,538
Tags: binary search, data structures, implementation, sortings, trees Correct Solution: ``` import sys from collections import defaultdict class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _get_sum(self, r): ''' sum on interval [0, r) ''' result = 0 while r > 0: result += self.tree[r-1] r &= (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 add(self, i, value=1): while i < self.n: self.tree[i] += value i |= (i + 1) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) swaps = [] for _ in range(n): i, j = map(int, input().split()) swaps.append(i) swaps.append(j) pos = defaultdict(list) for i, val in enumerate(swaps): pos[val].append(i) c = 0 prev = -1 compr = [0] * (2*n) decompr = {} for val in sorted(swaps): if prev == val: continue for j in pos[val]: compr[j] = c decompr[c] = val c += 1 prev = val arr = list(range(c)) for t in range(n): i, j = compr[t<<1], compr[t<<1|1] arr[i], arr[j] = arr[j], arr[i] bit = BIT(c) total_inv = 0 for i, val in enumerate(arr): total_inv += bit.get_sum(val+1, c) if i != val: total_inv += abs(decompr[val] - decompr[i]) - abs(val - i) bit.add(val) print(total_inv) ```
output
1
76,269
12
152,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4). Submitted Solution: ``` import random import datetime import sys import bisect __author__ = 'huash06' # N = int(input()) class Solution: def __init__(self): self.vals = {} def solve(self): # sortedVals = sorted(self.vals.items(), key=lambda x: x[0]) # print(sortedVals) # ivs = [x[1] for x in sortedVals] # print(ivs) ivs = list(self.vals.values()) res = self.inversionCount(ivs, 0, len(ivs)) # print(res) sortedIndice = sorted(self.vals.keys()) for si in sortedIndice: index = si val = self.vals[si] tmp = 0 if index > val: # previous # 如果位置index的数字小于index,计算它前面有多少比它大的数字。 # 除掉其中属於交换位置的数字 tmp += index - val - 1 if tmp > 0: # how many sorted vals in (val, index) # for sv in sortedVals: # i = sv[0] # v = sv[1] # if i > index: # break # if val < i < index: # tmp -= 1 tmp -= self.countSwaps(sortedIndice, val, index) elif index < val: # after # 如果位置index的数字于index,计算它后面有多少比它小的数字。 # 除掉其中属於交换位置的数字 tmp += val - index - 1 if tmp > 0: # how many sorted vals in (index, val) # for sv in sortedVals: # i = sv[0] # v = sv[1] # if i > val: # break # if index < i < val: # tmp -= 1 tmp -= self.countSwaps(sortedIndice, index, val) res += tmp # print(sortedVals) print(res) def readMockInput(self): N = 100000 for i in range(N): # a, b = [int(x) for x in input().split()] a, b = random.randint(1, 50), random.randint(1000, 1000000000) self.vals[a], self.vals[b] = self.getVal(b), self.getVal(a) def readInput(self): N = int(input()) for i in range(N): a, b = [int(x) for x in input().split()] self.vals[a], self.vals[b] = self.getVal(b), self.getVal(a) def getVal(self, pos): if pos in self.vals: return self.vals[pos] return pos def inversionCount(self, vals, l, r): if r - l <= 1: return 0 hlf = (l + r) // 2 leftCount = self.inversionCount(vals, l, hlf) rightCount = self.inversionCount(vals, hlf, r) count = leftCount + rightCount li = l ri = hlf ai = 0 A = [0] * (r-l) while li < hlf and ri < r: if vals[li] <= vals[ri]: A[ai] = vals[li] li += 1 else: A[ai] = vals[ri] ri += 1 # L[li:]所以的数字都大于R[ri],构成len(L)-li+1个逆序对 count += hlf-li ai += 1 while li < hlf: A[ai] = vals[li] ai += 1 li += 1 while ri < r: A[ai] = vals[ri] ai += 1 ri += 1 for i in range(r-l): vals[l+i] = A[i] return count def lowerBounds(self, vals, val): l = 0 r = len(vals) while l < r: mid = (l + r) // 2 if vals[mid] >= val: r = mid elif vals[mid] < val: l = mid + 1 return r def upperBounds(self, vals, val): l = 0 r = len(vals) while l < r: mid = (l + r) // 2 if vals[mid] > val: r = mid elif vals[mid] <= val: l = mid + 1 return l def countSwaps(self, vals, l, r): return self.lowerBounds(vals, r) - self.upperBounds(vals, l) # return bisect.bisect_left(vals, r, 0, len(vals)) - bisect.bisect_right(vals, l, 0, len(vals)) solution = Solution() solution.readInput() # solution.readMockInput() startTime = datetime.datetime.now() solution.solve() sys.stderr.write('Time Cost:{}\n'.format(datetime.datetime.now()-startTime)) ```
instruction
0
76,270
12
152,540
No
output
1
76,270
12
152,541
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4). Submitted Solution: ``` def inverses_merge(ls1, ls2): result = [] it1, it2 = 0, 0 l1 = len(ls1) l2 = len(ls2) while (it1 < l1) and (it2 < l2): if ls1[it1][0] < ls2[it2][0]: result.append(ls1[it1]) it1 += 1 else: result.append((ls2[it2][0], ls2[it2][1] + l1 - it1)) it2 += 1 while it1 < l1: result.append(ls1[it1]) it1 += 1 while it2 < l2: result.append(ls2[it2]) it2 += 1 return result def inverses_get(ls): l = len(ls) if l == 0: return [] if l == 1: return [(ls[0], 0)] else: return inverses_merge(inverses_get(ls[:(l // 2)]), inverses_get(ls[(l // 2):])) n = int(input()) d = {} for i in range(n): x, y = list(map(int, input().split())) if not x in d.keys(): d[x] = x; if not y in d.keys(): d[y] = y; t = d[x] d[x] = d[y] d[y] = t toget = [] index = {} i = 0 for t in d: toget.append(d[t]) index[d[t]] = i i += 1 s = 0 x = inverses_get(toget) for i in range(len(x)): s += x[i][1] s += abs(i - d[x[i][0]]) - abs(i - index[x[i][0]]) print(s) ```
instruction
0
76,271
12
152,542
No
output
1
76,271
12
152,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4). Submitted Solution: ``` import sys import collections result = [(0, 0)] * 200010 ls = [(0, 0)] * 200010 toget = [] def inverses_merge(l1, r1, l2, r2): counter = l1 l = l1 while (l1 < r1) and (l2 < r2): if ls[l1][0] < ls[l2][0]: result[counter] = ls[l1] l1 += 1 else: result[counter] = ((ls[l2][0], ls[l2][1] + r1 - l1)) l2 += 1 counter += 1 while l1 < r1: result[counter] = ls[l1] counter += 1 l1 += 1 while l2 < r2: result[counter] = ls[l2] counter += 1 l2 += 1 for i in range(l, counter, 1): ls[i] = result[i] def inverses_get(l, r): if r - l == 0: return if r - l == 1: ls[l] = (toget[l], 0) return m = (l + r) // 2 inverses_get(l, m) inverses_get(m, r) inverses_merge(l, m, m, r) n = int(sys.stdin.readline()) d = {} for i in range(n): x, y = list(map(int, sys.stdin.readline().split())) if not d.__contains__(x): d[x] = x if not d.__contains__(y): d[y] = y t = d[x] d[x] = d[y] d[y] = t index = {} d = collections.OrderedDict(sorted(d.items())) if len(d.items()) > 1000 and d.__contains__(100000): print("FAIL") sys.exit() i = 0 for t in (d.items()): toget.append(t[1]) index[t[1]] = i i += 1 s = 0 inverses_get(0, len(toget)) x = result for i in range(len(toget)): s += x[i][1] s += abs(x[i][0] - d[x[i][0]]) - abs(i - index[x[i][0]]) sys.stdout.write(str(s) + "\n") ```
instruction
0
76,272
12
152,544
No
output
1
76,272
12
152,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation. Output Print a single integer — the number of inversions in the resulting sequence. Examples Input 2 4 2 1 4 Output 4 Input 3 1 6 3 4 2 5 Output 15 Note In the first sample the sequence is being modified as follows: <image>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4). Submitted Solution: ``` import sys import collections result = [(0, 0)] * 200010 ls = [(0, 0)] * 200010 toget = [] def inverses_merge(l1, r1, l2, r2): counter = l1 l = l1 while (l1 < r1) and (l2 < r2): if ls[l1][0] < ls[l2][0]: result[counter] = ls[l1] l1 += 1 else: result[counter] = ((ls[l2][0], ls[l2][1] + r1 - l1)) l2 += 1 counter += 1 while l1 < r1: result[counter] = ls[l1] counter += 1 l1 += 1 while l2 < r2: result[counter] = ls[l2] counter += 1 l2 += 1 for i in range(l, counter, 1): ls[i] = result[i] def inverses_get(l, r): if r - l == 0: return if r - l == 1: ls[l] = (toget[l], 0) return m = (l + r) // 2 inverses_get(l, m) inverses_get(m, r) inverses_merge(l, m, m, r) n = int(sys.stdin.readline()) d = {} for i in range(n): x, y = list(map(int, sys.stdin.readline().split())) if not d.__contains__(x): d[x] = x if not d.__contains__(y): d[y] = y t = d[x] d[x] = d[y] d[y] = t index = {} d = collections.OrderedDict(sorted(d.items())) if len(d.items()) > 1000 and d.__contains__(10000): print("FAIL") sys.exit() i = 0 for t in (d.items()): toget.append(t[1]) index[t[1]] = i i += 1 s = 0 inverses_get(0, len(toget)) x = result for i in range(len(toget)): s += x[i][1] s += abs(x[i][0] - d[x[i][0]]) - abs(i - index[x[i][0]]) sys.stdout.write(str(s) + "\n") ```
instruction
0
76,273
12
152,546
No
output
1
76,273
12
152,547
Provide tags and a correct Python 3 solution for this coding contest problem. Author has gone out of the stories about Vasiliy, so here is just a formal task description. You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: 1. "+ x" — add integer x to multiset A. 2. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. 3. "? x" — you are given integer x and need to compute the value <image>, i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A. Multiset is a set, where equal elements are allowed. Input The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A. Output For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A. Example Input 10 + 8 + 9 + 11 + 6 + 1 ? 3 - 8 ? 3 ? 8 ? 11 Output 11 10 14 13 Note After first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1. The answer for the sixth query is integer <image> — maximum among integers <image>, <image>, <image>, <image> and <image>.
instruction
0
76,335
12
152,670
Tags: binary search, bitmasks, data structures, trees Correct Solution: ``` import sys input = sys.stdin.readline class BinaryTrie: class Node: def __init__(self, bit: bool = False): self.bit = bit # Stores the current bit (False if 0, True if 1) self.children = [] self.count = 0 # stores number of keys finishing at this bit self.counter = 1 # stores number of keys with this bit as prefix def __init__(self, size): self.root = BinaryTrie.Node() self.size = size # Maximum size of each key def convert(self, key): """Converts key from string/integer to a list of boolean values!""" bits = [] if isinstance(key, int): key = bin(key)[2:] if isinstance(key, str): for i in range(self.size - len(key)): bits += [False] for i in key: if i == "0": bits += [False] else: bits += [True] else: return list(key) return bits def add(self, key): """Add a key to the trie!""" node = self.root bits = self.convert(key) for bit in bits: found_in_child = False for child in node.children: if child.bit == bit: child.counter += 1 node = child found_in_child = True break if not found_in_child: new_node = BinaryTrie.Node(bit) node.children.append(new_node) node = new_node node.count += 1 def remove(self, key): """Removes a key from the trie! If there are multiple occurences, it removes only one of them.""" node = self.root bits = self.convert(key) nodelist = [node] for bit in bits: for child in node.children: if child.bit == bit: node = child node.counter -= 1 nodelist.append(node) break node.count -= 1 if not node.children and not node.count: for i in range(len(nodelist) - 2, -1, -1): nodelist[i].children.remove(nodelist[i + 1]) if nodelist[i].children or nodelist[i].count: break def query(self, prefix, root=None): """Search for a prefix in the trie! Returns the node if found, otherwise 0.""" if not root: root = self.root node = root if not root.children: return 0 for bit in prefix: bit_not_found = True for child in node.children: if child.bit == bit: bit_not_found = False node = child break if bit_not_found: return 0 return node di = {} tr = BinaryTrie(32) tr.add(0) for _ in range(int(input())): a, b = input().split() if a == "+": tr.add(int(b)) elif a == "-": tr.remove(int(b)) else: ans = 0 node = tr.root cnt = 32 y = bin(int(b))[2:] x = [False if i == "0" else True for i in "0"*(32-len(y)) + y] for i in x: cnt -= 1 next = tr.query([not i], node) if not next: node = tr.query([i], node) else: node = next ans += 2**cnt print(ans) ```
output
1
76,335
12
152,671
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,888
12
153,776
Tags: constructive algorithms, greedy, math Correct Solution: ``` '''Author- Akshit Monga''' import math t=int(input()) for _ in range(t): n=int(input()) arr=[int(x) for x in input().split()] if sum(arr)%n!=0: print(-1) continue p=sum(arr)//n ans=[] for i in range(1,n): if arr[i]%(i+1)==0: x=arr[i]//(i+1) arr[0] += arr[i] arr[i]=0 ans.append((i+1,1,x)) else: delta=(math.ceil(arr[i]/(i+1))*(i+1))-(arr[i]) ans.append((1, i + 1, delta)) arr[0]-=delta arr[i]+=delta assert arr[i]%(i+1)==0 x = arr[i] // (i + 1) arr[0] += arr[i] arr[i] = 0 ans.append((i + 1, 1, x)) # print(arr[0]) # print(arr) for i in range(1,n): ans.append((1,i+1,p)) arr[0]-=p arr[i]+=p print(len(ans)) # print(arr) for i in ans: print(i[0],i[1],i[2]) ```
output
1
76,888
12
153,777
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,889
12
153,778
Tags: constructive algorithms, greedy, math Correct Solution: ``` import math import collections t=int(input()) for w in range(t): n=int(input()) l=[int(i) for i in input().split()] s=sum(l) if(s%n!=0): print(-1) else: l1=[] c=0 for i in range(1,n): if(l[i]%(i+1)!=0): c+=2 l1.append((1,i+1,(i+1-l[i]%(i+1)))) l1.append((i+1,1,(l[i]//(i+1))+1)) else: c+=1 l1.append((i+1,1,l[i]//(i+1))) print(c+n-1) for i in range(c): print(l1[i][0],l1[i][1],l1[i][2]) for i in range(1,n): print(1,i+1,(s//n)) ```
output
1
76,889
12
153,779
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,890
12
153,780
Tags: constructive algorithms, greedy, math Correct Solution: ``` import sys ii = lambda: sys.stdin.readline().strip() idata = lambda: [int(x) for x in ii().split()] def solve(): n = int(ii()) data = idata() k = sum(data) // n if sum(data) % n: print(-1) return ans = [] for i in range(1, n): ans += [(1, i + 1, (i + 1 - (data[i] % (i + 1))) % (i + 1))] ans += [(i + 1, 1, (data[i] + i) // (i + 1))] for i in range(1, n): ans += [(1, i + 1, k)] print(len(ans)) for i in range(len(ans)): a, b, c = ans[i] print(a, b, c) return for t1 in range(int(ii())): solve() ```
output
1
76,890
12
153,781
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,891
12
153,782
Tags: constructive algorithms, greedy, math Correct Solution: ``` import os from sys import stdin, stdout class Input: def __init__(self): self.lines = stdin.readlines() self.idx = 0 def line(self): try: return self.lines[self.idx].strip() finally: self.idx += 1 def array(self, sep = ' ', cast = int): return list(map(cast, self.line().split(sep = sep))) def known_tests(self): num_of_cases, = self.array() for case in range(num_of_cases): yield self def unknown_tests(self): while self.idx < len(self.lines): yield self def problem_solver(): ''' ''' def solver(inpt): n, = inpt.array() a = inpt.array() s = sum(a) if s % n != 0: print(-1) return h = s // n c = [] for k in range(1, n): i = k + 1 y = a[k] % i if y: a[0] -= i - y a[k] += i - y c.append((1, i, i - y)) x = a[k] // i if x: a[0] += x * i a[k] -= x * i c.append((i, 1, x)) for k in range(1, n): i = k + 1 c.append((1, i, h)) print(len(c)) for x in c: print(*x) '''Returns solver''' return solver try: solver = problem_solver() for tc in Input().known_tests(): solver(tc) except Exception as e: import traceback traceback.print_exc(file=stdout) ```
output
1
76,891
12
153,783
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,892
12
153,784
Tags: constructive algorithms, greedy, math Correct Solution: ``` import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def output(*args): sys.stdout.buffer.write( ('\n'.join(map(str, args)) + '\n').encode('utf-8') ) def main(): t = int(input()) ans_a = [''] * t for ti in range(t): n = int(input()) a = [0] + list(map(int, input().split())) sum_a = sum(a) if sum_a % n: ans_a[ti] = '-1' continue req = sum_a // n ans = [] for i in range(2, n + 1): if a[i] % i: ans.append(f'{1} {i} {i - a[i] % i}') a[1] -= i - a[i] % i a[i] += i - a[i] % i ans.append(f'{i} {1} {a[i] // i}') a[1] += a[i] a[i] = 0 for i in range(2, n + 1): ans.append(f'{1} {i} {req}') ans_a[ti] = f'{len(ans)}\n' + '\n'.join(ans) output(*ans_a) if __name__ == '__main__': main() ```
output
1
76,892
12
153,785
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,893
12
153,786
Tags: constructive algorithms, greedy, math Correct Solution: ``` def t(lst): return ' '.join(map(str, lst)) gans = [] for _ in range(int(input())): n = int(input()) u = list(map(int, input().split())) ans = [] sm = sum(u) fn = sm // n if sm % n != 0: gans.append(str(-1)) continue for i in range(1, n): cur = (i + 1 - (u[i] % (i + 1))) % (i + 1) ans.append(t([1, i + 1, cur])) ans.append(t([i + 1, 1, (u[i] + cur) // (i + 1)])) for i in range(1, n): ans.append(t([1, i + 1, fn])) gans.append(str(len(ans))) gans += ans print('\n'.join(gans)) ```
output
1
76,893
12
153,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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,894
12
153,788
Tags: constructive algorithms, greedy, math Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) f = True ans = [] for i in range(1, n): x = a[i] % (i + 1) if x != 0: x = (i + 1) - x if a[0] >= x: ans.append((1, (i + 1), x)) a[i] += x a[0] -= x ans.append(((i + 1), 1, int((a[i] + x) / (i + 1)))) a[0] += a[i] a[i] = 0 else: f = False break if f == False or a[0] % n: print(-1) else: for i in range(1, n): ans.append((1, (i + 1), int(a[0] / n))) print(len(ans)) for i, j, x in ans: print(i, j, x) ```
output
1
76,894
12
153,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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1
instruction
0
76,895
12
153,790
Tags: constructive algorithms, greedy, math Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=998244353 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() for _ in range(Int()): n=Int() a=array() ans=[] if(len(set(a))==1): print(0) continue for i in range(1,n): k=i+1 ans.append((1,k,(k-a[i]%k)%k)) a[0]-=(k-a[i]%k)%k a[i]+=(k-a[i]%k)%k ans.append((k,1,a[i]//k)) a[0]+=k*(a[i]//k) a[i]-=k*(a[i]//k) tot=sum(a) if(tot%n): print(-1) else: need=tot//n for i in range(1,n): here=need-a[i] a[i]+=here ans.append((1,i+1,here)) a[0]-=here # print(*a) print(len(ans)) for i in ans: print(*i) ```
output
1
76,895
12
153,791
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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().split())) sum_all = sum(arr) if sum_all % n: print(-1) continue op = [] changes = True non_zero = True pos = 1 smallest = 1 while changes and smallest < n: for i in range(smallest, n): if (arr[i] > 0 and arr[i] % (i + 1) and (i + 1 - arr[i] % (i + 1) <= arr[0])): k = i + 1 - arr[i] % (i + 1) op.append((1, i + 1, k)) arr[0] -= k arr[i] += k if arr[i] > 0 and arr[i] % (i + 1) == 0: op.append((i + 1, 1, arr[i] // (i + 1))) arr[0] += arr[i] arr[i] = 0 while pos < len(arr) and arr[pos] < pos + 1: pos += 1 while smallest < len(arr) and arr[smallest] == 0: smallest += 1 if pos == n and smallest < n: break if pos != n: op.append((pos + 1, 1, arr[pos] // (pos + 1))) arr[0] += arr[pos] // (pos + 1) * (pos + 1) arr[pos] %= pos + 1 if smallest < n: print(-1) break for i in range(1, n): op.append((1, i + 1, sum_all // n)) print(len(op)) print('\n'.join(map(lambda x: str(x[0]) + ' ' + str(x[1]) + ' ' + str(x[2]), op))) ```
instruction
0
76,896
12
153,792
Yes
output
1
76,896
12
153,793
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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) s = sum(a) if s % n != 0: print(-1) continue b = s // n ans = [] for i in range(1, n): x = (i + 1 - (a[i] % (i + 1))) % (i + 1) ans += [[1, i + 1, x]] a[0] -= x a[i] += x ans += [[i + 1, 1, a[i] // (i + 1)]] a[0] += a[i] a[i] = 0 for i in range(1, n): ans += [[1, i + 1, b]] print(len(ans)) [print(*i) for i in ans] ```
instruction
0
76,897
12
153,794
Yes
output
1
76,897
12
153,795
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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` import copy def main(inp): t = int(inp()) for __ in range(t): def move(i, j, d, arr, commands): arr[i-1] -= d arr[j-1] += d commands.append((i, j, d//i)) assert arr[i-1] >= 0 def f(): n = int(inp()) arr = split_inp_int(inp) # calculate average total = sum(arr) if total % n != 0: print(-1) return avg = total//n commands = [] for i in range(1, n+1): if arr[i-1] % i: move(1, i, i - (arr[i-1] % i), arr, commands) move(i, 1, arr[i-1], arr, commands) for i in range(2, n+1): if arr[i-1] < avg: move(1, i, avg-arr[i-1], arr, commands) print(len(commands)) for command in commands: print(*command) for i in range(1, n): assert arr[i-1] == avg f() def split_inp_int(inp): return list(map(int, inp().split())) def use_fast_io(): import sys class InputStorage: def __init__(self, lines): lines.reverse() self.lines = lines def input_func(self): if self.lines: return self.lines.pop() else: return "" input_storage_obj = InputStorage(sys.stdin.readlines()) return input_storage_obj.input_func from collections import Counter, defaultdict from functools import reduce import operator import math def product(arr_): return reduce(operator.mul, arr_, 1) if __name__ == "__main__": main(input) ```
instruction
0
76,898
12
153,796
Yes
output
1
76,898
12
153,797
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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prod(a): ans = 1 for each in a: ans = (ans * each) return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if True else 1): n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() req = sum(a) / n if req != int(req): print(-1) continue req = int(req) print((n-1)*3) for i in range(1, n): next = (i + 1 - a[i]) % (i+1) print(1, i+1, next) a[0] -= next a[i] += next print(i+1, 1, a[i]//(i+1)) a[0] += a[i] a[i] = 0 for i in range(1, n): print(1, i+1, req) ```
instruction
0
76,899
12
153,798
Yes
output
1
76,899
12
153,799
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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` for time in range(int(input())): n = int(input()) l = list(map(int, input().split())) if sum(l)%n != 0: print(-1) else: average = sum(l)//n print(3*(n-1)) for i in range(1,n): print(1,i+1,(-l[i])%(i+1),sep=" ") print(i+1,1,(l[i]+i)//(i+1),sep=" ") for i in range(1,n+1): print(1,i+1,average) ```
instruction
0
76,900
12
153,800
No
output
1
76,900
12
153,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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD #------------------------------------------------------------------------- for _ in range (int(input())): n=int(input()) a=list(map(int,input().split())) b=list() s=sum(a) if s%n!=0: print(-1) continue avg=s//n for i in range (1,n): x=a[i]//(i+1) b.append((i+1,1,x)) a[i]-=x*(i+1) a[0]+=x*(i+1) for i in range (1,n): if a[i]>avg and a[i]<i+1: x=i+1-a[i] b.append((1,i+1,x)) a[i]+=x a[0]-=x x=a[i]//(i+1) b.append((i+1,1,x)) a[i]-=x*(i+1) a[0]+=x*(i+1) ch=1 for i in range (1,n): d=avg-a[i] if d>0: b.append((1,i+1,d)) a[0]-=d if a[0]<0: ch=0 if len(b)>3*n or ch==0: print(-1) else: print(len(b)) for i in b: print(*i) ```
instruction
0
76,902
12
153,804
No
output
1
76,902
12
153,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, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array should be non-negative. Can you find a sequence of no more than 3n operations after which all elements of the array are equal? Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 10^4) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case print the answer to it as follows: * if there is no suitable sequence of operations, print -1; * otherwise, print one integer k (0 ≤ k ≤ 3n) — the number of operations in the sequence. Then print k lines, the m-th of which should contain three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9) for the m-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize k. Example Input 3 4 2 16 4 18 6 1 2 3 4 5 6 5 11 19 1 1 3 Output 2 4 1 2 2 3 3 -1 4 1 2 4 2 4 5 2 3 3 4 5 1 Submitted Solution: ``` import sys import math input = sys.stdin.readline ttt = int(input()) for tt in range(ttt): ANS = [] n = int(input()) arr = [int(x) for x in input().split()] if sum(arr) % n != 0: print(-1) continue average = sum(arr) // n arr.insert(0, 0) for i in range(2, n + 1): ANS.append([i - 1, i, 1]) arr[i - 1] -= i - 1 arr[i] += i - 1 for i in range(2, n + 1): if arr[i] != average: ANS.append([i, 1, arr[i] // i]) arr[i] -= (arr[i] // i) * i arr[1] += (arr[i] // i) * i for i in range(2, n + 1): diff = average - arr[i] ANS.append([1, i, diff]) arr[i] = average arr[1] -= diff print(len(ANS)) for i in range(len(ANS)): print(*ANS[i]) ```
instruction
0
76,903
12
153,806
No
output
1
76,903
12
153,807
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,932
12
153,864
Tags: dp, implementation, math Correct Solution: ``` def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b def number_to_list(a): b = [] while a>=1: c = a%10 a = int(a/10) b.append(c) return list(reversed(b)) def str_list_to_int_list(a): a = list(map(int,a)) return a def make_1d_array(n,inti= 0): a = [inti for _ in range(n)] return a def make_2d_array(n,m,inti= 0): a = [[inti for _ in range(m)] for _ in range(n)] return a def make_3d_array(n,m,k,inti= 0): a = [[[inti for _ in range(k)] for _ in range(m)] for _ in range(n)] return a def gcd(a,b): if(b==0): return a else: return gcd(b,a%b); import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input())) n,q,k = I() a = I() dp_start = [0]*n dp_rest = [0]*n dp_end = [0]*n dp_sum = [0]*n if n!=1: prev = -1 for i in range(n): if i==0: dp_start[i] = a[i+1]-2 dp_rest[i] = a[i+1]-2 dp_end[i] = k-1 elif i==n-1: dp_start[i] = k-1 dp_rest[i] = max(0,k-prev-2) dp_end[i] = max(0,k-prev-1) else: dp_start[i] = a[i+1]-2 dp_rest[i] = a[i+1]-prev-2 dp_end[i] = max(0,k-prev-1) prev = a[i] sum1 = 0 for i in range(len(dp_sum)): sum1 += dp_rest[i] dp_sum[i] = sum1 for t1 in range(q): l1,r1 = I() if n==1: print(k-1) elif l1==r1: print(k-1) else: if r1-l1==1: print(dp_start[l1-1]+dp_end[r1-1]) else: print(dp_start[l1-1]+dp_sum[r1-2]-dp_sum[l1-1]+dp_end[r1-1]) ```
output
1
76,932
12
153,865
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,933
12
153,866
Tags: dp, implementation, math Correct Solution: ``` from sys import stdin,stdout n,q,k=map(int,stdin.readline().split()) a=list(map(int,stdin.readline().split())) for _ in range(q): l,r=map(int,stdin.readline().split()) dp=0 if r-l==0: stdout.write(str(k-1)+'\n') else: stdout.write(str(a[r-1]-a[l-1]- 2*(r-l)+k-1)+'\n') ```
output
1
76,933
12
153,867
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,934
12
153,868
Tags: dp, implementation, math Correct Solution: ``` # -*- coding: UTF-8 -*- import sys input = sys.stdin.readline from itertools import accumulate n, q, k = map(int, input().split()) a = list(map(int, input().split())) from_left = [a[0]-1] * n zero_left = [a[0]-1] * n for i in range(1, n): from_left[i] = a[i] - a[i-1] - 1 zero_left[i] = a[i] - 1 accu_left = list(accumulate(from_left)) from_right = [k-a[n-1]] * n zero_right = [k-a[n-1]] * n for i in range(n-2, -1, -1): from_right[i] = a[i+1] - a[i] - 1 zero_right[i] = k - a[i] accu_right = [from_right[n-1]] * n for i in range(n-2, -1, -1): accu_right[i] = accu_right[i+1] + from_right[i] for _ in range(q): l, r = map(int, input().split()) ans = 0 if not l == 1: ans += zero_left[l-1] ans += accu_left[r-1] - accu_left[l-1] else: ans += from_left[l-1] ans += accu_left[r-1] - accu_left[l-1] if not r == n: ans += zero_right[r-1] ans += accu_right[l-1] - accu_right[r-1] else: ans += from_right[r-1] ans += accu_right[l-1] - accu_right[r-1] print(ans) ```
output
1
76,934
12
153,869
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,935
12
153,870
Tags: dp, implementation, math Correct Solution: ``` n,q,k=map(int,input().split()) arr=list(map(int,input().split())) ans=[0]*(n) for i in range(1,n): ans[i]=ans[i-1]+2*(arr[i]-arr[i-1]-1) for qq in range(q): l,r=map(int,input().split()) l-=1 r-=1 print(ans[r]-ans[l]+arr[l]-1+k-arr[r]) ```
output
1
76,935
12
153,871
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,936
12
153,872
Tags: dp, implementation, math Correct Solution: ``` n,q,k=map(int,input().split());a=list(map(int,input().split())) for Q in range(q):l,r=map(int,input().split());print(a[r-1]-a[l-1]+(l-r)*2+k-1) ```
output
1
76,936
12
153,873
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,937
12
153,874
Tags: dp, implementation, math Correct Solution: ``` n, q, k = map(int, input().split()) a = list(map(int, input().split())) b, c = [], [0] if n > 1: for i in range(n): if i == 0: b.append(a[i+1] - 3) elif i == (n-1): b.append(k - a[i-1] - 2) else: b.append(a[i+1] - a[i-1] - 2) for i in range(n): c.append(c[i] + b[i]) for i in range(q): if n == 1: print(k-1) continue result = 0 l, r = map(int, input().split()) if l == r: print(k-1) continue l -= 1 r -= 1 result += a[l+1] + k - a[r-1] - 3 result += c[r] - c[l+1] print(result) ```
output
1
76,937
12
153,875
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,938
12
153,876
Tags: dp, implementation, math Correct Solution: ``` n, q, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(q): l, r = map(int, input().split()) print(k - (r-l+1) + (a[r-1]-a[l-1]+1-(r-l+1))) ```
output
1
76,938
12
153,877
Provide tags and a correct Python 3 solution for this coding contest problem. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5].
instruction
0
76,939
12
153,878
Tags: dp, implementation, math 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") n, q, k = gil() a = gil()+[k+1] ans = [] for i in range(n): prev = a[i-1] if i else 0 ans.append(a[i+1]-prev-1) # print(ans) pre = ans[:] for i in range(1, n): pre[i] += pre[i-1] for _ in range(q): l, r = gil() l -= 1 r -= 1 if l == r: print(k-1) else: v = pre[r] if l: v -= pre[l-1] if l: v += a[l-1] if r+1 < n: v += k-a[r+1]+1 v -= (r-l+1) print(v) ```
output
1
76,939
12
153,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` def readIntArray(): return list(map(int, input().split())) (n, q, k) = readIntArray() a = [0] + readIntArray() + [k + 1] b = [a[i + 1] - a[i - 1] - 2 for i in range(1, n + 1)] c = [0 for i in range(n + 1)] c[1] = b[0] for i in range(1, n): c[i + 1] = c[i] + b[i] for i in range(q): (l, r) = readIntArray() if l == r: print(k - 1) continue inner = c[r - 1] - c[l] left = a[l + 1] - 2 right = k - a[r - 1] - 1 print(inner + left + right) ```
instruction
0
76,940
12
153,880
Yes
output
1
76,940
12
153,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` #!/usr/bin/env python3 n, q, k = map(int, input().split()) a = list(map(int, input().split())) for _ in range(q): l, r = map(int, input().split()) l -= 1 r -= 1 answer = (k + 1) + a[r] - a[l] - 2 * (r - l + 1) print(answer) ```
instruction
0
76,941
12
153,882
Yes
output
1
76,941
12
153,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` import math import sys n,q,k=map(int,input().split()) a=list(map(int,input().split())) if n==1: for _ in range(q): input() print(k-1) else: d = [0,a[1]-2] for i in range(1,n-1): d.append((a[i+1]-a[i-1]-2)) d.append(k-a[-2]-1) d.append(0) f=[0] for i in range(1,len(d)): f.append(f[-1]+d[i]) for _ in range(q): l, r = map(int, input().split()) l-=1;r-=1 if l == r: print(k - 1) else: print(k-a[r-1]-1 + a[l+1]-2 + f[r]-f[l+1]) #print(f) ```
instruction
0
76,942
12
153,884
Yes
output
1
76,942
12
153,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` n, q, k = map(int, input().split()) a = list(map(int, input().split())) for _ in range(q): l, r = map(int, input().split()) s = k-1 + a[r-1]-a[l-1]+2*(l-r) print(s) ```
instruction
0
76,943
12
153,886
Yes
output
1
76,943
12
153,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` import sys,functools,collections,bisect,math #input = sys.stdin.readline print = sys.stdout.write #t = int(input()) for _ in range(1): n,q,k = map(int,input().strip(' ').split(' ')) arr = list(map(int,input().strip(' ').split(' '))) countlow = [] counthigh = [] for i in arr: countlow.append(i-1) counthigh.append(k-i) presum = [0] for i in range(1,n-1): presum.append(countlow[i]-countlow[i-1]+counthigh[i]-counthigh[i+1]-2) presum.append(0) for i in range(1,n): presum[i] += presum[i-1] for i in range(q): r,l = map(int,input().strip(' ').split(' ')) ans = presum[l-2]-presum[r-1] ans += countlow[r-1] if l > r: ans += counthigh[r-1] - counthigh[r] -1 ans += countlow[l-1] - countlow[l-2] -1 ans += counthigh[l-1] print(str(ans)+'\n') ```
instruction
0
76,944
12
153,888
No
output
1
76,944
12
153,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` from collections import Counter, defaultdict, OrderedDict, deque from bisect import bisect_left, bisect_right from functools import reduce, lru_cache from typing import List import itertools import sys import math import heapq import string import random MIN, MAX, MOD = -0x3f3f3f3f, 0x3f3f3f3f, 1000000007 def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) n, q, k = RL() a = RLL() nums = [(a[0]-1 + (a[1]-a[0]-1 if n >= 2 else k - a[0]))] for i in range(1, n - 1): x = a[i] - a[i-1] - 1 x += a[i+1] - a[i] - 1 nums.append(x) if n > 1: nums.append(a[-1] - a[-2] - 1 + k - a[-1]) for _ in range(q): l, r = RL() total = l - 1 + n - r total += 2 * (r-l-1) total += 2 * (a[r-1] - a[l-1]) print(total) ```
instruction
0
76,945
12
153,890
No
output
1
76,945
12
153,891
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` from sys import stdin#, setrecursionlimit from heapq import heappush, heappop, heapify, heappushpop #setrecursionlimit(1000000) lines = stdin.read().splitlines() li = -1 def inp(): global li; li += 1; return lines[li] def inpint(): global li; li += 1; return int(lines[li]) def inpints(change = 0): global li; li += 1; return [int(i) + change for i in lines[li].split()] def inpfloat(): global li; li += 1; return float(lines[li]) def inpfloats(change = 0): global li; li += 1; return [float(i) + change for i in lines[li].split()] n, q, k = inpints() arr = inpints() dp = [0]*(n + 1) dp[0] = k - arr[0] for i in range(1, n - 1): smaller = arr[i - 1] larger = arr[i + 1] dp[i] = larger - smaller - 2 + dp[i - 1] smaller = arr[n - 2] dp[n - 1] = k - smaller + dp[n - 2] for i in range(q): l, r = inpints(-1) total = dp[r - 1] - dp[l] if r >= l + 2 else 0 left = (arr[l + 1] if l < n - 1 else k + 1) - 2 right = k - (arr[r - 1] if r > 0 else 0) - 1 # print(total, left, right) print(total + left + right) ```
instruction
0
76,946
12
153,892
No
output
1
76,946
12
153,893
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a positive integer k, two arrays are called k-similar if: * they are strictly increasing; * they have the same length; * all their elements are positive integers between 1 and k (inclusive); * they differ in exactly one position. You are given an integer k, a strictly increasing array a and q queries. For each query, you are given two integers l_i ≤ r_i. Your task is to find how many arrays b exist, such that b is k-similar to array [a_{l_i},a_{l_i+1}…,a_{r_i}]. Input The first line contains three integers n, q and k (1≤ n, q ≤ 10^5, n≤ k ≤ 10^9) — the length of array a, the number of queries and number k. The second line contains n integers a_1, a_2, …,a_n (1 ≤ a_i ≤ k). This array is strictly increasing — a_1 < a_2 < … < a_n. Each of the following q lines contains two integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). Output Print q lines. The i-th of them should contain the answer to the i-th query. Examples Input 4 2 5 1 2 4 5 2 3 3 4 Output 4 3 Input 6 5 10 2 4 6 7 8 9 1 4 1 2 3 5 1 6 5 5 Output 8 9 7 6 9 Note In the first example: In the first query there are 4 arrays that are 5-similar to [2,4]: [1,4],[3,4],[2,3],[2,5]. In the second query there are 3 arrays that are 5-similar to [4,5]: [1,5],[2,5],[3,5]. Submitted Solution: ``` import sys from sys import stdout import bisect as bi import math from collections import defaultdict as dd from types import GeneratorType ##import queue ##from heapq import heapify, heappush, heappop ##import itertools ##import io ##import os ##import operator ##import random ##sys.setrecursionlimit(10**7) input=sys.stdin.readline ##input = io.BytesIsoO(os.read(0, os.fstat(0).st_size)).readline ##fo=open("output2.txt","w") ##fi=open("input2.txt","w") mo=10**9+7 MOD=998244353 def cin():return map(int,sin().split()) def ain():return list(map(int,sin().split())) def sin():return input().strip() def inin():return int(input()) ##---------------------------------------------------------------------------------------------------------------------- ## def pref(a,n,f): pre=[0]*n if(f==0): ##from beginning pre[0]=a[0] for i in range(1,n): pre[i]=a[i]+pre[i-1] else: ##from end pre[-1]=a[-1] for i in range(n-2,-1,-1): pre[i]=pre[i+1]+a[i] return pre for _ in range(1): n,q,k=cin() arr=ain() if n!=1: choices=[0]*n choices[0]=arr[1]-1-1 choices[-1]=k-arr[-2]-1 for i in range(1,n-1): choices[i]=max(0,arr[i+1]-arr[i-1]-2) prefc=pref(choices,n,0) ## print(choices) ## print(prefc) for i in range(q): l,r=cin() if(n==1):print(k-1) else: ans=0 if (r-l+1) >2: if(l!=1):ans=max(0,prefc[r-2]-prefc[l-1]) else:ans=max(0,prefc[r-2]-prefc[l-1]) ## print(ans,"L") ans+=max(0,arr[l]-2) ## print(ans) ans+=max(0,k-arr[r-2]-1) print(ans) ##-----------------------------------------------------------------------------------------------------------------------# def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) ##2 ki power def pref(a,n,f): pre=[0]*n if(f==0): ##from beginning pre[0]=a[0] for i in range(1,n): pre[i]=a[i]+pre[i-1] else: ##from end pre[-1]=a[-1] for i in range(n-2,-1,-1): pre[i]=pre[i+1]+a[i] return pre # in given set of integers def kadane(A): maxSoFar = maxEndingHere = start = end = beg = 0 for i in range(len(A)): maxEndingHere = maxEndingHere + A[i] if maxEndingHere < 0: maxEndingHere = 0;beg = i + 1 if maxSoFar < maxEndingHere: maxSoFar = maxEndingHere start = beg end = i return (maxSoFar,start,end) #max subarray sum and its range def modFact(n, p): if(n<0):return 0 if n >= p: return 0 result = 1 for i in range(1, n + 1):result = (result * i) % p return result def ncr(n, r, p): if(n<r or n<0): return 0 num = den = 1 for i in range(r): num = (num * (n - i)) % p ;den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p ##https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py ##write @bootstrap before recursive func def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc ```
instruction
0
76,947
12
153,894
No
output
1
76,947
12
153,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. And here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array. * Let's consider an arbitrary interval of the array with length len, starting in position i. Value <image>, is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length len, taken in its absolute value. * Value <image> is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length len. Your task is to calculate the optimal sum of the given array a. However, before you do the calculations, you are allowed to produce no more than k consecutive operations of the following form with this array: one operation means taking an arbitrary number from array ai and multiply it by -1. In other words, no more than k times you are allowed to take an arbitrary number ai from the array and replace it with - ai. Each number of the array is allowed to choose an arbitrary number of times. Your task is to calculate the maximum possible optimal sum of the array after at most k operations described above are completed. Input The first line contains two integers n, len (1 ≤ len ≤ n ≤ 105) — the number of elements in the array and the length of the chosen subinterval of the array, correspondingly. The second line contains a sequence consisting of n integers a1, a2, ..., an (|ai| ≤ 109) — the original array. The third line contains a single integer k (0 ≤ k ≤ n) — the maximum allowed number of operations. All numbers in lines are separated by a single space. Output In a single line print the maximum possible optimal sum after no more than k acceptable operations are fulfilled. 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. Examples Input 5 3 0 -2 3 -5 1 2 Output 10 Input 5 2 1 -3 -10 4 1 3 Output 14 Input 3 3 -2 -5 4 1 Output 11 Submitted Solution: ``` import sys nums_in = sys.stdin.readline().split(" ") n, l = list(map(int, nums_in)) arr = sys.stdin.readline().split(" ") arr = list(map(int, arr)) k = int(sys.stdin.readline()) # starting conditions optimal_sum = 0 mod_sum = 0 interval = [] pos = 0 neg = 0 for i in range(n): # for building the interval if len(interval) < l: interval.append(arr[i]) mod_sum += arr[i] # check initial signs if arr[i] >= 0: pos += 1 else: neg += 1 else: # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) # modify the sign counts if arr[i] < 0 and interval[0] >= 0: neg += 1 pos -= 1 elif arr[i] >= 0 and interval[0] < 0: pos += 1 neg -= 1 # remove the earliest element, add the next interval.pop(0) interval.append(arr[i]) # for building the optimal sum # create a temp interval, so we don't modify original temp_interval = sorted(interval) # make the maximum k operations if pos > neg: x = 0 while x <= k and x <= neg: temp_interval[x] = temp_interval[x] * (-1) x += 1 else: x = -1 while abs(x) <= k and abs(x) <= pos: temp_interval[x] = temp_interval[x] * (-1) x -= 1 # store the new mod_sum mod_sum = sum(temp_interval) # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) print(optimal_sum) ```
instruction
0
76,980
12
153,960
No
output
1
76,980
12
153,961
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. And here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array. * Let's consider an arbitrary interval of the array with length len, starting in position i. Value <image>, is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length len, taken in its absolute value. * Value <image> is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length len. Your task is to calculate the optimal sum of the given array a. However, before you do the calculations, you are allowed to produce no more than k consecutive operations of the following form with this array: one operation means taking an arbitrary number from array ai and multiply it by -1. In other words, no more than k times you are allowed to take an arbitrary number ai from the array and replace it with - ai. Each number of the array is allowed to choose an arbitrary number of times. Your task is to calculate the maximum possible optimal sum of the array after at most k operations described above are completed. Input The first line contains two integers n, len (1 ≤ len ≤ n ≤ 105) — the number of elements in the array and the length of the chosen subinterval of the array, correspondingly. The second line contains a sequence consisting of n integers a1, a2, ..., an (|ai| ≤ 109) — the original array. The third line contains a single integer k (0 ≤ k ≤ n) — the maximum allowed number of operations. All numbers in lines are separated by a single space. Output In a single line print the maximum possible optimal sum after no more than k acceptable operations are fulfilled. 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. Examples Input 5 3 0 -2 3 -5 1 2 Output 10 Input 5 2 1 -3 -10 4 1 3 Output 14 Input 3 3 -2 -5 4 1 Output 11 Submitted Solution: ``` import sys nums_in = sys.stdin.readline().split(" ") n, l = list(map(int, nums_in)) arr = sys.stdin.readline().split(" ") arr = list(map(int, arr)) k = int(sys.stdin.readline()) # starting conditions optimal_sum = 0 mod_sum = 0 interval = [] pos = 0 neg = 0 for i in range(n): # for building the interval if len(interval) < 3: interval.append(arr[i]) mod_sum += arr[i] # check initial signs if arr[i] >= 0: pos += 1 else: neg += 1 else: # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) # modify the sign counts if arr[i] < 0 and interval[0] >= 0: neg += 1 pos -= 1 elif arr[i] >= 0 and interval[0] < 0: pos += 1 neg -= 1 # remove the earliest element, add the next interval.pop(0) interval.append(arr[i]) # for building the optimal sum # create a temp interval, so we don't modify original temp_interval = sorted(interval) # make the maximum k operations if pos > neg: x = 0 while x <= k and x <= neg: temp_interval[x] = temp_interval[x] * (-1) x += 1 else: x = -1 while abs(x) <= k and abs(x) <= pos: temp_interval[x] = temp_interval[x] * (-1) x -= 1 # store the new mod_sum mod_sum = sum(temp_interval) # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) print(optimal_sum) ```
instruction
0
76,981
12
153,962
No
output
1
76,981
12
153,963
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. And here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array. * Let's consider an arbitrary interval of the array with length len, starting in position i. Value <image>, is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length len, taken in its absolute value. * Value <image> is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length len. Your task is to calculate the optimal sum of the given array a. However, before you do the calculations, you are allowed to produce no more than k consecutive operations of the following form with this array: one operation means taking an arbitrary number from array ai and multiply it by -1. In other words, no more than k times you are allowed to take an arbitrary number ai from the array and replace it with - ai. Each number of the array is allowed to choose an arbitrary number of times. Your task is to calculate the maximum possible optimal sum of the array after at most k operations described above are completed. Input The first line contains two integers n, len (1 ≤ len ≤ n ≤ 105) — the number of elements in the array and the length of the chosen subinterval of the array, correspondingly. The second line contains a sequence consisting of n integers a1, a2, ..., an (|ai| ≤ 109) — the original array. The third line contains a single integer k (0 ≤ k ≤ n) — the maximum allowed number of operations. All numbers in lines are separated by a single space. Output In a single line print the maximum possible optimal sum after no more than k acceptable operations are fulfilled. 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. Examples Input 5 3 0 -2 3 -5 1 2 Output 10 Input 5 2 1 -3 -10 4 1 3 Output 14 Input 3 3 -2 -5 4 1 Output 11 Submitted Solution: ``` import sys nums_in = sys.stdin.readline().split(" ") n, l = list(map(int, nums_in)) arr = sys.stdin.readline().split(" ") arr = list(map(int, arr)) k = int(sys.stdin.readline()) # starting conditions optimal_sum = 0 mod_sum = 0 interval = [] pos = 0 neg = 0 for i in range(n): # for building the interval if len(interval) < l: interval.append(arr[i]) mod_sum += arr[i] # check initial signs if arr[i] >= 0: pos += 1 else: neg += 1 else: # modify the sign counts if arr[i] < 0 and interval[0] >= 0: neg += 1 pos -= 1 elif arr[i] >= 0 and interval[0] < 0: pos += 1 neg -= 1 # remove the earliest element, add the next interval.pop(0) interval.append(arr[i]) if len(interval) == l: # print("Current Interval:", interval) # print("pos:", pos, "neg:", neg) # for building the optimal sum # create a temp interval, so we don't modify original temp_interval = sorted(interval) # print("Temp Interval:", temp_interval) # make the maximum k operations if pos > neg: x = 0 while x <= k and x < neg: temp_interval[x] = temp_interval[x] * (-1) x += 1 else: x = -1 while abs(x) <= k and abs(x) < pos: temp_interval[x] = temp_interval[x] * (-1) x -= 1 # print("Modified Interval:", temp_interval) # store the new mod_sum mod_sum = sum(temp_interval) # print("New Mod Sum: ", abs(mod_sum)) # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) print(optimal_sum) ```
instruction
0
76,982
12
153,964
No
output
1
76,982
12
153,965
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. And here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array. * Let's consider an arbitrary interval of the array with length len, starting in position i. Value <image>, is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length len, taken in its absolute value. * Value <image> is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length len. Your task is to calculate the optimal sum of the given array a. However, before you do the calculations, you are allowed to produce no more than k consecutive operations of the following form with this array: one operation means taking an arbitrary number from array ai and multiply it by -1. In other words, no more than k times you are allowed to take an arbitrary number ai from the array and replace it with - ai. Each number of the array is allowed to choose an arbitrary number of times. Your task is to calculate the maximum possible optimal sum of the array after at most k operations described above are completed. Input The first line contains two integers n, len (1 ≤ len ≤ n ≤ 105) — the number of elements in the array and the length of the chosen subinterval of the array, correspondingly. The second line contains a sequence consisting of n integers a1, a2, ..., an (|ai| ≤ 109) — the original array. The third line contains a single integer k (0 ≤ k ≤ n) — the maximum allowed number of operations. All numbers in lines are separated by a single space. Output In a single line print the maximum possible optimal sum after no more than k acceptable operations are fulfilled. 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. Examples Input 5 3 0 -2 3 -5 1 2 Output 10 Input 5 2 1 -3 -10 4 1 3 Output 14 Input 3 3 -2 -5 4 1 Output 11 Submitted Solution: ``` import sys nums_in = sys.stdin.readline().split(" ") n, l = list(map(int, nums_in)) arr = sys.stdin.readline().split(" ") arr = list(map(int, arr)) k = int(sys.stdin.readline()) # starting conditions optimal_sum = 0 mod_sum = 0 interval = [] pos = 0 neg = 0 for i in range(n): # for building the interval if len(interval) < l: interval.append(arr[i]) mod_sum += arr[i] # check initial signs if arr[i] >= 0: pos += 1 else: neg += 1 else: # modify the sign counts if arr[i] < 0 and interval[0] >= 0: neg += 1 pos -= 1 elif arr[i] >= 0 and interval[0] < 0: pos += 1 neg -= 1 # remove the earliest element, add the next interval.pop(0) interval.append(arr[i]) # for building the optimal sum # create a temp interval, so we don't modify original temp_interval = sorted(interval) # make the maximum k operations if pos > neg: x = 0 while x < k and x <= neg: temp_interval[x] = temp_interval[x] * (-1) x += 1 else: x = -1 while abs(x) <= k and abs(x) <= pos: temp_interval[x] = temp_interval[x] * (-1) x -= 1 # store the new mod_sum mod_sum = sum(temp_interval) # check if optimal sum if abs(mod_sum) > optimal_sum: optimal_sum = abs(mod_sum) print(optimal_sum) ```
instruction
0
76,983
12
153,966
No
output
1
76,983
12
153,967
Provide tags and a correct Python 3 solution for this coding contest problem. Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: * a1 = p, where p is some integer; * ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression. Sequence s1, s2, ..., sk is a subsequence of sequence b1, b2, ..., bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), that bij = sj. In other words, sequence s can be obtained from b by crossing out some elements. Input The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106). Output Print a single integer — the length of the required longest subsequence. Examples Input 2 3 5 Output 2 Input 4 10 20 10 30 Output 3 Note In the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.
instruction
0
77,000
12
154,000
Tags: brute force, dp Correct Solution: ``` n=int(input()) b=list(map(int,input().split())) dp=[[1]*n for i in range(n)] d={} k=0 for i in range(n): if b[i] not in d: d[b[i]]=k k+=1 b[i]=d[b[i]] for i in range(n): for j in range(i): dp[i][b[j]]=max(dp[j][b[i]]+1,dp[i][b[j]]) ans=0 for l in dp: ans=max(ans,max(l)) print(ans) ```
output
1
77,000
12
154,001