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. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2
instruction
0
1,232
12
2,464
Tags: brute force, constructive algorithms, implementation, number theory Correct Solution: ``` """ Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have EVEN sum (each of them must have even sum) and remaining k - p have ODD sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. input 5 5 3 2 6 10 5 9 output YES 1 9 1 5 1 10 1 6 1 2 input 5 5 3 7 14 2 9 5 output NO input 5 3 1 1 2 3 7 5 output YES 3 5 1 3 1 7 1 2 """ class part_array: def __init__(self): self.count = 0 self.num_list = [] def AddNumber(self, n): self.num_list.append(n) self.count += 1 def AddNumberList(self, li): self.num_list.extend(li) self.count += len(li) def print_solution_and_exit(e, o): print('YES') for part in e: print (part.count, ' '.join(map(str, part.num_list))) for part in o: print (part.count, ' '.join(map(str, part.num_list))) exit() def print_solution_error(): print ('NO') exit() n, k, p = map(lambda t : int(t), input().split()) numbers = list(map(lambda t : int(t), input().split())) odds = list(filter( lambda t: t % 2 == 1, numbers)) evens = list(filter( lambda t: t % 2 == 0, numbers)) odd_parts = [] even_parts = [] # need to have at leas k - p odd numbers. Cannot get an odd sum without one if k - p > len(odds): print_solution_error() # check if we can get the even piles #p - len(evens) < while len(even_parts) < p and len(evens) > 0: part = part_array() part.AddNumber(evens.pop()) even_parts.append(part) while len(odd_parts) < k - p and len(odds) > 0: part = part_array() part.AddNumber(odds.pop()) odd_parts.append(part) # check if only odd parts need to be created needed_odd_parts = k - p - len(odd_parts) if len(even_parts) == p and needed_odd_parts > 0: # excess even numbers can be added to any odd part excess_odds = len(odds) - needed_odd_parts if excess_odds < 0 or excess_odds % 2 == 1: # not enough odd numberss # the exxess need to have an even sum print_solution_error() for i in range(needed_odd_parts): part = part_array() part.AddNumber(odds.pop()) odd_parts.append(part) #check if only even parts need to be created needed_even_parts = p - len(even_parts) if len(odd_parts) == k - p and needed_even_parts > 0: excess_evens = len(evens) - needed_even_parts if len(odds) % 2 == 1 or excess_evens + len(odds) // 2 < 0: # not enough odd numberss # the exxess need to have an even sum print_solution_error() while needed_even_parts > 0: if len(evens) > 0: part = part_array() part.AddNumber(evens.pop()) even_parts.append(part) else: part = part_array() part.AddNumber(odds.pop()) part.AddNumber(odds.pop()) even_parts.append(part) needed_even_parts -= 1 # now we need both even and odd, but we exausted all low hanging needed_even_parts = p - len(even_parts) needed_odd_parts = k - p - len(odd_parts) if needed_odd_parts > 0 or needed_even_parts > 0: print('needed_even_parts', needed_even_parts, 'needed_odd_parts', needed_odd_parts) print_solution_and_exit() # here we just add the remaning numbers to the solution if len(odds) % 2 == 1: print_solution_error() #k is at least 1 so we have a part if len(odd_parts) > 0: odd_parts[0].AddNumberList(odds) odd_parts[0].AddNumberList(evens) else: even_parts[0].AddNumberList(odds) even_parts[0].AddNumberList(evens) ods = [] # done evens = [] #done print_solution_and_exit(even_parts, odd_parts) #while len(odd_parts) + len(even_parts) < k: print('DEBUG') print (numbers) print (evens) print (odds) ```
output
1
1,232
12
2,465
Provide tags and a correct Python 3 solution for this coding contest problem. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2
instruction
0
1,233
12
2,466
Tags: brute force, constructive algorithms, implementation, number theory Correct Solution: ``` import os,io from sys import stdout import collections # import random # import math # from operator import itemgetter input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # from collections import Counter # from decimal import Decimal # import heapq # from functools import lru_cache import sys # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(102400000) # from functools import lru_cache # @lru_cache(maxsize=None) ###################### # --- Maths Fns --- # ###################### def primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def divisors(n): i = 1 result = [] while i*i <= n: if n%i == 0: if n/i == i: result.append(i) else: result.append(i) result.append(n/i) i+=1 return result def distance(xa, ya, xb, yb): return ((ya-yb)**2 + (xa-xb)**2)**(0.5) # @lru_cache(maxsize=None) def digitsSum(n): if n == 0: return 0 r = 0 while n > 0: r += n % 10 n //= 10 return r ###################### # ---- GRID Fns ---- # ###################### def isValid(i, j, n, m): return i >= 0 and i < n and j >= 0 and j < m def print_grid(grid): for line in grid: print(" ".join(map(str,line))) ###################### # ---- MISC Fns ---- # ###################### def kadane(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def ceil(n, d): if n % d == 0: return n // d else: return (n // d) + 1 def _abs(a, b): return int(abs(a - b)) def evenodd(l): even = [e for e in l if e & 1 == 0] odd = [e for e in l if e & 1] return (even, odd) # INPUTS -------------------------- # s = input().decode('utf-8').strip() # n = int(input()) # l = list(map(int, input().split())) # t = int(input()) # for _ in range(t): # for _ in range(t): n, k, p = list(map(int, input().split())) l = list(map(int, input().split())) even, odd = evenodd(l) rest = k - p reven = [] rodd = [] i, j = 0, 0 while i < len(even) and p > 0: reven.append([even[i]]) p -= 1 i += 1 while j < len(odd)-1 and p > 0: reven.append([odd[j], odd[j+1]]) p -= 1 j += 2 if i == len(even) and j >= len(odd)-1 and p > 0: print('NO') exit() if p == 0: even = even[i:] odd = odd[j:] i, j = 0, 0 while j < len(odd) and rest > 0: rodd.append([odd[j]]) rest -= 1 j += 1 if j == len(odd) and rest > 0: print('NO') exit() if rest == 0: odd = odd[j:] if len(even) or len(odd): oddRemaining = len(odd) if oddRemaining % 2 == 1: print('NO') exit() else: if not len(reven): rodd[0] += odd + even else: reven[0] += odd + even print('YES') for e in reven: print(len(e), " ".join(list(map(str, e)))) for e in rodd: print(len(e), " ".join(list(map(str, e)))) ```
output
1
1,233
12
2,467
Provide tags and a correct Python 3 solution for this coding contest problem. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2
instruction
0
1,234
12
2,468
Tags: brute force, constructive algorithms, implementation, number theory Correct Solution: ``` import sys inputStr = input() inputArr = inputStr.split(' ') n = int(inputArr[0]) k = int(inputArr[1]) p = int(inputArr[2]) arr = list(map(int, input().split(' '))) odds = [] evens = [] for i in range(len(arr)): if(arr[i]%2): odds.append(i) else: evens.append(i) ans = [] oddPointer = 0 evenPointer = 0 for i in range(k-p): if (oddPointer >= len(odds)): print("NO") quit() oddArr = [odds[oddPointer]] oddPointer += 1 ans.append(oddArr) for i in range(p): if (oddPointer < len(odds)): if (oddPointer + 1 >= len(odds)): print("NO") quit() else : oddArr = [odds[oddPointer], odds[oddPointer+1]] oddPointer += 2 ans.append(oddArr) elif (evenPointer < len(evens)): evenArr = [evens[evenPointer]] evenPointer += 1 ans.append(evenArr) else: print("NO") quit() if ((len(odds) - oddPointer)%2): print("NO") quit() for i in range(oddPointer, len(odds)): ans[0].append(odds[i]) for i in range(evenPointer, len(evens)): ans[0].append(evens[i]) print("YES") for i in range(len(ans)): sys.stdout.write(str(len(ans[i]))) sys.stdout.write(' ') for j in range(len(ans[i])): sys.stdout.write(str(arr[ans[i][j]])) sys.stdout.write(' ') sys.stdout.write('\n') sys.stdout.flush() ```
output
1
1,234
12
2,469
Provide tags and a correct Python 3 solution for this coding contest problem. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2
instruction
0
1,235
12
2,470
Tags: brute force, constructive algorithms, implementation, number theory Correct Solution: ``` n,k,p = map(int,input().split()) ar = list(map(int,input().split())); q = k-p zeros,ones = [],[] res = [] for a in ar: if a%2: ones += [a] else: zeros += [a] while p: if len(zeros): res += [[zeros.pop()]] elif len(ones)>=2: res += [ones[-2:]] del ones[-2:] else: print('NO') exit(0) p -= 1 while q: if len(ones): res += [[ones.pop()]] else: print('NO') exit(0) q -= 1 if len(zeros): res[0] += zeros if len(ones)%2==0: res[0] += ones else: print('NO') exit(0) print('YES') for s in res: print(len(s),*s) # C:\Users\Usuario\HOME2\Programacion\ACM ```
output
1
1,235
12
2,471
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` def main(): import sys tokens = [int(i) for i in sys.stdin.read().split()] tokens.reverse() n, k, p = [tokens.pop() for i in range(3)] a = [tokens.pop() for i in range(n)] odd = [i for i in a if i & 1] even = [i for i in a if i & 1 == 0] if len(odd) < k - p or (len(odd) - (k - p)) % 2 == 1: print("NO") return result = [] for i in range(k - p): result.append([odd.pop()]) while len(result) < k and odd: result.append([odd.pop(), odd.pop()]) while len(result) < k and even: result.append([even.pop()]) if len(result) < k: print("NO") return result[-1].extend(odd) result[-1].extend(even) print("YES") print('\n'.join(' '.join(map(str, [len(i)] + i)) for i in result)) main() ```
instruction
0
1,236
12
2,472
Yes
output
1
1,236
12
2,473
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` n, k, p = map(int, input().split()) s = k - p a = b = c = '' for i in input().split(): i = ' ' + i if i[-1] in '13579': if s > 0: a += '\n1' + i elif s & 1: if p >= 0: b += i else: c += i else: if p > 0: b += '\n2' + i else: c += i p -= 1 s -= 1 else: if p > 0: a += '\n1' + i p -= 1 else: c += i if s > 0 or s & 1 or p > 0: print('NO') else: print('YES') if a: print(str(1 + c.count(' ')) + c + a[2: ] + b) else: print(str(2 + c.count(' ')) + c + b[2: ]) ```
instruction
0
1,237
12
2,474
Yes
output
1
1,237
12
2,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` def solve(): n, k, p = map(int, input().split()) a = list(map(int, input().split())) even = list(filter(lambda x: x % 2 == 0, a)) odd = list(filter(lambda x: x % 2 == 1, a)) if (len(odd) - (k - p)) % 2 != 0: print('NO') return ans = [[] for _ in range(k)] for i in range(k - p): if odd: ans[i].append(odd.pop()) else: print('NO') return for i in range(k - p, k): if even: ans[i].append(even.pop()) elif len(odd) >= 2: ans[i].append(odd.pop()) ans[i].append(odd.pop()) else: print('NO') return ans[0] += even ans[0] += odd print('YES') for part in ans: print(len(part), ' '.join(map(str, part))) solve() ```
instruction
0
1,238
12
2,476
Yes
output
1
1,238
12
2,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` n,k,p=map(int,input().split()) oc,ec=[],[] for i in map(int,input().split()): if i&1: oc.append(i) else:ec.append(i) l=len(oc) if l<k-p or l&1!=(k-p)&1 or len(ec)+(l-(k-p))/2<p: print('NO') exit() res=[] q=k-p while p: if len(ec): res.append([ec.pop()]) elif len(oc)>=2: res.append(oc[-2:]) del oc[-2:] else: print('NO') exit(0) p-=1 while q: if len(oc): res.append([oc.pop()]) else:print('NO');exit(0) q-=1 if len(ec): res[0]+=ec if len(oc)%2==0: res[0]+=oc print('YES') for s in res: print(len(s),*s) ```
instruction
0
1,239
12
2,478
Yes
output
1
1,239
12
2,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` import sys def fastio(): from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() def debug(*var, sep = ' ', end = '\n'): print(*var, file=sys.stderr, end = end, sep = sep) INF = 10**20 MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) from math import gcd from math import ceil from collections import defaultdict as dd, Counter from bisect import bisect_left as bl, bisect_right as br n, k, p = I() o = k - p a = I() nums = [[], []] for i in range(n): nums[a[i] % 2].append([a[i]]) def NO(): print("NO") exit() if o > len(nums[1]): NO() ans = [[], []] for i in range(o): if nums[1]: ans[1].append(nums[1].pop()) else: NO() if len(nums[1]) % 2: NO() while nums[1]: nums[0].append(nums[1].pop() + nums[1].pop()) for i in range(p): ans[0].append(nums[0].pop()) if p: for i in nums[0]: ans[0][0] += i if o: for i in nums[0]: ans[1][0] += i if len(ans[0]) != p or len(ans[1]) != o: NO() print('YES') if p: for i in ans[0]: print(len(i), *i) if o: for i in ans[1]: print(len(i), *i) ```
instruction
0
1,240
12
2,480
No
output
1
1,240
12
2,481
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` n,k,p=list(map(int, input().split(' '))) a=list(map(int, input().split(' '))) odd, even = [],[] for temp in a: if(temp%2==0): even.append(temp) else: odd.append(temp) if(len(odd)%2!=(k-p)%2): print ("NO") else: ans=[] for i in range(k): ans.append([]) i=0 for o in odd: if(i<k-p): ans[i].append(o) i+=1 elif(p!=0): ans[i].append(o) else: ans[0].append(o) for o in even: if(i<k): ans[i].append(o) i+=1 else: ans[0].append(o) print (ans) t=0 for f in ans: cur = sum(f) if(cur%2==1): t+=1 if(False and t!=k-p): print ("NO") else: print ("YES") for f in ans: print (len(f), " ".join(map(str,f))) ```
instruction
0
1,241
12
2,482
No
output
1
1,241
12
2,483
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` n,k,p=map(int,input().split()) l=[int(i) for i in input().split()] odd=[i for i in l if i&1] even=[i for i in l if i&1==0] if len(odd)%2!=(k-p)%2: print("NO") exit() #parity not maintained ans=[] for i in range(k): ans.append([]) i=0 for o in odd: if i<k-p: ans[i].append(o) i+=1 elif i<k: ans[i].append(o) if len(ans[i])>=2: i+=1 else: ans[0].append(o) for e in even: if i<k: ans[i].append(e) i+=1 else: ans[0].append(e) cnt=0 #print(ans) for i in ans: if sum(i)&1: cnt+=1 if cnt!=k-p: print("NO") exit() print("YES") for i in ans: print(len(i),*i) ```
instruction
0
1,242
12
2,484
No
output
1
1,242
12
2,485
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning. Input The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109). Output In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition. Examples Input 5 5 3 2 6 10 5 9 Output YES 1 9 1 5 1 10 1 6 1 2 Input 5 5 3 7 14 2 9 5 Output NO Input 5 3 1 1 2 3 7 5 Output YES 3 5 1 3 1 7 1 2 Submitted Solution: ``` n,k,p=list(map(int, input().split(' '))) a=list(map(int, input().split(' '))) odd, even = [],[] for temp in a: if(temp%2==0): even.append(temp) else: odd.append(temp) if(len(odd)%2!=(k-p)%2): print ("NO") else: ans=[] for i in range(k): ans.append([]) i=0 for o in odd: if(i<k-p): ans[i].append(o) i+=1 elif(p!=0): ans[i].append(o) else: ans[0].append(o) for o in even: if(i<k): ans[i].append(o) i+=1 else: ans[0].append(o) print (ans) t=0 for f in ans: cur = sum(f) if(cur%2==1): t+=1 if(False and t!=k-p): print ("NO") else: for f in ans: print (len(f), " ".join(map(str,f))) ```
instruction
0
1,243
12
2,486
No
output
1
1,243
12
2,487
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,333
12
2,666
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` def main(): from heapq import heapify, heappop, heappushpop,heappush n, k, x = map(int, input().split()) l, sign, h = list(map(int, input().split())), [False] * n, [] helper = lambda: print(' '.join(str(-a if s else a) for a, s in zip(l, sign))) for i, a in enumerate(l): if a < 0: sign[i] = True h.append((-a, i)) else: h.append((a, i)) heapify(h) a, i = heappop(h) if 1 - sum(sign) % 2: j = min(a // x + (1 if a % x else 0), k) a -= j * x if a > 0: l[i] = a return helper() k -= j a = -a sign[i] ^= True for _ in range(k): a, i = heappushpop(h, (a, i)) a += x l[i] = a for a, i in h: l[i] = a helper() if __name__ == '__main__': main() ```
output
1
1,333
12
2,667
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,334
12
2,668
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import heapq inp = list(map(int, input().split())) n = inp[0] k = inp[1] x = inp[2] a = [int(i) for i in input().strip().split(' ')] isPositive = True nodes = [[abs(val), val, index] for index, val in enumerate(a)] for el in a: if el < 0: isPositive = not isPositive heapq.heapify(nodes) for i in range(k): minNode = nodes[0] val = minNode[1] isCurPositive = val >= 0 newVal = val if isPositive == isCurPositive: newVal -= x else: newVal += x minNode[1] = newVal if val >= 0 > newVal or val < 0 <= newVal: isPositive = not isPositive heapq.heapreplace(nodes, [abs(newVal), newVal, minNode[2]]) result = [None] * n for node in nodes: result[node[2]] = str(node[1]) print(" ".join(result)) ```
output
1
1,334
12
2,669
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,335
12
2,670
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` f = lambda: map(int, input().split()) from heapq import * n, k, x = f() t, h, p = 0, [], list(f()) for i in range(n): t ^= p[i] < 0 heappush(h, (abs(p[i]), i)) for j in range(k): i = heappop(h)[1] d = p[i] < 0 if not t: d, t = 1 - d, -x <= p[i] < x if d: p[i] -= x else: p[i] += x heappush(h, (abs(p[i]), i)) for q in p: print(q) ```
output
1
1,335
12
2,671
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,336
12
2,672
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import heapq n,k,v = map(int, input().split()) num = list(map(int, input().split())) sign = len([x for x in num if x<0]) minx,mini = min([[abs(x),i] for i,x in enumerate(num)]) if sign%2==0: if num[mini]<0: c = min(minx//v+1, k) k -= c num[mini] += v*c elif num[mini]>=0: c = min(minx//v+1, k) k -= c num[mini] -= v*c heap = [] heapq.heapify(heap) for i,x in enumerate(num): heapq.heappush(heap, [abs(x), i]) while k: absx,curi = heapq.heappop(heap) #print(curi, num[curi]) if num[curi]>=0: num[curi] += v else: num[curi] -= v heapq.heappush(heap, [abs(num[curi]),curi]) k -= 1 print(' '.join([str(x) for x in num])) ```
output
1
1,336
12
2,673
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,337
12
2,674
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import heapq as hq from math import ceil n, k, x = [int(i) for i in input().strip().split(' ')] arr = [int(i) for i in input().strip().split(' ')] is_neg = False for i in arr: if i < 0: is_neg = True if is_neg == False else False narr = [[abs(i), pos, i < 0] for pos, i in enumerate(arr)] hq.heapify(narr) if is_neg: while k > 0: hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]]) k -= 1 else: minode = hq.heappop(narr) mi = minode[0] kswitch = ceil(mi/x) #make the off number of negatives if kswitch > k: kswitch = k else: minode[2] = False if minode[2] == True else True k -= kswitch hq.heappush(narr, [abs(mi-kswitch*x), minode[1], minode[2]]) while k > 0: hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]]) k -= 1 narr = sorted(narr, key=lambda x:x[1]) arr = [str(i[0]*(-1 if i[2] else 1)) for i in narr] print(" ".join(arr)) ```
output
1
1,337
12
2,675
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,338
12
2,676
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ def calc(n): if n>=0: return 1 return -1 n,k,x=map(int,input().split()) l=list(map(int,input().split())) eq=0 for i in l: if i<0: eq+=1 e=[[abs(l[i]),i,calc(l[i])] for i in range(n)] e.sort() if eq%2==0: k1=int(math.ceil(e[0][0]/x)) k1=min(k,k1) e[0][0]-=k1*x if e[0][0]<=0: e[0][2]*=-1 e[0][0] = abs(e[0][0]) k-=k1 heapq.heapify(e) while(k>0): w=heapq.heappop(e) w[0]+=x heapq.heappush(e,w) k-=1 ans=[0]*n for i in e: a,b,c=i ans[b]=a*c print(*ans) ```
output
1
1,338
12
2,677
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,339
12
2,678
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` import heapq n, k, X = map(int, input().split()) a = list(map(int, input().split())) Q = [] sit = 0 for i, x in enumerate(a): if x < 0: sit += 1 heapq.heappush(Q, (abs(x), x, i)) sit = sit % 2 while k > 0: (val, x, i) = heapq.heappop(Q) change = None if x < 0: if sit == 1: change = x - X else: change = x + X else: if sit == 1: change = x + X else: change = x - X if (x * change < 0) or (x < 0 and change == 0) or (x == 0 and change < 0): sit = (sit+1) % 2 heapq.heappush(Q, (abs(change), change, i)) k-=1 ans = [0] * n for (val, x, i) in Q: ans[i] = str(x) print(' '.join(ans)) #5 3 1 #5 4 3 5 2 #5 3 1 #5 4 3 5 5 #5 3 1 #5 4 4 5 5 #3 2 7 #5 4 2 ```
output
1
1,339
12
2,679
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5
instruction
0
1,340
12
2,680
Tags: constructive algorithms, data structures, greedy, math Correct Solution: ``` __author__ = 'Think' def respond(): if len(arr)>0: if not arr[0][2]: print(-arr[0][0], end="") else: print(arr[0][0], end="") for i in arr[1:]: if i[2]: print(" "+str(i[0]), end="") else: print(" "+str(-i[0]), end="") n, k, x=[int(i) for i in input().split()] data=[int(i) for i in input().split()] arr=[] parity=0 for i in range(n): if data[i]<0: parity+=1 arr.append([abs(data[i]), i, data[i]>=0]) ordered=sorted(arr, key=lambda n:abs(n[0])) if ordered[0][0]>=k*x and (parity%2)==0: arr[ordered[0][1]][0]-=k*x respond() else: start=0 if (parity%2)==0: start=1 c=ordered[0][0] ordered[0][0]=(x*((c//x)+1))-c k-=(c//x+1) arr[ordered[0][1]][2]=(not arr[ordered[0][1]][2]) if k>0: total=0 prev=0 broken=False for m in range(len(ordered)): a=ordered[m][0]//x if a==prev: total+=a continue prev=a if m*a-total<k: total+=a continue else: broken=True break if not broken: m+=1 base=(k+total)//m k-=(m*base-total) increm=sorted(ordered[:m], key=lambda n:(n[0]%x)) for i in increm: pos=i[1] if k>0: arr[pos][0]=(base+1)*x+(arr[pos][0]%x) k-=1 else: arr[pos][0]=base*x+(arr[pos][0]%x) respond() else: respond() ```
output
1
1,340
12
2,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` import heapq n, k, x = [int(val) for val in input().split()] a = [int(val) for val in input().split()] data = [(val, 1, i) if val >= 0 else (-1 * val, -1, i) for i, val in enumerate(a)] heapq.heapify(data) sign = sum([1 if s == -1 else 0 for _, s, _ in data]) if sign % 2 == 1: for i in range(k): e = heapq.heappop(data) heapq.heappush(data, (e[0] + x, e[1], e[2])) else: e = heapq.heappop(data) if e[0] < k * x: s = (e[0] // x) + 1 k -= s heapq.heappush(data, (s * x - e[0], -1 * e[1], e[2])) for i in range(k): e = heapq.heappop(data) heapq.heappush(data, (e[0] + x, e[1], e[2])) else: heapq.heappush(data, (e[0] - k * x, e[1], e[2])) output = [0] * n for val, s, i in data: output[i] = s * val print(' '.join([str(val) for val in output])) ```
instruction
0
1,341
12
2,682
Yes
output
1
1,341
12
2,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` import heapq s = input().split() n = int(s[0]) k = int(s[1]) x = int(s[2]) neg=0 zeroes=0 numbers = list(map(int,input().split())) num = [] for i in numbers: if(i<0): neg+=1 elif(i==0): zeroes+=1 for i,x1 in enumerate(numbers): num.append([abs(x1),i]) heapq.heapify(num) temp=[] steps=0 if(neg%2==0): temp = heapq.heappop(num) # print(temp[1],temp[0]) # print(numbers[temp[1]],x) if(numbers[temp[1]]<0): steps = min(abs(numbers[temp[1]])//x+1,k) k-=steps numbers[temp[1]]+=steps*x heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]]) else: steps = min((abs(numbers[temp[1]])//x)+1,k) # print(steps) k-=steps numbers[temp[1]]-=steps*x heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]]) while(k>0): temp = heapq.heappop(num) # print(temp[1],temp[0]) if(numbers[temp[1]]<0): # steps = (numbers[temp[1]]//x+1) # k-=steps numbers[temp[1]]-=x heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]]) else: # steps = (numbers[temp[1]]//x+1) # k-=steps numbers[temp[1]]+=x heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]]) k-=1 for i in numbers: print(i,end=" ") ```
instruction
0
1,342
12
2,684
Yes
output
1
1,342
12
2,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` def pull(i): global sign if L[i] < 0: L[i]+= x if L[i]>=0: sign*= -1 elif L[i] > 0: L[i]-= x if L[i]<0: sign*= -1 elif sign < 0: L[i]+= x else: L[i]-= x sign = -1 def push(i): global sign if L[i] > 0: L[i]+= x elif L[i] < 0: L[i]-= x elif sign < 0: L[i]+= x else: L[i]-= x sign = -1 n,k,x = map(int,input().split()) L = list(map(int,input().split())) sign = 1 for q in L: if q<0: sign*= -1 for i in range(n): if L[i] == 0: if k == 0: break k-= 1 push(i) ini = min(range(n), key=lambda i: abs(L[i])) while (sign > 0 or not L[ini]) and k > 0: k-= 1 pull(ini) #print(L, sign) #print(L) S = sorted(range(n), key=lambda i: abs(L[i])) i = 0 while k > 0: push(S[i]) k-= 1 j = (i+1)%n if abs(L[S[i]]) > abs(L[S[j]]): i = j #print(L) for i in L: print(i, end=' ') ```
instruction
0
1,343
12
2,686
No
output
1
1,343
12
2,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` import heapq class Node(object): def __init__(self, index, val): self.index = index self.val = val def __lt__(self, other): return abs(self.val).__lt__(abs(other.val)) inp = list(map(int, input().split())) n = inp[0] k = inp[1] x = inp[2] a = list(map(int, input().split())) isPositive = True nodes = [] for i in range(len(a)): el = a[i] node = Node(i, el) nodes.append(node) if el < 0: isPositive = not isPositive heapq.heapify(nodes) for i in range(k): minNode = nodes[0] val = minNode.val isCurPositive = val >= 0 if isPositive == isCurPositive: minNode.val -= x else: minNode.val += x if val * minNode.val < 0: isPositive = not isPositive heapq.heapify(nodes) result = ['0'] * n for node in nodes: result[node.index] = str(node.val) print(" ".join(result)) ```
instruction
0
1,344
12
2,688
No
output
1
1,344
12
2,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` import heapq n, k, X = map(int, input().split()) a = list(map(int, input().split())) Q = [] sit = 0 for i, x in enumerate(a): if x < 0: sit += 1 heapq.heappush(Q, (abs(x), x, i)) sit = sit % 2 while k > 0: (val, x, i) = heapq.heappop(Q) change = None if x < 0: if sit == 1: change = x - X else: change = x + X else: if sit == 1: change = x + X else: change = x - X if (x * change < 0) or (x < 0 and change == 0): sit = (sit+1) % 2 heapq.heappush(Q, (abs(change), change, i)) k-=1 ans = [0] * n for (val, x, i) in Q: ans[i] = x print(ans) #5 3 1 #5 4 3 5 2 #5 3 1 #5 4 3 5 5 #5 3 1 #5 4 4 5 5 #3 2 7 #5 4 2 ```
instruction
0
1,345
12
2,690
No
output
1
1,345
12
2,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) — the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 Submitted Solution: ``` def s(): [n,k,x] = list(map(int,input().split())) a = list(map(int,input().split())) a = [[a[i],i] for i in range(len(a))] a.sort(key = lambda x:abs(x[0])) z = 0 neg = 0 for i in a: i = i[0] if i == z: z += 1 if i < 0: neg += 1 if neg %2 == 0: if a[0][0] == 0: a[0][0] = -x k -= 1 elif a[0][0] < 0: while k > 0 and a[0][0] <= 0: a[0][0] += x k -= 1 else: while k > 0 and a[0][0] >= 0: a[0][0] -= x k -= 1 a.sort(key = lambda x:abs(x[0])) i = 0 while k > 0: if i >= n: i = 0 while k > 0 and abs(a[i][0]) <= abs(a[0][0]): if a[i][0] < 0: a[i][0] -= x else: a[i][0] += x k -= 1 i += 1 b = n*[0] for i in a: b[i[1]] = i[0] print(*b) s() ```
instruction
0
1,346
12
2,692
No
output
1
1,346
12
2,693
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,347
12
2,694
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` #Precomputation arr=[1] while len(arr)!=50: arr.append(arr[-1]*2+1) #input n,k=map(int,input().split()) l=arr[n-1] while k>1 and k!=l//2+1: l=l//2 if k>l: k-=l+1 n-=1 if k>1: print(n) else: print(1) ```
output
1
1,347
12
2,695
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,348
12
2,696
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` import sys from math import hypot N = 0 cos = 0.5 sin = -(3 ** 0.5) / 2 type = 0 sqrt2 = 2 ** 0.5 sin45 = 1 / (2 ** 0.5) size_po = 1 / (2 ** 0.5) sin_45 = -sin45 num = [6 / 19, 6 / 19, 11 / 9, 16 / 21, 20 / 32, 22 / 18, 8 / 10] def make_koch(n, x1, y1, x2, y2, painter): if n > 8: Window.SpinBox.setValue(8) return 0 if n == 0: painter.drawLine(x1, y1, x2, y2) else: x3, y3 = (x2 - x1) / 3 + x1, (y2 - y1) / 3 + y1 make_koch(n - 1, x1, y1, x3, y3, painter) x4, y4 = x2 - (x2 - x1) / 3, y2 - (y2 - y1) / 3 make_koch(n - 1, x4, y4, x2, y2, painter) # Now we are going to turn x3, y3, x4, y4 x5, y5 = (x4 - x3) * cos - (y4 - y3) * sin + x3, ((y4 - y3) * cos + (x4 - x3) * sin) + y3 make_koch(n - 1, x3, y3, x5, y5, painter) make_koch(n - 1, x5, y5, x4, y4, painter) def make_dima_tree(n, x1, y1, x2, y2, painter): painter.drawLine(x1, y1, x2, y2) if n > 0: # Now we are turning line x1, y1, x2, y2 length = hypot(x2 - x1, y2 - y1) sinb = (y2 - y1) / length cosb = (x2 - x1) / length x3, y3 = sin45 * cosb - sin45 * sinb, sin45 * cosb + sin45 * sinb x3 *= size_po * length y3 *= size_po * length x3 += x2 y3 += y2 make_dima_tree(n - 1, x2, y2, x3, y3, painter) x3, y3 = sin45 * cosb - sin_45 * sinb, sin45 * cosb + sin_45 * sinb x3 *= size_po * length y3 *= size_po * length x3 += x2 y3 += y2 make_dima_tree(n - 1, x2, y2, x3, y3, painter) def f(n, k): m = our[n] if m // 2 + 1 == k: return n return f(n - 1, k % (m // 2 + 1)) def make_dr(n, x1, y1, x2, y2, painter): if n == 0: painter.drawLine(x1, y1, x2, y2) else: # turning x1, y1, x2, y2 length = hypot(x2 - x1, y2 - y1) sinb = (y2 - y1) / length cosb = (x2 - x1) / length x2 -= x1 y2 -= y1 x3 = sin45 * cosb - sin45 * sinb y3 = sin45 * cosb + sin45 * sinb x3 *= size_po * length y3 *= size_po * length x3 += x1 y3 += y1 x2 += x1 y2 += y1 make_dr(n - 1, x1, y1, x3, y3, painter) make_dr(n - 1, x3, y3, x2, y2, painter) def make_dr2(n, x1, y1, x2, y2, painter): if n == 0: painter.drawLine(x1, y1, x2, y2) else: # turning x1, y1, x2, y2 length = hypot(x2 - x1, y2 - y1) sinb = (y2 - y1) / length cosb = (x2 - x1) / length x2 -= x1 y2 -= y1 x3 = sin45 * cosb - sin45 * sinb y3 = sin45 * cosb + sin45 * sinb x3 *= size_po * length y3 *= size_po * length x3 += x1 y3 += y1 x2 += x1 y2 += y1 make_dr2(n - 1, x1, y3, x3, y1, painter) make_dr2(n - 1, x3, y2, x2, y3, painter) def make_dr3(n, x1, y1, x2, y2, painter): if n == 0: painter.drawLine(x1, y1, x2, y2) else: # turning x1, y1, x2, y2 length = hypot(x2 - x1, y2 - y1) sinb = (y2 - y1) / length cosb = (x2 - x1) / length x2 -= x1 y2 -= y1 x3 = sin45 * cosb - sin45 * sinb y3 = sin45 * cosb + sin45 * sinb x3 *= size_po * length y3 *= size_po * length x3 += x1 y3 += y1 x2 += x1 y2 += y1 make_dr3(n - 1, x1, y1, x3, y3, painter) make_dr3(n - 1, x2, y2, x3, y3, painter) our = [0, 1] n, k = map(int, input().split()) class MyWidget(): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.depth = N def paintEvent(self, event): painter = QtGui.QPainter() painter.begin(self) if type == 0: make_koch(self.depth, 10, self.height() - 10, self.width(), self.height() - 10, painter) elif type == 1: make_dima_tree(self.depth, self.width() / 2, self.height(), self.width() / 2, self.height() / 2, painter) elif type == 2: make_birch(self.depth, self.width() / 4, self.height() - 170, self.width() / 4, self.height() / 2.5, painter) elif type == 3: make_tree(self.depth, self.width() / 2, self.height() - 10, self.width() / 2, self.height() * 2 / 3, painter) elif type == 4: make_dr(self.depth, self.width() / 3.7, self.height() / 4.1, self.width() / 3.7 * 2.7, self.height() / 4.1, painter) elif type == 6: make_dr3(self.depth, self.width() / 4.8, self.height() / 2.5, self.width() / 6 * 5, self.height() / 2.5, painter) elif type == 5: make_dr2(self.depth, self.width() / 55, self.height() / 4.7, self.width() / 55 * 54, self.height() / 4.7, painter) painter.end() def setValue(self, depth): if depth > 19: Window.SpinBox.setValue(19) if self.depth != depth: self.depth = depth self.repaint() while len(our) <= n + 1: our.append(our[-1] * 2 + 1) print(f(n, k)) class MyWindow(): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.resize(1910, 610) self.setWindowTitle("Painter demo") self.Widget = MyWidget(self) self.Widget.setGeometry(0, 0, 1900, 600) self.setMinimumSize(300, 300) self.SpinBox = QtGui.QSpinBox(self) self.SpinBox.setGeometry(10, 10, 100, 30) QtCore.QObject.connect(self.SpinBox, QtCore.SIGNAL("valueChanged(int)"), self.Widget.setValue) self.SpinBox.setValue(5) self.b = QtGui.QComboBox(self) self.b.addItem("Прямая Коха") self.b.addItem("Модифицированное дерево") self.b.addItem("Неведомая берёза") self.b.addItem("Дерево") self.b.addItem("Кривая Леви") self.b.addItem("Ваза") self.b.addItem("Кривая Дракона") self.b.setGeometry(130, 10, 250, 30) QtCore.QObject.connect(self.b, QtCore.SIGNAL("currentIndexChanged(int)"), self.temp) self.b.setCurrentIndex(5) # self.b.emit(QtCore.SIGNAL("currentIndexChanged()")) def temp(self, a): global type type = self.b.currentIndex() self.resizeEvent(0) self.Widget.repaint() def resizeEvent(self, event): Y = self.height() X = self.width() dx = 0 dy = 0 cons = num[type] if Y / X > cons: dy = (Y - X * cons) / 2 Y = X * cons elif Y / X < cons: dx = (X - Y / cons) / 2 X = Y / cons self.Widget.setGeometry(dx, dy, X, Y) ```
output
1
1,348
12
2,697
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,349
12
2,698
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` n, k = map(int, input().split()) if k % 2 == 1: print(1) else: power = 51 while k % 2 ** power != 0: power -= 1 print(power + 1) ```
output
1
1,349
12
2,699
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,350
12
2,700
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` lengthes = dict() lengthes[0] = 1 for k in range(1, 51): lengthes[k] = lengthes[k - 1] * 2 + 1 n, k = list(map(int, input().split())) def rec(n, k): if n == 0: return 1 if k <= lengthes[n - 1]: return rec(n - 1, k) if k == lengthes[n - 1] + 1: return n + 1 return rec(n - 1, k - 1 - lengthes[n - 1]) print(rec(n - 1, k)) ```
output
1
1,350
12
2,701
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,351
12
2,702
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` a, b = map(int, input().split()) c = 1 while (b % 2 == 0): b //= 2 c += 1 print(c) ```
output
1
1,351
12
2,703
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,352
12
2,704
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` y, x = map(int, input().split()) for i in range(50): if (x >> i) & 1: print(i + 1) break ```
output
1
1,352
12
2,705
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,353
12
2,706
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` def dfs(n, k): if n == 1: return 1 m = 1 << (n-1) if m == k: return n if m > k: return dfs(n-1, k) return dfs(n-1, k-m) N, K = map(int, input().split()) print(dfs(N, K)) ```
output
1
1,353
12
2,707
Provide tags and a correct Python 3 solution for this coding contest problem. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
instruction
0
1,354
12
2,708
Tags: binary search, bitmasks, constructive algorithms, implementation Correct Solution: ``` # n, a, b = list(map(lambda k: int(k), input().split(' '))) # s = input() def solveQ1(n, a, b, s): if s[a-1] == s[b-1]: return 0 c = s[b-1] n = len(s) min_dist = n for i in range(n): if s[i] == c: min_dist = min(abs(a-1-i), min_dist) return min_dist n, k = list(map(lambda i: int(i), input().split(' '))) def solveQ2(n, k): if n == 1: return 1 if k == pow(2, n-1): return n if k > pow(2, n-1): return solveQ2(n - 1, k - pow(2, n-1)) else: return solveQ2(n - 1, k) print(solveQ2(n, k)) # lst = [1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1] # for i in range(1, 63): # print(solveQ2(6, i)) # if solveQ2(6, i) != lst[i-1]: # print(solveQ2(6, i)) # print(6, i, lst[i-1]) ```
output
1
1,354
12
2,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1). Output Print single integer — the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. Submitted Solution: ``` import math n, k = list(map(int, input().split())) arr = reversed([int(math.pow(2, i)) for i in range(50)]) for index, num in enumerate(arr): if k % num == 0: print(50 - index) break ```
instruction
0
1,356
12
2,712
Yes
output
1
1,356
12
2,713
Provide a correct Python 3 solution for this coding contest problem. You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K. a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K? Constraints * All input values are integers. * 1 ≤ N ≤ 2 \times 10^5 * 1 ≤ K ≤ 10^9 * 1 ≤ a_i ≤ 10^9 Input Input is given from Standard Input in the following format: N K a_1 a_2 : a_N Output Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K. Examples Input 3 6 7 5 7 Output 5 Input 1 2 1 Output 0 Input 7 26 10 20 30 40 30 20 10 Output 13
instruction
0
1,556
12
3,112
"Correct Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor, cos, radians, pi, sin from operator import mul from functools import reduce from operator import mul sys.setrecursionlimit(2147483647) INF = 10 ** 13 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 10 ** 9 + 7 class BIT: def __init__(self, size): self.bit = [0] * size self.size = size self.total = 0 def add(self, i, w): x = i + 1 self.total += w while x <= self.size: self.bit[x - 1] += w x += x & -x return def sum(self, i): res = 0 x = i + 1 while x: res += self.bit[x - 1] x -= x & -x return res n, k = LI() A = IR(n) A = [0] + list(accumulate([a - k for a in A])) D = {v:i for i,v in enumerate(sorted(A))} bit = BIT(len(A)) c = 0 for a in A: c += bit.sum(D[a]) bit.add(D[a], 1) print(c) ```
output
1
1,556
12
3,113
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations: * add(i, x): add x to ai. * getSum(s, t): print the sum of as, as+1,...,at. Note that the initial values of ai (i = 1, 2, . . . , n) are 0. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 * If comi is 0, then 1 ≤ xi ≤ n, 0 ≤ yi ≤ 1000. * If comi is 1, then 1 ≤ xi ≤ n, 1 ≤ yi ≤ n. Input n q com1 x1 y1 com2 x2 y2 ... comq xq yq In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes add(xi, yi) and '1' denotes getSum(xi, yi). Output For each getSum operation, print the sum in a line. Example Input 3 5 0 1 1 0 2 2 0 3 3 1 1 2 1 2 2 Output 3 2
instruction
0
1,642
12
3,284
"Correct Solution: ``` import sys input = sys.stdin.readline class SegmentTree(): def __init__(self,arr,func=min,ie=2**63): self.n = 2**(len(arr)-1).bit_length() self.ie = ie self.func = func self.tree = [ie for _ in range(2*self.n)] for i in range(len(arr)): self.tree[self.n+i-1] = arr[i] for i in range(self.n-1)[::-1]: self.tree[i] = func(self.tree[2*i+1],self.tree[2*i+2]) def update(self,index,x): index += self.n-1 self.tree[index] = x while index>0: index = (index-1)//2 self.tree[index] = self.func(self.tree[2*index+1],self.tree[2*index+2]) def query(self,left,right): #開区間! if right <= left: return self.ie left += self.n-1 right += self.n-2 res = self.ie while right-left > 1: if left & 1 == 0: res = self.func(res,self.tree[left]) if right & 1 == 1: res = self.func(res,self.tree[right]) right -= 1 left = left//2 right = (right-1)//2 if left == right: res = self.func(res,self.tree[left]) else: res = self.func(self.func(res,self.tree[left]),self.tree[right]) return res N,Q = map(int,input().split()) A = [0 for _ in range(N)] st = SegmentTree(A,lambda x,y:x+y,0) ans = [] for _ in range(Q): com,x,y = map(int,input().split()) if com == 0: st.update(x-1,st.query(x-1,x)+y) else: ans.append(st.query(x-1,y)) print(*ans,sep='\n') ```
output
1
1,642
12
3,285
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,775
12
3,550
Tags: binary search, data structures Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class Binary_Indexed_Tree(): def __init__(self, n): self.n = n self.data = [0]*(n+1) def add(self, i, x): while i <= self.n: self.data[i] += x i += i & -i def get(self, i): return self.sum_range(i, i) def sum(self, i): ret = 0 while i: ret += self.data[i] i &= i-1 return ret def sum_range(self, l, r): return self.sum(r)-self.sum(l-1) def lower_bound(self, w): if w<=0: return 0 i = 0 k = 1<<(self.n.bit_length()) while k: if i+k <= self.n and self.data[i+k] < w: w -= self.data[i+k] i += k k >>= 1 return i+1 n = int(input()) a = list(map(int, input().split())) d = {j:i for i,j in enumerate(a)} BIT1 = Binary_Indexed_Tree(n) BIT2 = Binary_Indexed_Tree(n) BIT3 = Binary_Indexed_Tree(n) tentou = 0 ans = [] for i in range(n): tmp = 0 p = d[i+1] inv_p = n-p tentou += BIT1.sum(inv_p) BIT1.add(inv_p, 1) BIT2.add(p+1, 1) BIT3.add(p+1, p+1) m = i//2+1 mean = BIT2.lower_bound(i//2+1) tmp = 0 if i%2 == 0: tmp -= m*(m-1) else: tmp -= m*m tmp += tentou left = BIT3.sum_range(1, mean) right = BIT3.sum_range(mean, n) if i%2 == 0: left = mean*m - left right = right - mean*m else: left = mean*m - left right = right - mean*(m+1) tmp += left + right ans.append(tmp) print(*ans) ```
output
1
1,775
12
3,551
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,776
12
3,552
Tags: binary search, data structures Correct Solution: ``` #Author:MVP n = int(input()) arr = list(map(int,input().split())) trees = [0]*(1+n) dic = [0]*(n+1) ans = [0]*n def update(t,i,v): while i < len(t): t[i] += v i += lowbit(i) def lowbit(x): return x&-x def sum(t,i): ans = 0 while i>0: ans += t[i] i -= lowbit(i) return ans def getmid(arr,l1,flag): low,high = 1,n if l1%2 == 0 and flag: midv = l1//2 else: midv = l1//2+1 #print(midv,l1,dic[i]) while low <= high: mid = (low+high)//2 ret = sum(arr,mid) if ret >= midv: high = mid-1 else: low = mid+1 return low for i in range(n): dic[arr[i]]=i+1 for i in range(1,n+1): ans[i-1] += sum(trees,n)-sum(trees,dic[i]) if i>=2: ans[i-1] += ans[i-2] update(trees,dic[i],1) visited = [0]*(1+n) mid = 0 last = 0 for i in range(1,n+1): update(visited,dic[i],1) mid = getmid(visited,i,dic[i]>mid) tt = sum(visited,dic[i]) minus = min(tt-1,i-tt) tmp = abs(dic[i]-mid-(tt-sum(visited,mid)))- minus #print(dic[i],mid,tt,sum(visited,mid),minus,i) ans[i-1] += tmp+last last = tmp+last #print(ans,tmp,last,mid,i,dic[i]) print(" ".join(map(str,ans))) ```
output
1
1,776
12
3,553
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,777
12
3,554
Tags: binary search, data structures Correct Solution: ``` class Fenwick: def __init__(self, max_val): self.b = [0] * (max_val + 1) def update(self, i, increment): while i > 0 and i < len(self.b): self.b[i] += increment i += i & (-i) def sum(self, i): ans = 0 while i > 0: ans += self.b[i] i -= i & (-i) return ans def at_sum(self, k): a, b = 0, len(self.b) while a < b: mid = (a + b) // 2 if k <= self.sum(mid): b = mid else: a = mid + 1 return a def solve(p): pos = [0] * len(p) for i, e in enumerate(p): pos[e - 1] = i + 1 ans = 0 fenwick = Fenwick(len(p)) for i in range(1, len(p) + 1): p = pos[i - 1] fenwick.update(p, 1) r = fenwick.sum(p) m = (i + 1) // 2 if r <= m: m = m + (i % 2 == 0) ans += fenwick.at_sum(m) - p - m + 1 + i - r else: ans += p - fenwick.at_sum(m) + m - r yield ans input() a = [int(_) for _ in input().split()] print(*solve(a)) ```
output
1
1,777
12
3,555
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,778
12
3,556
Tags: binary search, data structures Correct Solution: ``` import heapq class DynamicMedian(): def __init__(self): self.l_q = [] self.r_q = [] self.l_sum = 0 self.r_sum = 0 def add(self, val): if len(self.l_q) == len(self.r_q): self.l_sum += val val = -heapq.heappushpop(self.l_q, -val) self.l_sum -= val heapq.heappush(self.r_q, val) self.r_sum += val else: self.r_sum += val val = heapq.heappushpop(self.r_q, val) self.r_sum -= val heapq.heappush(self.l_q, -val) self.l_sum += val def median_low(self): if len(self.l_q) + 1 == len(self.r_q): return self.r_q[0] else: return -self.l_q[0] def median_high(self): return self.r_q[0] def minimum_query(self): res1 = (len(self.l_q) * self.median_high() - self.l_sum) res2 = (self.r_sum - len(self.r_q) * self.median_high()) return res1 + res2 #Binary Indexed Tree (Fenwick Tree) class BIT(): def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def add(self, i, val): i = i + 1 while i <= self.n: self.bit[i] += val i += i & -i def _sum(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def sum(self, i, j): return self._sum(j) - self._sum(i) import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) bit = BIT(n) dm = DynamicMedian() memo = {} for i in range(n): memo[a[i] - 1] = i b = [0] * n for i in range(n): dm.add(memo[i]) b[i] = dm.minimum_query() - (i+1)**2 // 4 ans = [0] * n tmp = 0 for i in range(len(a)): bit.add(memo[i], 1) tmp += bit.sum(memo[i] + 1, n) ans[i] = tmp + b[i] print(*ans) ```
output
1
1,778
12
3,557
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,779
12
3,558
Tags: binary search, data structures Correct Solution: ``` from bisect import bisect_right, bisect_left # instead of AVLTree class BITbisect(): def __init__(self, InputProbNumbers): # 座圧 self.ind_to_co = [-10**18] self.co_to_ind = {} for ind, num in enumerate(sorted(list(set(InputProbNumbers)))): self.ind_to_co.append(num) self.co_to_ind[num] = ind+1 self.max = len(self.co_to_ind) self.data = [0]*(self.max+1) def __str__(self): retList = [] for i in range(1, self.max+1): x = self.ind_to_co[i] if self.count(x): c = self.count(x) for _ in range(c): retList.append(x) return "[" + ", ".join([str(a) for a in retList]) + "]" def __getitem__(self, key): key += 1 s = 0 ind = 0 l = self.max.bit_length() for i in reversed(range(l)): if ind + (1<<i) <= self.max: if s + self.data[ind+(1<<i)] < key: s += self.data[ind+(1<<i)] ind += (1<<i) if ind == self.max or key < 0: raise IndexError("BIT index out of range") return self.ind_to_co[ind+1] def __len__(self): return self._query_sum(self.max) def __contains__(self, num): if not num in self.co_to_ind: return False return self.count(num) > 0 # 0からiまでの区間和 # 左に進んでいく def _query_sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s # i番目の要素にxを足す # 上に登っていく def _add(self, i, x): while i <= self.max: self.data[i] += x i += i & -i # 値xを挿入 def push(self, x): if not x in self.co_to_ind: raise KeyError("The pushing number didnt initialized") self._add(self.co_to_ind[x], 1) # 値xを削除 def delete(self, x): if not x in self.co_to_ind: raise KeyError("The deleting number didnt initialized") if self.count(x) <= 0: raise ValueError("The deleting number doesnt exist") self._add(self.co_to_ind[x], -1) # 要素xの個数 def count(self, x): return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1) # 値xを超える最低ind def bisect_right(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_right(self.ind_to_co, x) - 1 return self._query_sum(i) # 値xを下回る最低ind def bisect_left(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_left(self.ind_to_co, x) if i == 1: return 0 return self._query_sum(i-1) import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) Ind = [0]*(N+1) for i, a in enumerate(A): Ind[a] = i+1 Bit = BITbisect(list(range(N+1))) ans = [0] Bit.push(Ind[1]) a = 0 for n in range(2, N+1): ind = Ind[n] f = Bit.bisect_left(ind) #print(Bit) l = len(Bit) if l%2 == 0: if f == l//2: a += l//2-l//2 elif f < l//2: p1 = Bit[l//2-1] a += (p1-ind-1) - (l//2-1) + l-f else: p2 = Bit[l//2] a += (ind-p2-1) - (l//2-1) + l-f else: p1 = Bit[l//2] #print(f, p1, ind, l) if f <= l//2: a += (p1-ind-1) - l//2 + l-f else: a += (ind-p1-1) - l//2 + l-f ans.append(a) Bit.push(ind) print(*ans, sep=" ") ```
output
1
1,779
12
3,559
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,780
12
3,560
Tags: binary search, data structures Correct Solution: ``` n = int(input()) a = [0] + list(map(int, input().split())) pos, pb, ps = [[0] * (n + 1) for x in range(3)] def add(bit, i, val): while i <= n: bit[i] += val i += i & -i def sum(bit, i): res = 0 while i > 0: res += bit[i] i -= i & -i return res def find(bit, sum): i, t = 0, 0 if sum == 0: return 0 for k in range(17, -1, -1): i += 1 << k if i <= n and t + bit[i] < sum: t += bit[i] else: i -= 1 << k return i + 1 for i in range(1, n + 1): pos[a[i]] = i invSum = 0 totalSum = 0 for i in range(1, n + 1): totalSum += pos[i] invSum += i - sum(pb, pos[i]) - 1 add(pb, pos[i], 1) add(ps, pos[i], pos[i]) mid = find(pb, i // 2) if i % 2 == 1: mid2 = find(pb, i // 2 + 1) seqSum = (i + 1) * (i // 2) // 2 else: mid2 = mid seqSum = i * (i // 2) // 2 leftSum = sum(ps, mid) rightSum = totalSum - sum(ps, mid2) print(rightSum - leftSum - seqSum + invSum, end=" ") ```
output
1
1,780
12
3,561
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
instruction
0
1,781
12
3,562
Tags: binary search, data structures Correct Solution: ``` import sys input = sys.stdin.buffer.readline # all operations are log(n) class bit: def __init__(self, n): self.n = n+1 self.mx_p = 0 while 1 << self.mx_p < self.n: self.mx_p += 1 self.a = [0]*(self.n) self.tot = 0 def add(self, idx, val): self.tot += val idx += 1 while idx < self.n: self.a[idx] += val idx += idx & -idx def sum_prefix(self, idx): tot = 0 idx += 1 while idx > 0: tot += self.a[idx] idx -= idx & -idx return tot def sum(self, l, r): return self.sum_prefix(r) - self.sum_prefix(l-1) # lowest idx such that sum_prefix(idx) = val else -1 if idx doesn't exist # idx is the idx in the underlying array (idx-1) def lower(self, val): if val > self.tot: return -1 tot = 0 idx = 0 for i in range(self.mx_p, -1, -1): if idx + (1<<i) < self.n and tot + self.a[idx + (1 << i)] < val: tot += self.a[idx + (1 << i)] idx += 1 << i return idx n = int(input()) p = list(map(int,input().split())) p = sorted([[p[i],i] for i in range(n)]) ones = bit(n+1) # 1 at positions ones_idx = bit(n+1) # indices at positions inversions = 0 for k in range(1,n+1): val, i = p[k-1] ones.add(i,1) ones_idx.add(i,i) inversions += ones.sum(i+1,n) num1l = (k+1)//2 num1r = k - num1l idxl = ones.lower((k+1)//2) idxr = idxl + 1 num0l = idxl+1 - num1l num0r = n - idxr - num1r suml = ones_idx.sum_prefix(idxl) sumr = ones_idx.tot - suml movel = idxl*(idxl+1)//2 - suml - (num0l - 1)*(num0l)//2 mover = (n-1-idxr)*(n-1-idxr+1)//2 - (num1r*(n-1) - sumr) - (num0r-1)*(num0r)//2 print(inversions + movel + mover) ```
output
1
1,781
12
3,563
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` n = int(input()) l = list(map(int, input().split())) i = 1 a = [0] while i < n: i1 = l.index(i) i2 = l.index(i + 1) if i2 > i1: a.append(a[-1] + i2 - i1 - 1) if a[-1] != a[-2]: temp = [] if len(l[:i1+1]) > 1: temp += l[:i1+1] else: temp += list(l[:i1+1]) temp += [l[i2]] if len(l[i1+1:i2]) > 1: temp += l[i1+1:i2] else: temp += list(l[i1+1:i2]) if len(l[i2+1:]) > 1: temp += l[i2+1:] else: temp += list(l[i2+1:]) l = temp else: a.append(a[-1] + i1 - i2) temp = [] if a[-1] != a[-2]: if len(l[:i2]) > 1: temp += l[:i2] else: temp += list(l[:i2]) if len(l[i2+1:i1]) > 1: temp += l[i2+1:i1] else: temp += list(l[i2+1:i1]) temp += [l[i1], l[i2]] if len(l[i1+1:]) > 1: temp += l[i1+1:] else: temp += list(l[i1+1:]) l = temp i += 1 print(*a, sep=' ') ```
instruction
0
1,782
12
3,564
No
output
1
1,782
12
3,565
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` from bisect import bisect_right, bisect_left # instead of AVLTree class BITbisect(): def __init__(self, InputProbNumbers): # 座圧 self.ind_to_co = [-10**18] self.co_to_ind = {} for ind, num in enumerate(sorted(list(set(InputProbNumbers)))): self.ind_to_co.append(num) self.co_to_ind[num] = ind+1 self.max = len(self.co_to_ind) self.data = [0]*(self.max+1) def __str__(self): retList = [] for i in range(1, self.max+1): x = self.ind_to_co[i] if self.count(x): c = self.count(x) for _ in range(c): retList.append(x) return "[" + ", ".join([str(a) for a in retList]) + "]" def __getitem__(self, key): key += 1 s = 0 ind = 0 l = self.max.bit_length() for i in reversed(range(l)): if ind + (1<<i) <= self.max: if s + self.data[ind+(1<<i)] < key: s += self.data[ind+(1<<i)] ind += (1<<i) if ind == self.max or key < 0: raise IndexError("BIT index out of range") return self.ind_to_co[ind+1] def __len__(self): return self._query_sum(self.max) def __contains__(self, num): if not num in self.co_to_ind: return False return self.count(num) > 0 # 0からiまでの区間和 # 左に進んでいく def _query_sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s # i番目の要素にxを足す # 上に登っていく def _add(self, i, x): while i <= self.max: self.data[i] += x i += i & -i # 値xを挿入 def push(self, x): if not x in self.co_to_ind: raise KeyError("The pushing number didnt initialized") self._add(self.co_to_ind[x], 1) # 値xを削除 def delete(self, x): if not x in self.co_to_ind: raise KeyError("The deleting number didnt initialized") if self.count(x) <= 0: raise ValueError("The deleting number doesnt exist") self._add(self.co_to_ind[x], -1) # 要素xの個数 def count(self, x): return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1) # 値xを超える最低ind def bisect_right(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_right(self.ind_to_co, x) - 1 return self._query_sum(i) # 値xを下回る最低ind def bisect_left(self, x): if x in self.co_to_ind: i = self.co_to_ind[x] else: i = bisect_left(self.ind_to_co, x) if i == 1: return 0 return self._query_sum(i-1) import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) Ind = [0]*(N+1) for i, a in enumerate(A): Ind[a] = i+1 Bit = BITbisect(list(range(N+1))) ans = [0] Bit.push(Ind[1]) a = 0 for n in range(2, N+1): ind = Ind[n] f = Bit.bisect_left(ind) #print(Bit) l = len(Bit) if l%2 == 0: if f == l//2: a += l//2 elif f < l//2: p1 = Bit[l//2-1] a += (p1-ind-1) - (l//2-1) + l-f else: p2 = Bit[l//2] a += (ind-p2-1) - (l//2-1) + l-f else: p1 = Bit[l//2] #print(f, p1, ind, l) if f <= l//2: a += (p1-ind-1) - l//2 + l-f else: a += (ind-p1-1) - l//2 + l-f ans.append(a) Bit.push(ind) print(*ans, sep=" ") ```
instruction
0
1,783
12
3,566
No
output
1
1,783
12
3,567
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` n = int(input()) permutation = [int(x) for x in input().split()] res = [] count = 0 for k in range(1, n+1): if k == 1: res.append(count) else: now = permutation.index(k) target = permutation.index(k-1) if now > target: while permutation.index(k) != permutation.index(k-1) + 1: permutation[now-1], permutation[now] = permutation[now], permutation[now-1] now -= 1 count += 1 elif now < target: while permutation.index(k) != permutation.index(k-1) + 1: permutation[now+1], permutation[now] = permutation[now], permutation[now+1] now += 1 count += 1 res.append(count) for i in res: print(i, end=" ") print() ```
instruction
0
1,784
12
3,568
No
output
1
1,784
12
3,569
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation. You need to find f(1), f(2), …, f(n). Input The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation. The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n). Output Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n. Examples Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0 Submitted Solution: ``` # Binary Indexed Tree (Fenwick Tree) class BIT(): def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def add(self, i, val): i = i + 1 while i <= self.n: self.bit[i] += val i += i & -i def _sum(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def sum(self, i, j): return self._sum(j) - self._sum(i) import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) bit = BIT(n) memo = {} for i in range(n): memo[a[i] - 1] = i ans = [0] * n tmp = 0 for i in range(len(a)): bit.add(memo[i], 1) tmp += bit.sum(memo[i] + 1, n) ans[i] = tmp print(*ans) ```
instruction
0
1,785
12
3,570
No
output
1
1,785
12
3,571
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define the function f of multiset a as the multiset of number of occurences of every number, that is present in a. E.g., f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}. Let's define f^k(a), as applying f to array a k times: f^k(a) = f(f^{k-1}(a)), f^0(a) = a. E.g., f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 2, 2\}. You are given integers n, k and you are asked how many different values the function f^k(a) can have, where a is arbitrary non-empty array with numbers of size no more than n. Print the answer modulo 998 244 353. Input The first and only line of input consists of two integers n, k (1 ≤ n, k ≤ 2020). Output Print one number — the number of different values of function f^k(a) on all possible non-empty arrays with no more than n elements modulo 998 244 353. Examples Input 3 1 Output 6 Input 5 6 Output 1 Input 10 1 Output 138 Input 10 2 Output 33 Submitted Solution: ``` from itertools import combinations_with_replacement from collections import Counter def check(n,k): for q in range(k): if q==0: x = [] for p in range(n,0,-1): for i in range(p): s = p-i for j in combinations_with_replacement([e for e in range(1,i+2)],s): l = list(j) if sum(l)==p: x.append(l) break # print(x) else: b = [] for l in x: a = [] c = dict(Counter(l)) # print(c) for i in c: a.append(c[i]) a.sort() if a not in b: b.append(a) x = b[:] return len(x) nk = input().split() n = int(nk[0]) k = int(nk[1]) print(check(n,k)) ```
instruction
0
1,786
12
3,572
No
output
1
1,786
12
3,573
Provide tags and a correct Python 3 solution for this coding contest problem. Eugene likes working with arrays. And today he needs your help in solving one challenging task. An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0. Help Eugene to calculate the number of nonempty good subarrays of a given array a. Input The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a. Output Output a single integer — the number of good subarrays of a. Examples Input 3 1 2 -3 Output 5 Input 3 41 -41 41 Output 3 Note In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0. In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
instruction
0
1,788
12
3,576
Tags: binary search, data structures, implementation, two pointers Correct Solution: ``` from collections import defaultdict def solve(arr, n): ma = defaultdict(list) ma[0].append(-1) p = [arr[i] for i in range(n)] for i in range(1, n): p[i] += p[i-1] cnt, lst = 0, -1 for i in range(n): if ma[p[i]]: lst = max(lst, ma[p[i]][-1]+1) #print(i, lst, p[i]) cnt += (i-lst) ma[p[i]].append(i) return cnt def main(): n = int(input()) arr = list(map(int, input().strip().split())) ret = solve(arr, n) print(ret) if __name__ == "__main__": main() ```
output
1
1,788
12
3,577