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
Provide tags and a correct Python 3 solution for this coding contest problem. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
instruction
0
30,964
12
61,928
Tags: combinatorics, dp Correct Solution: ``` from copy import deepcopy import itertools from bisect import bisect_left from bisect import bisect_right import math from collections import deque def read(): return int(input()) def readmap(): return map(int, input().split()) def readlist(): return list(map(int, input().split())) MAX = 10000 MOD = 998244353 fac = [0] * MAX finv = [0] * MAX inv = [0] * MAX def COMinit(): fac[0] = 1 fac[1] = 1 finv[0] = 1 finv[1] = 1 inv[1] = 1; for i in range(2, MAX): fac[i] = fac[i - 1] * i % MOD inv[i] = MOD - inv[MOD%i] * (MOD // i) % MOD finv[i] = finv[i - 1] * inv[i] % MOD return None def COM(n, k): if n < k: return 0 if n < 0 or k < 0: return 0 return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD N = read() A = readlist() for i in range(N): A[i] = max(0, A[i]) if A[i] > N - i - 1: A[i] = 0 COMinit() dp = [0] * N for n in range(1, N): dp[n] = dp[n-1] for i in range(n): if i == 0: dp[n] = (dp[n] + COM(n - i - 1, A[i] - 1)) % MOD else: dp[n] = (dp[n] + COM(n - i - 1, A[i] - 1) * (dp[i - 1] + 1)) % MOD print(dp[N - 1]) ```
output
1
30,964
12
61,929
Provide tags and a correct Python 3 solution for this coding contest problem. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
instruction
0
30,965
12
61,930
Tags: combinatorics, dp Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") N = 10001 # array to store inverse of 1 to N factorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N! naturalNumInverse = [None] * (N + 1) # array to store factorial of # first N numbers fact = [None] * (N + 1) # Function to precompute inverse of numbers def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse # of factorials def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to N def factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) time def Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p return ans p=998244353 InverseofNumber(p) InverseofFactorial(p) factorial(p) n=int(input()) b=list(map(int,input().split())) b.reverse() dp=[[0,0] for i in range(n+1)] dp[0][1]=1 for i in range(1,n+1): if (i>1): dp[i][0] = sum(dp[i - 1])%p if b[i-1]<=0: pass else: j=0 while(j<i): l=i-j if l>=(b[i-1]+1): dp[i][1]+=(dp[j][1]*(Binomial(l-1,b[i-1],p)))%p j+=1 print(sum(dp[-1])%p) ```
output
1
30,965
12
61,931
Provide tags and a correct Python 3 solution for this coding contest problem. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
instruction
0
30,966
12
61,932
Tags: combinatorics, dp Correct Solution: ``` n = int(input()) m = 998244353 dp = [1] + [0] * n; for i in map(int, input().split()) : v = dp[:] if(0 < i < n) : v[i] = (v[i] + v[0]) % m for j in range(n) : v[j] = (v[j] + dp[j + 1]) % m dp = v print((dp[0] - 1) % m) ```
output
1
30,966
12
61,933
Provide tags and a correct Python 3 solution for this coding contest problem. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
instruction
0
30,967
12
61,934
Tags: combinatorics, dp Correct Solution: ``` n = int(input()) m = 998244353 dp = [1] + [0] * n; for i in map(int, input().split()) : v = dp[:] if(0 < i < n) : v[i] = (v[i] + v[0]) % m for j in range(n) : v[j] = (v[j] + dp[j + 1]) % m dp = v print((dp[0] - 1) % m) #print the result ```
output
1
30,967
12
61,935
Provide tags and a correct Python 3 solution for this coding contest problem. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
instruction
0
30,968
12
61,936
Tags: combinatorics, dp Correct Solution: ``` mod=998244353 def ncr(n,r): if n<r or n==0: return 0 if r==0: return 1 return (fac[n]*invfac[r]*invfac[n-r])%mod n=int(input()) a=list(map(int,input().split())) fac = [1] * (n + 1) invfac = [1] * (n + 1) for i in range(1, n + 1): fac[i] = (i * fac[i - 1]) % mod invfac[i] = pow(fac[i], mod - 2, mod) dp=[0]*(n+1) for i in range(n-1,-1,-1): if a[i]>0: for j in range(min(n,i+a[i]+1),n): dp[i]=(dp[i]+dp[j]*ncr(j-i-1,a[i]))%mod dp[i]=(dp[i]+ncr(n-i-1,a[i]))%mod print(sum(dp)%mod) ```
output
1
30,968
12
61,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. 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 def getc(s): c = 0 for i in range(len(s) - 7, -1, -1): st = 'abacaba' if s[i:i + 7] == st: c += 1 return c max_n = 2 * 10 ** 5 mod = 998244353 fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1) fact[0] = 1 for i in range(max_n): fact[i + 1] = fact[i] * (i + 1) % mod inv_fact[-1] = pow(fact[-1], mod - 2, mod) for i in reversed(range(max_n)): inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod def nCr_mod(n, r): res = 1 while n or r: a, b = n % mod, r % mod if a < b: return 0 res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod n //= mod r //= mod return res for _ in range(int(input()) if not True else 1): #l, r, m = map(int, input().split()) n = int(input()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) a = list(map(int, input().split())) #b = list(map(int, input().split())) dp = [0]*n for i in range(n-1, -1, -1): if a[i] < 1:continue if n-i-1 >= a[i]: dp[i] = nCr_mod(n-i-1, a[i]) for j in range(i+a[i]+1, n-1): # 2 3 1 1 2 1 1 spaces = j-i-1 comb = nCr_mod(spaces, a[i]) dp[i] += comb * dp[j] print(sum(dp) % mod) ```
instruction
0
30,969
12
61,938
Yes
output
1
30,969
12
61,939
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` n = int(input()) m = 998244353 dp = [1] + [0] * n; for j in map(int, input().split()) : v = dp[:] if(0 < j < n) : v[j] = (v[j] + v[0]) % m for k in range(n) : v[k] = (v[k] + dp[k + 1]) % m dp = v print((dp[0] - 1) % m) ```
instruction
0
30,970
12
61,940
Yes
output
1
30,970
12
61,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` #!/usr/bin/python3 MOD = 998244353 def solve(N, A): dp = [[0] * N for _ in range(N + 1)] dp[0][0] = 1 for i in range(N): for j in range(N): c = dp[i][j] dp[i + 1][j] += c dp[i + 1][j] %= MOD if j == 0: if A[i] > 0 and A[i] < N: dp[i + 1][A[i]] += c dp[i + 1][A[i]] %= MOD else: dp[i + 1][j - 1] += c dp[i + 1][j - 1] %= MOD return (dp[N][0] + MOD - 1) % MOD def main(): N = int(input()) A = [int(e) for e in input().split(' ')] assert len(A) == N print(solve(N, A)) if __name__ == '__main__': main() ```
instruction
0
30,971
12
61,942
Yes
output
1
30,971
12
61,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` from random import randint def factMod(n, mod): res = 1 for i in range(2, n+1): res = (res * i) % mod return res def powMod(n, p, mod): res = 1 while p > 0: if p % 2 == 1: res = (res * n) % mod p //= 2 n = (n * n) % mod return res def invMod(n, mod): return powMod(n, mod - 2, mod) #t = 6 #print(invMod(t, 97)) #print( (invMod(t, 97) * t) % 97 ) #exit(0) def CnkMod(n, k, mod): return ( factMod(n, mod) * invMod(factMod(k, mod) * factMod(n-k, mod), mod) ) % mod def computeCnksMod(N, mod): res = [[0] * (N+1) for i in range(N+1)] res[0][0] = 1 for n in range(1, N+1): res[n][0] = res[n-1][0] for k in range(1, n+1): res[n][k] = (res[n-1][k] + res[n-1][k-1]) % mod return res magic = 998244353 n = int(input()) + 1 aa = [1] + [int(s)+1 for s in input().split(' ')] #aa = [1] + [randint(0, 999) for i in range(1000)] #n = len(aa) cnks = computeCnksMod(n, magic) #print('aa:', aa) d = [0] * (n + 1) d[n] = 1 for i in reversed(list(range(n))): if i != 0 and aa[i] < 2: continue cur = 0 tosel = aa[i] - 1 for j in range(i + tosel + 1, n + 1): avail = j - i - 1 #cur = (cur + CnkMod(avail, tosel, magic) * d[j]) % magic cur = (cur + cnks[avail][tosel] * d[j]) % magic d[i] = cur #print(d) print(d[0] - 1) ```
instruction
0
30,972
12
61,944
Yes
output
1
30,972
12
61,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` def modInverse(a,mod): return pow(a,mod-2,mod) def solve2(arr,dp2,mod): n = len(arr) dp = [0]*(n+1) dp[-1] = 1 for i in range(n-1,-1,-1): if arr[i] > 0: for j in range(i+arr[i],n): #print(i,j) dp[i] += dp2[j-i-1][arr[i]-1]*max(1,dp[j+1]) dp[i] %= mod for j in range(i+1,n): dp[i] += dp[j] dp[i] %= mod #print(dp) print(dp[0]) def main(): n = int(input()) arr = list(map(int,input().split())) mod = 998244353 dp2 = [[0 for i in range(n+1)] for j in range(n+1)] for i in range(n+1): dp2[i][0] = 1 for j in range(1,i+1): dp2[i][j] = dp2[i][j-1]*(i-j+1) dp2[i][j] %= mod dp2[i][j] *= modInverse(j,mod) dp2[i][j] %= mod solve2(arr,dp2,mod) main() ```
instruction
0
30,973
12
61,946
No
output
1
30,973
12
61,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` MOD = 998244353 n = int(input()) d = [0] * n a = list(map(int, input().split())) for i in range(n - 2, -1, -1): if (a[i] <= 0): continue; cur_cnk = 1 cur_k = cur_n = a[i] for j in range(i + a[i] + 1, n): d[i] = (d[i] + d[j] * cur_cnk % MOD) % MOD cur_cnk *= (cur_n + 1) cur_cnk //= (cur_n + 1 - cur_k) cur_n += 1 d[i] = (d[i] + cur_cnk) % MOD ans = 0 for i in range(n): ans = (ans + d[i]) % MOD print(ans) ```
instruction
0
30,974
12
61,948
No
output
1
30,974
12
61,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted 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**33, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------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()) s=Combination(mod1) l=list(map(int,input().split())) dp=[0 for i in range(n+1)] for i in range(n-2,-1,-1): for j in range(n-1,i,-1): ch=j-i-1 d=l[i]-1 dp[i]+=(dp[j+1]+1)*s.ncr(ch,d) dp[i]%=mod1 print(sum(dp)%mod1) ```
instruction
0
30,975
12
61,950
No
output
1
30,975
12
61,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≀ n ≀ 10^3) β€” the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≀ a_i ≀ 10^9) β€” the sequence itself. Output In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences β€” [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences β€” [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) mod = 998244353 dp = [0] * (n + 2) C = [[0] * (n + 2) for i in range(n + 2)] for i in range(0, n + 1): C[i][0] = 1 for j in range(1, i + 1): C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod ans = 0 dp[n] = 1 for iter in range(0, n): i = n - iter - 1 for j in range(i + arr[i] + 1, n + 1): dp[i] += dp[j] * C[j - i - 1][arr[i]] dp[i] %= mod ans += dp[i] print(ans % mod) ```
instruction
0
30,976
12
61,952
No
output
1
30,976
12
61,953
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 elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≀ i, j ≀ n; i β‰  j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1). Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < ... < a_n should hold (where n is the resulting size of the array). Calculate the minimum number of actions required to make the array strictly ascending. Input The first line contains one integer T (1 ≀ T ≀ 10000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of elements in the initial array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that: * the number of test cases having n β‰₯ 5 is not greater than 5000; * the number of test cases having n β‰₯ 8 is not greater than 500; * the number of test cases having n β‰₯ 10 is not greater than 100; * the number of test cases having n β‰₯ 11 is not greater than 50; * the number of test cases having n β‰₯ 12 is not greater than 25; * the number of test cases having n β‰₯ 13 is not greater than 10; * the number of test cases having n β‰₯ 14 is not greater than 3; * the number of test cases having n β‰₯ 15 is not greater than 1. Output For each test case, print the answer as follows: In the first line, print k β€” the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them. Example Input 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 Note In the first test case, the sequence of operations changes a as follows: [2, 1, 3, 5, 1, 2, 4, 5] β†’ [2, 1, 3, 5, 1, 4, 7] β†’ [1, 3, 5, 1, 6, 7] β†’ [2, 3, 5, 6, 7]. Submitted Solution: ``` T = int(input()) X = [] for _ in range(T): N = int(input()) A = [int(a) for a in input().split()] X.append([N, A]) print("X =", X) ```
instruction
0
31,135
12
62,270
No
output
1
31,135
12
62,271
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 elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≀ i, j ≀ n; i β‰  j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1). Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < ... < a_n should hold (where n is the resulting size of the array). Calculate the minimum number of actions required to make the array strictly ascending. Input The first line contains one integer T (1 ≀ T ≀ 10000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of elements in the initial array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that: * the number of test cases having n β‰₯ 5 is not greater than 5000; * the number of test cases having n β‰₯ 8 is not greater than 500; * the number of test cases having n β‰₯ 10 is not greater than 100; * the number of test cases having n β‰₯ 11 is not greater than 50; * the number of test cases having n β‰₯ 12 is not greater than 25; * the number of test cases having n β‰₯ 13 is not greater than 10; * the number of test cases having n β‰₯ 14 is not greater than 3; * the number of test cases having n β‰₯ 15 is not greater than 1. Output For each test case, print the answer as follows: In the first line, print k β€” the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them. Example Input 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 Note In the first test case, the sequence of operations changes a as follows: [2, 1, 3, 5, 1, 2, 4, 5] β†’ [2, 1, 3, 5, 1, 4, 7] β†’ [1, 3, 5, 1, 6, 7] β†’ [2, 3, 5, 6, 7]. Submitted Solution: ``` a=input() print(3) print('6 8') print('1 6') print('4 1') print('7') print('1 15') print('1 13') print('1 11') print('1 9') print('1 7') print('1 5') print('1 3') print('1') print('2 1') print('0') ```
instruction
0
31,136
12
62,272
No
output
1
31,136
12
62,273
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 elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≀ i, j ≀ n; i β‰  j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1). Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < ... < a_n should hold (where n is the resulting size of the array). Calculate the minimum number of actions required to make the array strictly ascending. Input The first line contains one integer T (1 ≀ T ≀ 10000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of elements in the initial array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that: * the number of test cases having n β‰₯ 5 is not greater than 5000; * the number of test cases having n β‰₯ 8 is not greater than 500; * the number of test cases having n β‰₯ 10 is not greater than 100; * the number of test cases having n β‰₯ 11 is not greater than 50; * the number of test cases having n β‰₯ 12 is not greater than 25; * the number of test cases having n β‰₯ 13 is not greater than 10; * the number of test cases having n β‰₯ 14 is not greater than 3; * the number of test cases having n β‰₯ 15 is not greater than 1. Output For each test case, print the answer as follows: In the first line, print k β€” the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them. Example Input 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 Note In the first test case, the sequence of operations changes a as follows: [2, 1, 3, 5, 1, 2, 4, 5] β†’ [2, 1, 3, 5, 1, 4, 7] β†’ [1, 3, 5, 1, 6, 7] β†’ [2, 3, 5, 6, 7]. Submitted Solution: ``` def check(a, n): for i in range(1, n): if a[i] <= a[i - 1]: return False return True def solve(): t = int(input()) q = [] for x in range(t): n = int(input()) a = list(map(int, input().split())) p = [] y = 0 while not check(a, len(a)) and len(a) > y: j = len(a) - y - 1 m = 0 for k in range(1, j - 1): if a[k] == a[0]: m = k break if a[m] == a[j]: z = m m = j j = z a[j] += a[m] a.__delitem__(m) y += 1 p.append((m + 1, j + 1)) q.append([y, p]) return q b = solve() for y, p in b: print(y) for i, j in p: print(i, j) ```
instruction
0
31,137
12
62,274
No
output
1
31,137
12
62,275
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 elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≀ i, j ≀ n; i β‰  j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n also decreases by 1). Your goal is to make the array a strictly ascending. That is, the condition a_1 < a_2 < ... < a_n should hold (where n is the resulting size of the array). Calculate the minimum number of actions required to make the array strictly ascending. Input The first line contains one integer T (1 ≀ T ≀ 10000) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 15) β€” the number of elements in the initial array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that: * the number of test cases having n β‰₯ 5 is not greater than 5000; * the number of test cases having n β‰₯ 8 is not greater than 500; * the number of test cases having n β‰₯ 10 is not greater than 100; * the number of test cases having n β‰₯ 11 is not greater than 50; * the number of test cases having n β‰₯ 12 is not greater than 25; * the number of test cases having n β‰₯ 13 is not greater than 10; * the number of test cases having n β‰₯ 14 is not greater than 3; * the number of test cases having n β‰₯ 15 is not greater than 1. Output For each test case, print the answer as follows: In the first line, print k β€” the minimum number of operations you have to perform. Then print k lines, each containing two indices i and j for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them. Example Input 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Output 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 Note In the first test case, the sequence of operations changes a as follows: [2, 1, 3, 5, 1, 2, 4, 5] β†’ [2, 1, 3, 5, 1, 4, 7] β†’ [1, 3, 5, 1, 6, 7] β†’ [2, 3, 5, 6, 7]. Submitted Solution: ``` for q in range(int(input())): print('Yes') ```
instruction
0
31,138
12
62,276
No
output
1
31,138
12
62,277
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,171
12
62,342
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input().rstrip() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' mod=1000000007 # mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') file = 1 def solve(): n = ii() a = li() d = [0]*(n+1) K = 0 a.insert(0,0) def answer(): ans = (d[1] + K) if ans %2 != 0: ans +=1 print(int(ans//2)) # As b increasing and c decreasing....... # ans = max(b[n],c[1]) # a[i] > a[i-1] then b[i] = b[i-1] + (a[i] - a[i-1]) and c[i] = c[i-1] # a[i] < a[i-1] then b[i] = b[i-1] and c[i] = c[i-1] + (a[i] - a[i-1]) # Let c[1] = x so, b[1] = (a[1] - x) # b[2] = b[1] + max(0,a[2] - a[1]) as a[i] > a[i-1] only b[i] = b[i-1] + (a[i] - a[i-1]) # b[3] = b[2] + max(0,a[3] - a[2]) # b[n] = b[n-1] + max(0,a[n] - a[n-1]) # so, b[n] = b[1] + max(0,a[i] - a[i-1]) where 2<=i<=n # so, b[n] = (a[1] - x) + K, where K = max(0,a[i] -a[i-1]) where 2<=i<=n # so, ans = max(x,a[1] - x + K) # for minimize the answer we assume that x = a[1] - x + K # x = (a[1] + K) / 2 # ans = (a[1] + K) / 2 # d array = [0,a[1],max(0,a[2]-a[1]),max(0,a[3]-a[2])..........] for i in range(1,n+1): d[i] = a[i] - a[i-1] if i > 1: K += max(0,d[i]) answer() # query for _ in range(ii()): l,r,x = mi() # d[l] = a[l] - a[l-1] # temp = d[l] # so, a[l] will be affected due to change of a[l] to a[l] + x # now,d[l] = (a[l] + x) - a[l-1] = temp + x # the value inside l and r don't affected # d[l+1] = a[l+1] - a[l] # here both a[l] and a[l+1] will affected,so d[l+1] unchanged. # d[r+1] = a[r+1] - a[r] = tmp # here only a[r] changed but a[r+1] not changed so d[r+1] will affected. # d[r+1] = a[r+1] - (a[r] + x) # d[r+1] = tmp - x if l > 1: K -= max(0,d[l]) d[l] += x if l > 1: K += max(0,d[l]) if r < n: K -= max(0,d[r+1]) d[r+1] -= x K += max(0,d[r+1]) answer() if __name__ =="__main__": if(file): if path.exists('input.txt'): sys.stdin=open('input.txt', 'r') sys.stdout=open('output.txt','w') else: input=sys.stdin.readline solve() ```
output
1
31,171
12
62,343
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,172
12
62,344
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys _ord, inp, num, neg, _Index = lambda x: x, [], 0, False, 0 i, s = 0, sys.stdin.buffer.read() try: while True: if s[i] >= b"0"[0]:num = 10 * num + _ord(s[i]) - 48 elif s[i] == b"-"[0]:neg = True elif s[i] != b"\r"[0]: inp.append(-num if neg else num) num, neg = 0, False i += 1 except IndexError: pass if s and s[-1] >= b"0"[0]: inp.append(-num if neg else num) def inin(size=None): global _Index if size==None: ni=_Index;_Index+=1 return inp[ni] else: ni=_Index;_Index+=size return inp[ni:ni+size] _T_=1 #inin() for _t_ in range(_T_): n=inin() a=inin(n) d=[0 for i in range(n-1)] k=0 for i in range(1,n): d[i-1]+=a[i]-a[i-1] k+=max(0,a[i]-a[i-1]) x=(a[0]+k+1)//2 print(x) q=inin() for _ in range(q): l,r,c=inin(3) l-=1; r-=1 if l==0: a[0]+=c else: if d[l-1]>=0: k-=d[l-1] d[l-1]+=c if d[l-1]>=0: k+=d[l-1] if r==n-1: pass else: if d[r]>=0: k-=d[r] d[r]-=c if d[r]>=0: k+=d[r] x=(a[0]+k+1)//2 print(x) ```
output
1
31,172
12
62,345
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,173
12
62,346
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys input = sys.stdin.buffer.readline class BIT: def __init__(self, n): self.size = n self.bit = [0] * (n + 1) def build(self, array): for i in range(1, self.size + 1): if i - 1 + (i & -i) >= self.size: self.bit[i] = array[i - 1] else: self.bit[i] = array[i - 1] - array[i - 1 + (i & -i)] def _add(self, i, val): while i > 0: self.bit[i] += val i -= i & -i def get_val(self, i): i = i + 1 s = 0 while i <= self.size: s += self.bit[i] i += i & -i return s def add(self, l, r, val): self._add(r, val) self._add(l, -val) def get_diff(self, i, j): s = 0 i = i + 1 while i <= self.size: s += self.bit[i] i += i & -i j = j + 1 while j <= self.size: s -= self.bit[j] j += j & -j return s n = int(input()) a = list(map(int, input().split())) q = int(input()) queries = [list(map(int, input().split())) for i in range(q)] diff = [a[i + 1] - a[i] for i in range(n - 1)] diff_sum = 0 for d in diff: if d > 0: diff_sum += d bit = BIT(n) bit.build(a) val0 = bit.get_val(0) ans = [] ans.append((diff_sum + val0 + 1) // 2) for l, r, val in queries: l -= 1 bit.add(l, r, val) d1, d2 = -1, -1 d1_new, d2_new = -1, -1 if l - 1 >= 0: d1 = diff[l - 1] d1_new = bit.get_diff(l, l - 1) diff[l - 1] = d1_new if r - 1 < n - 1: d2 = diff[r - 1] d2_new = bit.get_diff(r, r - 1) diff[r - 1] = d2_new diff_sum -= max(d1, 0) + max(d2, 0) diff_sum += max(d1_new, 0) + max(d2_new, 0) if l == 0: val0 += val ans.append((diff_sum + val0 + 1) // 2) print("\n".join(map(str, ans))) ```
output
1
31,173
12
62,347
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,174
12
62,348
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys sys.setrecursionlimit(10**5) 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 = II() aa = LI() dd = [0]*n s = 0 for i in range(n-1): dd[i+1] = aa[i+1]-aa[i] for d in dd: if d > 0: s += d # print(dd) # print(sp,sn) b0 = (aa[0]-s)//2 print(max(b0+s, aa[0]-b0)) def add(i, a, s): if i == 0: aa[0] += a return s if dd[i] > 0: s -= dd[i] dd[i] += a if dd[i] > 0: s += dd[i] return s for _ in range(II()): l, r, x = MI() l -= 1 s = add(l, x, s) if r < n: s = add(r, -x, s) b0 = (aa[0]-s)//2 print(max(b0+s, aa[0]-b0)) ```
output
1
31,174
12
62,349
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,175
12
62,350
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys; Case=1 #Case=int(sys.stdin.buffer.readline()) def main(): #Code goes here n=inin() a=inar() d=[0 for i in range(n-1)] k=0 for i in range(1,n): d[i-1]+=a[i]-a[i-1] k+=max(0,a[i]-a[i-1]) x=(a[0]+k+1)//2 pr(x) q=inin() for _ in range(q): l,r,c=inar() l-=1; r-=1 if l==0: a[0]+=c else: if d[l-1]>=0: k-=d[l-1] d[l-1]+=c if d[l-1]>=0: k+=d[l-1] if r==n-1: pass else: if d[r]>=0: k-=d[r] d[r]-=c if d[r]>=0: k+=d[r] x=(a[0]+k+1)//2 pr(x) #Template goes here import sys inp=sys.stdin.buffer.readline inar=lambda: list(map(int,inp().split())) inin=lambda: int(inp()) inst=lambda: inp().decode().strip() wrt=sys.stdout.write pr=lambda *args,end='\n': wrt(' '.join([str(x) for x in args])+end) enum=enumerate inf=float('inf') for __Case__ in range(Case): main() ```
output
1
31,175
12
62,351
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,176
12
62,352
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys import atexit import os class Fastio: def __init__(self): self.ibuf = bytes() self.obuf = bytearray() self.pil = 0 self.pir = 0 self.buf = bytearray(21) self.buf[20] = 10 def load(self): self.ibuf = self.ibuf[self.pil:] self.ibuf += os.read(0, max(os.fstat(0).st_size, 131072)) self.pil = 0 self.pir = len(self.ibuf) def flush(self): os.write(1, self.obuf) self.obuf = bytearray() def fastin(self): if self.pir - self.pil < 32: self.load() minus = 0 x = 0 while self.ibuf[self.pil] < 45: self.pil += 1 if self.ibuf[self.pil] == 45: minus = 1 self.pil += 1 while self.ibuf[self.pil] >= 48: x = x * 10 + (self.ibuf[self.pil] & 15) self.pil += 1 if minus: x = -x return x def fastoutln(self, x): i = 19 if x == 0: self.buf[i] = 48 i -= 1 else: if x < 0: self.obuf.append(45) x = -x while x != 0: x, r = divmod(x, 10) self.buf[i] = 48 + r i -= 1 self.obuf.extend(self.buf[i+1:21]) if len(self.obuf) > 131072: self.flush() fastio = Fastio() rd = fastio.fastin wtn = fastio.fastoutln atexit.register(fastio.flush) N = rd() a = [0] * N for i in range(N): a[i] = rd() for i in range(N-1, 0, -1): a[i] -= a[i-1] p = 0 for i in range(1, N): p += max(0, a[i]) wtn((a[0] + p + 1) // 2) Q = rd() for _ in range(Q): l, r, x = rd(), rd(), rd() l -= 1 if l != 0: p -= max(a[l], 0) a[l] += x if l != 0: p += max(a[l], 0) if r != N: p -= max(a[r], 0) a[r] -= x p += max(a[r], 0) wtn((a[0] + p + 1) // 2) ```
output
1
31,176
12
62,353
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,177
12
62,354
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` 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().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n = N() a = RLL() p = [0] for i in range(1,n): p.append(a[i]-a[i-1]) now = sum(i for i in p if i>0) s = a[0] print((s+now+1)>>1) q = N() for _ in range(q): l,r,x = RL() if l==1: s+=x else: tmp = p[l-1] p[l-1]+=x if tmp<0: delta = max(0,p[l-1]) else: delta = max(-tmp,x) now+=delta if r<n: tmp = p[r] p[r]-=x if tmp<0: delta = max(0,p[r]) else: delta = max(-tmp,-x) now+=delta # p[0] = s # print(p,now) print((s+now+1)>>1) ```
output
1
31,177
12
62,355
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≀ i≀ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≀ n, b_iβ‰₯ b_{i-1} must hold * c is non-increasing, which means that for every 1<i≀ n, c_i≀ c_{i-1} must hold You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c. Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, …, a_r. You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change. Input The first line contains an integer n (1≀ n≀ 10^5). The secound line contains n integers a_1,a_2,…,a_n (1≀ i≀ n, -10^9≀ a_i≀ 10^9). The third line contains an integer q (1≀ q≀ 10^5). Each of the next q lines contains three integers l,r,x (1≀ l≀ r≀ n,-10^9≀ x≀ 10^9), desribing the next change. Output Print q+1 lines. On the i-th (1 ≀ i ≀ q+1) line, print the answer to the problem for the sequence after i-1 changes. Examples Input 4 2 -1 7 3 2 2 4 -3 3 4 2 Output 5 5 6 Input 6 -9 -10 -9 -6 -5 4 3 2 6 -9 1 2 -10 4 6 -3 Output 3 3 3 1 Input 1 0 2 1 1 -1 1 1 -1 Output 0 0 -1 Note In the first test: * The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice. * After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice. * After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice.
instruction
0
31,178
12
62,356
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import sys n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) d = [] b = 0 c = 0 F = a[0] L = a[-1] for i in range (1, n): x = a[i] - a[i-1] if x >= 0: b = b + x else: c = c - x d.append(x) Q = int(sys.stdin.readline().strip()) for q in range (0, Q + 1): if q > 0: l, r, x = list(map(int, sys.stdin.readline().strip().split())) else: l, r, x = 1, 1, 0 if x != 0 and l > 1: if x >= 0 and d[l-2] >= 0: b = b + x elif x >= 0 and d[l-2] < 0: b = b + x - min(-d[l-2], x) c = c - min(-d[l-2], x) elif x < 0 and d[l-2] >= 0: c = c - min(d[l-2], -x) - x b = b - min(d[l-2], -x) elif x < 0 and d[l-2] < 0: c = c - x d[l-2] = d[l-2] + x elif x != 0 and l == 1: F = F + x if x != 0 and r < n: if x <= 0 and d[r-1] >= 0: b = b - x elif x <= 0 and d[r-1] < 0: b = b - x - min(-x, -d[r-1]) c = c - min(-x, -d[r-1]) elif x > 0 and d[r-1] >= 0: c = c - min(x, d[r-1]) + x b = b - min(x, d[r-1]) elif x > 0 and d[r-1] < 0: c = c + x d[r-1] = d[r-1] - x elif x != 0 and r == n: L = L + x print((L + F + b + c + 3) // 4) ```
output
1
31,178
12
62,357
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,212
12
62,424
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` #### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to_key from collections import deque, Counter from heapq import heappush, heappop from math import log, ceil ###################### #### STANDARD I/O #### ###################### import sys import os 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") 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) def print(*args, **kwargs): 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() def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def ii(): return int(inp()) def si(): return str(inp()) def li(lag = 0): l = list(map(int, inp().split())) if lag != 0: for i in range(len(l)): l[i] += lag return l def mi(lag = 0): matrix = list() for i in range(n): matrix.append(li(lag)) return matrix def lsi(): #string list return list(map(str, inp().split())) def print_list(lista, space = " "): print(space.join(map(str, lista))) ###################### ### BISECT METHODS ### ###################### def bisect_left(a, x): """i tale che a[i] >= x e a[i-1] < x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] < x: left = mid+1 else: right = mid return left def bisect_right(a, x): """i tale che a[i] > x e a[i-1] <= x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] > x: right = mid else: left = mid+1 return left def bisect_elements(a, x): """elementi pari a x nell'Γ‘rray sortato""" return bisect_right(a, x) - bisect_left(a, x) ###################### ### MOD OPERATION #### ###################### MOD = 10**9 + 7 maxN = 5 FACT = [0] * maxN INV_FACT = [0] * maxN def add(x, y): return (x+y) % MOD def multiply(x, y): return (x*y) % MOD def power(x, y): if y == 0: return 1 elif y % 2: return multiply(x, power(x, y-1)) else: a = power(x, y//2) return multiply(a, a) def inverse(x): return power(x, MOD-2) def divide(x, y): return multiply(x, inverse(y)) def allFactorials(): FACT[0] = 1 for i in range(1, maxN): FACT[i] = multiply(i, FACT[i-1]) def inverseFactorials(): n = len(INV_FACT) INV_FACT[n-1] = inverse(FACT[n-1]) for i in range(n-2, -1, -1): INV_FACT[i] = multiply(INV_FACT[i+1], i+1) def coeffBinom(n, k): if n < k: return 0 return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n-k])) ###################### #### GRAPH ALGOS ##### ###################### # ZERO BASED GRAPH def create_graph(n, m, undirected = 1, unweighted = 1): graph = [[] for i in range(n)] if unweighted: for i in range(m): [x, y] = li(lag = -1) graph[x].append(y) if undirected: graph[y].append(x) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 graph[x].append([y,w]) if undirected: graph[y].append([x,w]) return graph def create_tree(n, unweighted = 1): children = [[] for i in range(n)] if unweighted: for i in range(n-1): [x, y] = li(lag = -1) children[x].append(y) children[y].append(x) else: for i in range(n-1): [x, y, w] = li(lag = -1) w += 1 children[x].append([y, w]) children[y].append([x, w]) return children def dist(tree, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in tree[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza def diameter(tree): _, foglia, _ = dist(tree, n, 0) diam, _, _ = dist(tree, n, foglia) return diam def dfs(graph, n, A): v = [-1] * n s = [[A, 0]] v[A] = 0 while s: el, dis = s.pop() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def bfs(graph, n, A): v = [-1] * n s = deque() s.append([A, 0]) v[A] = 0 while s: el, dis = s.popleft() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges #FROM A GIVEN ROOT, RECOVER THE STRUCTURE def parents_children_root_unrooted_tree(tree, n, root = 0): q = deque() visited = [0] * n parent = [-1] * n children = [[] for i in range(n)] q.append(root) while q: all_done = 1 visited[q[0]] = 1 for child in tree[q[0]]: if not visited[child]: all_done = 0 q.appendleft(child) if all_done: for child in tree[q[0]]: if parent[child] == -1: parent[q[0]] = child children[child].append(q[0]) q.popleft() return parent, children # CALCULATING LONGEST PATH FOR ALL THE NODES def all_longest_path_passing_from_node(parent, children, n): q = deque() visited = [len(children[i]) for i in range(n)] downwards = [[0,0] for i in range(n)] upward = [1] * n longest_path = [1] * n for i in range(n): if not visited[i]: q.append(i) downwards[i] = [1,0] while q: node = q.popleft() if parent[node] != -1: visited[parent[node]] -= 1 if not visited[parent[node]]: q.append(parent[node]) else: root = node for child in children[node]: downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2] s = [node] while s: node = s.pop() if parent[node] != -1: if downwards[parent[node]][0] == downwards[node][0] + 1: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1]) else: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0]) longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1 for child in children[node]: s.append(child) return longest_path ### TBD SUCCESSOR GRAPH 7.5 ### TBD TREE QUERIES 10.2 da 2 a 4 ### TBD ADVANCED TREE 10.3 ### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES) ###################### ## END OF LIBRARIES ## ###################### from copy import deepcopy def subandremove(d, el): d[el] -= 1 if d[el] == 0: d.pop(el) def f(a, n): for i in range(n-1): cc = {} for el in a: cc[el] = cc.get(el, 0) + 1 x = a[i] + a[-1] kkk = 2 subandremove(cc, a[i]) subandremove(cc, a[n-1]) x = a[-1] pu = n-1 while kkk != n: while a[pu] not in cc: pu -= 1 el = x - a[pu] if el in cc and el == a[pu] and cc[el] >= 2: subandremove(cc, a[pu]) subandremove(cc, el) kkk = kkk+2 x = a[pu] elif el in cc and el != a[pu]: subandremove(cc, a[pu]) subandremove(cc, el) kkk = kkk+2 x = a[pu] else: break if kkk == n: return a[i] + a[n-1] return None def g(a, n, x): cc = {} for el in a: cc[el] = cc.get(el, 0) + 1 coppie = [a[n-1]] coppie.append(x - a[n-1]) kkk = 2 subandremove(cc, a[n-1]) subandremove(cc, x - a[n-1]) x = a[-1] pu = n-1 while kkk != n: while a[pu] not in cc: pu -= 1 el = x - a[pu] if el in cc and el == a[pu] and cc[el] >= 2: subandremove(cc, a[pu]) subandremove(cc, el) coppie.append(a[pu]) coppie.append(el) kkk = kkk+2 x = a[pu] elif el in cc and el != a[pu]: subandremove(cc, a[pu]) subandremove(cc, el) coppie.append(a[pu]) coppie.append(el) kkk = kkk+2 x = a[pu] else: break return coppie for test in range(ii()): n = 2*ii() a = sorted(li()) b = f(a, n) if b == None: print("NO") else: print("YES") print(b) coppie = g(a, n, b) for i in range(n//2): print_list([coppie[2*i], coppie[2*i+1]]) ```
output
1
31,212
12
62,425
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,213
12
62,426
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` ############################## import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') def inp(): return sys.stdin.readline().rstrip() def mpint(): return map(int, inp().split(' ')) def itg(): return int(inp()) # ############################## import # 2020/9/10 class SortedList: def __init__(self, values=None, _load=200): """Initialize sorted list instance.""" if values is None: values = [] self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos], _list_lens[pos], _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __bool__(self): """Return the size of the sorted list.""" return self._len != 0 def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # ############################## main def solve(): n = itg() arr = sorted(mpint()) mx = arr.pop() for num in arr: sl = SortedList(arr) sl.discard(num) ans = [(num + mx,), (mx, num)] x = mx for _ in range(n - 1): a = sl.pop() b = x - a if b not in sl: break sl.discard(b) ans.append((a, b)) x = a else: print("YES") for tp in ans: print(*tp) return print("NO") def main(): # solve() # print(solve()) for _ in range(itg()): # print(solve()) solve() # print("yes" if solve() else "no") # print("YES" if solve() else "NO") DEBUG = 0 URL = 'https://codeforces.com/contest/1474/problem/C' if __name__ == '__main__': # 0: normal, 1: runner, 2: interactive, 3: debug if DEBUG == 1: import requests from ACgenerator.Y_Test_Case_Runner import TestCaseRunner runner = TestCaseRunner(main, URL) inp = runner.input_stream print = runner.output_stream runner.checking() else: if DEBUG != 3: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) if DEBUG: _print = print def print(*args, **kwargs): _print(*args, **kwargs) sys.stdout.flush() main() # Please check! ```
output
1
31,213
12
62,427
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,214
12
62,428
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` from collections import Counter for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) if n==1: print('YES') print(l[0]+l[1]) print(l[0],l[1]) continue l1=[] l.sort(reverse=True) f=-1 b=l[0] for i in range(2*n - 1, 0, -1): #print(l1) if len(l1)==n-1: break else: l1.clear() a = l[0] + l[i] f=l[i] #print(l[i],f) d = Counter(l) d[l[i]]-=1 d[b]-=1 #print(d,l[i]) j=1 while j<len(l): s=l[j] #print(d,l[i],'ghg',s,b,l1) if (d[s]>=1 and d[b - s] >= 1): d[s]-=1 if d[b-s]>=1: d[b - s] -= 1 else: b=l[0] break l1.append([s, b - s]) j+=1 b=max(s,b-s) #print(b) elif(d[s]<=0): j+=1 continue else: b=l[0] break if(len(l1)==n-1): print('YES') print(l[0]+f) print(l[0],f) for p in l1: print(*p) else: print('NO') ```
output
1
31,214
12
62,429
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,215
12
62,430
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` from collections import * from sys import * input = stdin.readline for _ in range(int(input())): n = int(input()) l = sorted(map(int,input().split())) d = Counter(l) d[l[-1]]-=1 ans = [] s1 = 0 for i in range(2*n-1): last = l[-1] curr = d.copy() curr[l[i]]-=1 ans = [f"{l[-1]} {l[i]}"] s1 = l[i]+last for j in range(2*n-1,-1,-1): if curr[l[j]]>0: val = last-l[j] curr[l[j]]-=1 if curr[val]>0: ans.append(f"{l[j]} {val}") last = l[j] curr[val]-=1 else: break if len(ans)==n: break else: print("NO") if len(ans)==n: print('YES') print(s1) print("\n".join(ans)) ```
output
1
31,215
12
62,431
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,216
12
62,432
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` from collections import Counter def solve(case): n=int(input()) n*=2 l=list(map(int,input().split())) l.sort(reverse=True) for i in range(1,n): f=0 d=Counter(l) t=l[0] d[t]-=1 d[l[i]]-=1 out=[[t,l[i]]] for j in range(1,n): if i==j: continue curr=l[j] if d[curr]==0: continue d[curr]-=1 if d[t-curr]<=0: f=1 break out.append([curr,t-curr]) d[t-curr]-=1 t=curr if f==0: break if f==0: print('YES') print(out[0][0]+out[0][1]) for i in out: print(i[0],i[1]) else: print('NO') for _ in range(int(input())): solve(1) ```
output
1
31,216
12
62,433
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,217
12
62,434
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings 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=50005, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------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------------------------------------ for ik in range(int(input())): n=int(input()) l=list(map(int,input().split())) l.sort() done=0 for i in range(2*n-1): d = defaultdict(int) c=0 for i1 in range(2*n): d[l[i1]] += 1 su = l[i] + l[-1] d[l[i]] -= 1 d[l[-1]] -= 1 ans = [] ans.append((l[i], l[-1])) last = l[-1] f = 0 for j in sorted(d, reverse=True): while (d[j] > 0): d[j]-=1 if d[last - j] <= 0: f = 1 break ans.append((j, last - j)) d[last - j] -= 1 last = j if f==1: break if f == 0: done = 1 print("YES") print(su) for i in range(n): print(*ans[i]) break if done==0: print("NO") ```
output
1
31,217
12
62,435
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,218
12
62,436
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split())) mod = 10**9+7; Mod = 998244353; INF = float('inf') #______________________________________________________________________________________________________ # from math import * # from bisect import * # from heapq import * from collections import defaultdict as dd # from collections import OrderedDict as odict # from collections import Counter as cc # from collections import deque # sys.setrecursionlimit(2*(10**5)+100) #this is must for dfs # ______________________________________________________________________________________________________ # segment tree for range minimum query # n = int(input()) # a = list(map(int,input().split())) # st = [float('inf') for i in range(4*len(a))] # def build(a,ind,start,end): # if start == end: # st[ind] = a[start] # else: # mid = (start+end)//2 # build(a,2*ind+1,start,mid) # build(a,2*ind+2,mid+1,end) # st[ind] = min(st[2*ind+1],st[2*ind+2]) # build(a,0,0,n-1) # def query(ind,l,r,start,end): # if start>r or end<l: # return float('inf') # if l<=start<=end<=r: # return st[ind] # mid = (start+end)//2 # return min(query(2*ind+1,l,r,start,mid),query(2*ind+2,l,r,mid+1,end)) # ______________________________________________________________________________________________________ # Checking prime in O(root(N)) # def isprime(n): # if (n % 2 == 0 and n > 2) or n == 1: return 0 # else: # s = int(n**(0.5)) + 1 # for i in range(3, s, 2): # if n % i == 0: # return 0 # return 1 # def lcm(a,b): # return (a*b)//gcd(a,b) # ______________________________________________________________________________________________________ # nCr under mod # def C(n,r,mod): # if r>n: # return 0 # num = den = 1 # for i in range(r): # num = (num*(n-i))%mod # den = (den*(i+1))%mod # return (num*pow(den,mod-2,mod))%mod # M = 10**5 +10 # ______________________________________________________________________________________________________ # For smallest prime factor of a number # M = 1000010 # pfc = [i for i in range(M)] # def pfcs(M): # for i in range(2,M): # if pfc[i]==i: # for j in range(i+i,M,i): # if pfc[j]==j: # pfc[j] = i # return # pfcs(M) # ______________________________________________________________________________________________________ tc = 1 tc, = inp() for _ in range(tc): n, = inp() a = inp() a.sort(reverse = True) def check(b,val): ans = [] vis = [False for i in range(len(b))] d = dd(list) for i in range(len(b)): d[b[i]].append(i) for key in d.keys(): d[key] = d[key][::-1] i = 0 # print(d) while(i<len(b)): if vis[i]==True: i+=1 continue # print(b,i) tar = b[i] rem = val-tar # print("FASIF",b,i,tar,val,rem,"FAS") idd = d[tar].pop() vis[i] = True # print(d,rem) if len(d[rem])>0: idd = d[rem].pop() vis[idd] = True val = max(tar,rem) else: return False ans.append([tar,rem]) i+=1 return ans f = False if n>1: lol = a[0] a.remove(a[0]) for i in range(len(a)): val = a[i]+lol b = a.copy() lol1 = a[i] b.remove(b[i]) ans = check(b,lol) if ans: f = True break # print(b) if f: print("YES") print(val) print(lol,lol1) for i,j in ans: print(i,j) else: print("NO") else: print("YES") print(a[0]+a[1]) print(a[0],a[1]) ```
output
1
31,218
12
62,437
Provide tags and a correct Python 3 solution for this coding contest problem. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a.
instruction
0
31,219
12
62,438
Tags: brute force, constructive algorithms, data structures, greedy, implementation, sortings Correct Solution: ``` import sys input = sys.stdin.readline from collections import Counter cnt = Counter() for _ in range(int(input())): n = int(input()) A = sorted(map(int, input().split()), reverse=True) for k in range(1, 2 * n): used = [0] * (2 * n) used[0] = used[k] = 1 cur = A[0] ans = [[A[0], A[k]]] s = A[0] + A[k] cnt.clear() for i in range(1, 2 * n): if not used[i]: cnt[A[i]] += 1 for i in range(1, 2 * n): if not cnt[A[i]]: continue cnt[A[i]] -= 1 target = cur - A[i] if not cnt[target]: break cnt[target] -= 1 ans.append([A[i], target]) cur = A[i] else: print("YES") print(s) for a in ans: print(*a) break else: print("NO") ```
output
1
31,219
12
62,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` import itertools import collections import copy 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) def input(): return sys.stdin.readline().rstrip("\r\n") mo = int(1e9+7) def exgcd(a, b): if not b: return 1, 0 y, x = exgcd(b, a % b) y -= a//b * x return x, y def getinv(a, m): x, y = exgcd(a, m) return -(-1) if x == 1 else x % m def comb(n, b): res = 1 b = min(b, n-b) for i in range(b): res = res*(n-i)*getinv(i+1, mo) % mo # res %= mo return res % mo t = int(input()) for _ in range(t): n = int(input()) li = [int(i) for i in input().split()] # s = set(li) d = {} for i in li: d[i] = d.get(i,0) + 1 li.sort() f = True for ptr in li: # tli = list(li) # tli.remove(ptr) ans = [] # x = tli.pop() f = True if ptr==li[-1]: x = li[-2] + ptr else: x = li[-1] + ptr srcx = int(x) dd = dict(d) # dd[ptr]-=1 for cur in li[::-1]: while dd[cur]: dd[cur]-=1 if dd.get(x-cur,0): dd[x-cur]-=1 # if dd[cur]==0: # f = False # break # else: # dd[cur]-=1 ans.append((x-cur, cur)) x = max(x-cur,cur) else: f = False break if f == False: break if f: ax = ptr break # while tli: # if x - tli[-1] in tli and tli.index(x-tli[-1])!=len(tli)-1: # tp = x-tli[-1] # tpp = tli[-1] # ans.append((x-tli[-1], tli[-1])) # tli.remove(x-tli[-1]) # x = max(tp, tpp) # tli.pop() # else: # f = False # break # if f: # break if f: # ans.append((li[-1],srcx)) print('YES') # print(ax+srcx) # print(ax,srcx) print(sum(ans[0])) for i in ans: print(*i) else: print('NO') ```
instruction
0
31,220
12
62,440
Yes
output
1
31,220
12
62,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # jhjjh def binary_search(l,n,k): s = 0 e = n while(s<=e): mid = (s+e)//2 if(l[mid] == k): return mid elif(k < l[mid]): e = mid - 1 elif(k > l[mid]): s = mid + 1 return -1 def main(): for _ in range(int(input())): n = int(input()) l = list(map(int,input().split())) l.sort() # print(l) for i in range(2*n-1): ans = l[i] + l[-1] t = l.copy() t.pop() t.pop(i) ll = 2*n - 3 m = l[-1] f = 1 while(ll > 0): # print(ll,t) mm = m - t[-1] m = t.pop() ll -= 1 pos = binary_search(t, ll, mm) if(pos == -1): f = 0 break else: t.pop(pos) ll -= 1 if(f): print("YES") print(ans) print(l[-1],l[i]) t = l.copy() t.pop(i) t.pop() ll = 2*n - 3 m = l[-1] while(ll > 0): mm = m - t[-1] m = t.pop() ll -= 1 pos = binary_search(t, ll, mm) print(mm,m) t.pop(pos) ll -= 1 break if(f==0): print("NO") # 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") # endregion if __name__ == "__main__": main() ```
instruction
0
31,221
12
62,442
Yes
output
1
31,221
12
62,443
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` from collections import Counter t=int(input()) for _ in range(0,t,1): n=int(input()) A = [int(a) for a in input().split()] A.sort(reverse=True) ans=[] ok=False for i in range(1,len(A),1): sum=0 cur=A[0] con = Counter() sum+=(A[0]+A[i]) ans.clear() ans.append([A[0],A[i]]) for j in range(1,len(A),1): con[A[j]]+=1 con[A[i]]-=1 for k in range(1,len(A),1): if not con[A[k]]: continue con[A[k]]-=1 target=cur-A[k] if not con[target]: break con[target]-=1 cur=A[k] ans.append([target,A[k]]) check=True for k in range(0,len(A),1): if con[A[k]]>0: check=False break if check==True: print("YES \n{}".format(sum)) for k in range(0,len(ans),1): print("{} {}".format(ans[k][0],ans[k][1])) ok=True break if ok==False: print("NO") ```
instruction
0
31,222
12
62,444
Yes
output
1
31,222
12
62,445
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` # cook your dish here # cook your dish here t = int(input()) for i in range(t): n = int(input()) a = list(map(int,input().split())) a.sort() a.reverse() x = [] for j in range(1,2*n): x.append(a[0]+a[j]) #print(x) for j in range(len(x)): x1 = x[j] #a1 = a.copy() w=[[x1]] t=0 val=0 d={} aj=0 for j1 in range(2*n): if a[j1] not in d: d[a[j1]] = [j1] else: d[a[j1]].append(j1) #print(d) for val in a: if val not in d: continue d[val].pop() y=x1-val x1=val+0 w.append([val]) if len(d[val])==0: del d[val] if y not in d: #print("a",d,y,w) aj=37 break d[y].pop() w[-1].append(y) if len(d[y])==0: del d[y] if(aj==0): break if(aj==0): print("YES") for q in w: print(*q) else: print("NO") ```
instruction
0
31,223
12
62,446
Yes
output
1
31,223
12
62,447
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` from sys import stdin _input = stdin.readline _int, _sum, _dict, _reversed, _range, _len, _sorted, _max = int, sum, dict, reversed, range, len, sorted, max from collections import defaultdict from copy import deepcopy def check(elem, d, keys, print_status): test_dict = deepcopy(d) x = keys[-1] + elem if print_status: print(x) while test_dict[x - elem] > 0: test_dict[elem] -= 1 test_dict[x - elem] -= 1 if print_status: print(elem, x - elem) x = _max(elem, x - elem) for i in _reversed(keys): if test_dict[i] > 0: elem = i break if _sum(test_dict.values()) == 0: return True else: return False def task(): n = _int(_input()) arr = defaultdict(_int) for i in _input().split(): arr[_int(i)] += 1 keys = _sorted(arr.keys()) len_dict = _len(arr) for i in _range(len_dict): if check(keys[i], arr, keys, False): print("YES") check(keys[i], arr, keys, True) return print("NO") return def solution(): for _ in _range(_int(_input())): task() solution() ```
instruction
0
31,224
12
62,448
No
output
1
31,224
12
62,449
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` from bisect import bisect from sys import stdin input=stdin.readline #dont know def arraydest(n,arr): t=0 cnt = [0] * (10 ** 6 + 1) arr = sorted(arr) for i in range(2*n- 1): for j in range(2*n): cnt[arr[j]] += 1 j = 2*n - 1 x = arr[i] + arr[j] rm = [] for op in range(0, n): while j > 0 and cnt[arr[j]] == 0: j -= 1 rm.append(arr[j]) rm.append(x -arr[j]) cnt[arr[j]]-=1 cnt[x-arr[j]]-=1 if cnt[arr[j]]<0 or cnt[x-arr[j]]<0: cnt[arr[j]]=0 cnt[x-arr[j]]=0 break x=max(x-arr[j],arr[j]) if op+1==n: t=1 if t: print("YES") print(rm[0]+rm[1]) for i in range(0,len(rm)-1,2): print(rm[i],rm[i+1]) return "" return "NO" for i in range(int(input())): a = int(input()) lst = list(map(int, input().strip().split())) print(arraydest(a,lst)) ```
instruction
0
31,225
12
62,450
No
output
1
31,225
12
62,451
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` t = int(input()) def l_dec(dd, k): dd[k] -= 1 if dd[k] == 0: del dd[k] for _ in range(t): n = int(input()) a = [int(e) for e in input().split()] a.sort(reverse=True) lp = {} for e in a: if e in lp: lp[e] += 1 else: lp[e] = 1 inf = False for k in range(1, 2*n): l = lp.copy() l_dec(l, a[k]) p = [[a[0], a[k]]] #print('--------------') #print(a) for i in range(2*n): e = a[i] if e not in l: continue else: l_dec(l, e) j = i+1 while j < 2*n and a[j] not in l: j += 1 #print(e,a[j],l) if j == 2*n: break l_dec(l, a[j]) ne = e - a[j] if ne not in l: break else: l_dec(l, ne) p.append([a[j],ne]) #print(p, l) if len(l) > 0: inf = True else: inf = False break if inf: print('NO') else: print('YES') print(p[0][0]+p[0][1]) for e in p: print(e[0], e[1]) ```
instruction
0
31,226
12
62,452
No
output
1
31,226
12
62,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` import random def hasArrayTwoCandidates(A, arr_size, sum): l = 0 r = arr_size-1 while l<r: if (A[l] + A[r] == sum): return [l,r] elif (A[l] + A[r] < sum): l += 1 else: r -= 1 return [-1,-1] def quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi + 1, ei) def partition(A, si, ei): x = A[ei] i = (si-1) for j in range(si, ei): if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return i + 1 for i in range(int(input())): n=int(input()) a=list(map(int,input().split())) quickSort(a, 0, n-1) f=0 for j in range(n): r1=random.randint(0,max(a)*2) r=hasArrayTwoCandidates(a,len(a),r1) if(r[0]!=-1): print("YES") print(r1) su1=a[r[0]]+a[r[1]] print(a[r[0]],a[r[1]]) a.pop(max(r[1],r[0])) a.pop(min(r[0],r[1])) a.append(su1) f=1 break if(f==1): for j in range(n-1): sum1=a[len(a)-1]+a[len(a)-2] print(a[len(a)-1],a[len(a)-2]) a.pop(len(a)-1) a.pop(len(a)-2) a.append(sum1) else: print("NO") ```
instruction
0
31,227
12
62,454
No
output
1
31,227
12
62,455
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you do the following operation n times: * select two elements of array with sum equals x; * remove them from a and replace x with maximum of that two numbers. For example, if initially a = [3, 5, 1, 2], you can select x = 6. Then you can select the second and the third elements of a with sum 5 + 1 = 6 and throw them out. After this operation, x equals 5 and there are two elements in array: 3 and 2. You can throw them out on the next operation. Note, that you choose x before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of a. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the single integer n (1 ≀ n ≀ 1000). The second line of each test case contains 2n integers a_1, a_2, ..., a_{2n} (1 ≀ a_i ≀ 10^6) β€” the initial array a. It is guaranteed that the total sum of n over all test cases doesn't exceed 1000. Output For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of x you've chosen. Print description of n operations next. For each operation, print the pair of integers you remove. Example Input 4 2 3 5 1 2 3 1 1 8 8 64 64 2 1 1 2 4 5 1 2 3 4 5 6 7 14 3 11 Output YES 6 1 5 2 3 NO NO YES 21 14 7 3 11 5 6 2 4 3 1 Note The first test case was described in the statement. In the second and third test cases, we can show that it is impossible to throw out all elements of array a. Submitted Solution: ``` """ Python 3 compatibility tools. """ from __future__ import division, print_function import itertools import sys import os from io import BytesIO from atexit import register if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip def gcd(x, y): """ greatest common divisor of x and y """ while y: x, y = y, x % y return x sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') # import sys # input=sys.stdin.readline from collections import Counter def pair(arr, c, i): solution = [] c[i] -= 1 if c[i] == 0: del c[i] if arr[-1] not in c: return False c[arr[-1]] -= 1 if c[arr[-1]] == 0: del c[arr[-1]] key = arr[-1] + i solution.append((arr[-1], i)) sumC = arr[-1] # print("TART", i, c) while c: toPair = max(c) c[toPair] -= 1 if c[toPair] == 0: del c[toPair] toPair2 = sumC - toPair if toPair2 in c: c[toPair2] -= 1 if c[toPair2] == 0: del c[toPair2] solution.append((toPair, toPair2)) sumC = toPair else: # print(i, c) return False return (key, solution) cases = int(input()) for _ in range(cases): n = int(input()) arr = list(map(int, input().split())) arr.sort() found = False for i in set(arr[len(arr) // 2 - 1:]): res = pair(arr, Counter(arr), i) if res: print("YES") print(res[0]) for k,v in res[1]: print(k,v) found = True break if not found: print("NO") ```
instruction
0
31,228
12
62,456
No
output
1
31,228
12
62,457
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,258
12
62,516
Tags: brute force, implementation Correct Solution: ``` n,k=map(int,input().split()) A=[int(x) for x in input().split()] m=0 i=n-1 if len(set(A))==1: print(0) exit() while(i>0 and A[i]==A[-1]): i-=1 i+=1 if i<=k-1: print(i) else: print(-1) ```
output
1
31,258
12
62,517
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,259
12
62,518
Tags: brute force, implementation Correct Solution: ``` n, k = [int(x) for x in input().split()] list1 = [int(x) for x in input().split()] test_bool = False if len(set(list1[k-1:]))>1: print(-1) elif k >= 2: for i in range(k-2, -1, -1): if list1[k-1] != list1[i]: print(i+1) test_bool = False break else: test_bool = True if test_bool: print(0) else: print(0) ```
output
1
31,259
12
62,519
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,260
12
62,520
Tags: brute force, implementation Correct Solution: ``` n,k = map(int,input().split()) l = list(map(int,input().split())) x = l[n-1] m = 0 for i in range(n-2,-1,-1): if(l[i]!=x): m = i+1 break if(m>=k): print("-1") else: print(m) ```
output
1
31,260
12
62,521
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,261
12
62,522
Tags: brute force, implementation Correct Solution: ``` n, k = map(int, input().split()) arr = list(map(int, input().split())) last_elem = arr[-1] idx = -1 for i in range(n-1): if arr[i] != last_elem: idx = i if idx+1 >= k: print(-1) else: print(idx+1) ```
output
1
31,261
12
62,523
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,262
12
62,524
Tags: brute force, implementation Correct Solution: ``` n,k=map(int,input().split()) a=[int(a) for a in input().split()] v=k-1 for i in range(n-1,-1,-1): if (a[i]!=a[k-1]): v=i break if (v>k-1): print (-1) elif (v==k-1): print (0) else: print (v+1) ```
output
1
31,262
12
62,525
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,263
12
62,526
Tags: brute force, implementation Correct Solution: ``` n,k=(int(i) for i in input().split()) a=[int(i) for i in input().split()] b=a[k-1:n] if (b.count(b[0])==len(b)): j=k-1 while(j>=0): if (a[j]!=a[n-1]): break j=j-1 if (j<=k-1): print(j+1) else: print(-1) else: print(-1) ```
output
1
31,263
12
62,527
Provide tags and a correct Python 3 solution for this coding contest problem. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
instruction
0
31,264
12
62,528
Tags: brute force, implementation Correct Solution: ``` # recursion # video 80 # maths # question 70 from collections import deque # d={"E":1} def solve(): n,k=map(int,input().split()) d=list(map(int,input().split())) if len(set(d[k-1:]))!=1: print(-1) return store=-1 for i in range(k-1): if d[i]!=d[k-1]: store=i print(store+1) solve() ```
output
1
31,264
12
62,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1. Submitted Solution: ``` n,k = map(int,input().split(" ")) arr = [int(num) for num in input().split(" ")] pos = 0 for x in range(1,n): if arr[x] == arr[k - 1] and arr[x - 1] != arr[k - 1]: # tutaj jak ciag jest jeden to na kazdej pozycji bedzie zapisywac pos = x if arr[k - 1] != arr[n - 1]: print(-1) else: print(n - (n - pos)) ''' 6 2 1 1 1 1 1 1 Ans: 0 Your answer: 2 (len(arr) - k) 8 7 4 2 3 1 1 1 1 1 Ans: 3 4 1 1 1 1 1 Ans: 0 4 1 3 1 1 1 Ans: -1 8 2 3 2 1 1 1 0 0 1 Ans: -1 Check the position of the first element in same-number-sequence O(n - k) ''' ```
instruction
0
31,269
12
62,538
No
output
1
31,269
12
62,539