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.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | instruction | 0 | 70,137 | 12 | 140,274 |
Tags: binary search, greedy, sortings
Correct Solution:
```
n, k = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
exclude = set()
ans = 0
a.sort()
for i in a:
if i not in exclude:
exclude.add(i*k)
ans += 1
print(ans)
``` | output | 1 | 70,137 | 12 | 140,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | instruction | 0 | 70,138 | 12 | 140,276 |
Tags: binary search, greedy, sortings
Correct Solution:
```
from collections import OrderedDict
def kmultiple(x, k):
c = 0
for e in x:
if x[e] != 0:
c += 1
if e*k in x:
x[e*k] = 0
return c
if __name__ == '__main__':
x = OrderedDict()
_, k = input().split()
k = int(k)
lst = [int(x) for x in input().split()]
lst.sort()
for e in lst:
x[e] = 1
print(kmultiple(x, k))
``` | output | 1 | 70,138 | 12 | 140,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
def sfun(n, k, lst):
s = {}
for i in range(n):
if lst[i] * k in s:
continue
s[lst[i]] = 1
return len(s)
N, K = [int(j) for j in input().split()]
a = [int(x) for x in input().split()]
print(sfun(N, K, sorted(a, reverse=True)))
``` | instruction | 0 | 70,140 | 12 | 140,280 |
Yes | output | 1 | 70,140 | 12 | 140,281 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
n, k = map(int, input().split())
seq_set = set()
for e in sorted(int(c) for c in input().split()):
if e % k or e // k not in seq_set:
seq_set.add(e)
print(len(seq_set))
``` | instruction | 0 | 70,141 | 12 | 140,282 |
Yes | output | 1 | 70,141 | 12 | 140,283 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
from collections import *
n, k = map(int, input().split())
a, ans, mem = sorted(map(int, input().split())), 0, defaultdict(int)
for i in a:
if i % k == 0 and not mem[i // k] or i % k:
mem[i] = 1
ans += 1
print(ans)
``` | instruction | 0 | 70,142 | 12 | 140,284 |
Yes | output | 1 | 70,142 | 12 | 140,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
n, k = (int(x) for x in input().split())
a = {int(x) for x in input().split()}
exclude = set()
ans = 0
for i in a:
if i not in exclude:
exclude.add(i)
exclude.add(i*k)
exclude.add(i//k)
ans += 1
print(ans)
``` | instruction | 0 | 70,143 | 12 | 140,286 |
No | output | 1 | 70,143 | 12 | 140,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
# from sys import stdin
# input = stdin.readline
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,7)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
def seive():
prime=[1 for i in range(10**6+1)]
prime[0]=0
prime[1]=0
for i in range(10**6+1):
if(prime[i]):
for j in range(2*i,10**6+1,i):
prime[j]=0
return prime
n,k=L()
A=L()
if k==1:
print(1)
exit()
s1=set()
s2=set()
d={}
for ele in A:
s1.add(ele)
d[ele]=d.get(ele,0)+1
for ele in sorted(list(s1)):
if ele%k==0 and ele//k in s2:
continue
s2.add(ele)
ans=0
for ele in s2:
ans+=d[ele]
print(ans)
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | instruction | 0 | 70,145 | 12 | 140,290 |
No | output | 1 | 70,145 | 12 | 140,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Submitted Solution:
```
n, k = map(int, input().split())
s = list(map(int, input().split()))
s = sorted(s)
my_dict = {}
for i in s:
if i not in my_dict:
my_dict[i] = 1
count = 0
for i in s:
if i*k in my_dict:
s.remove(i*k)
count += 1
print(len(s))
``` | instruction | 0 | 70,146 | 12 | 140,292 |
No | output | 1 | 70,146 | 12 | 140,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polar bears like unique arrays — that is, arrays without repeated elements.
You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, with the following conditions for all i (1 ≤ i ≤ n):
* ai, bi are non-negative integers;
* si = ai + bi .
Ideally, a and b should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length n to be almost unique, if and only if it can be turned into a unique array by removing no more than <image> entries.
For example, the array [1, 2, 1, 3, 2] is almost unique because after removing the first two entries, it becomes [1, 3, 2]. The array [1, 2, 1, 3, 1, 2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array.
So, your task is to split the given unique array s into two almost unique arrays a and b.
Input
The first line of the input contains integer n (1 ≤ n ≤ 105).
The second line contains n distinct integers s1, s2, ... sn (0 ≤ si ≤ 109).
Output
If it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array a. In the third line, print the array b. There may be more than one solution. Any of them will be accepted.
If it is impossible to split s into almost unique arrays a and b, print "NO" (without quotes) in the first line.
Examples
Input
6
12 5 8 3 11 9
Output
YES
6 2 6 0 2 4
6 3 2 3 9 5
Note
In the sample, we can remove the first two entries from a and the second entry from b to make them both unique.
Submitted Solution:
```
'''input
6
12 5 8 3 11 9
'''
'''
nho chuyen sang python 3
'''
# import math
n = int(input())
cnt = 0
s = []
for it in input().split():
s.append((int(it), cnt))
cnt += 1
s.sort()
a = [0] * n
b = [0] * n
for i in range(0, n // 3):
a[s[i][1]] = i
b[s[i][1]] = s[i][0] - i
for i in range(n // 3, 2 * n // 3):
a[s[i][1]] = s[i][0] - i
b[s[i][1]] = i
for i in range(2 * n // 3, n):
a[s[i][1]] = s[i][0] - i
b[s[i][1]] = n - i - 1
print("YES")
for i in a:
print(i, end=' ')
print()
for i in b:
print(i, end=' ')
print()
``` | instruction | 0 | 70,147 | 12 | 140,294 |
No | output | 1 | 70,147 | 12 | 140,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polar bears like unique arrays — that is, arrays without repeated elements.
You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, with the following conditions for all i (1 ≤ i ≤ n):
* ai, bi are non-negative integers;
* si = ai + bi .
Ideally, a and b should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length n to be almost unique, if and only if it can be turned into a unique array by removing no more than <image> entries.
For example, the array [1, 2, 1, 3, 2] is almost unique because after removing the first two entries, it becomes [1, 3, 2]. The array [1, 2, 1, 3, 1, 2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array.
So, your task is to split the given unique array s into two almost unique arrays a and b.
Input
The first line of the input contains integer n (1 ≤ n ≤ 105).
The second line contains n distinct integers s1, s2, ... sn (0 ≤ si ≤ 109).
Output
If it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array a. In the third line, print the array b. There may be more than one solution. Any of them will be accepted.
If it is impossible to split s into almost unique arrays a and b, print "NO" (without quotes) in the first line.
Examples
Input
6
12 5 8 3 11 9
Output
YES
6 2 6 0 2 4
6 3 2 3 9 5
Note
In the sample, we can remove the first two entries from a and the second entry from b to make them both unique.
Submitted Solution:
```
'''input
6
12 5 8 3 11 9
'''
'''
nho chuyen sang python 3
'''
# import math
n = int(input())
s = [int(i) for i in input().split()]
a = []
b = []
for i in range(0, n // 3):
a.append(i)
b.append(s[i] - a[i])
for i in range(n // 3, 2 * n // 3):
a.append(s[i] - i)
b.append(i)
for i in range(2 * n // 3, n):
b.append(n - i - 1)
a.append(s[i] - b[i])
print("YES")
for i in a:
print(i, end=' ')
print()
for i in b:
print(i, end=' ')
print()
``` | instruction | 0 | 70,148 | 12 | 140,296 |
No | output | 1 | 70,148 | 12 | 140,297 |
Provide a correct Python 3 solution for this coding contest problem.
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq K \leq 10^5$
* $1 \leq a_i \leq 10^5$
Input
The input is given in the following format.
$N$ $K$
$a_1$ $a_2$ ... $a_N$
Output
Print the smallest sub-array size in a line.
Examples
Input
6 2
4 1 2 1 3 5
Output
2
Input
6 3
4 1 2 1 3 5
Output
3
Input
3 4
1 2 3
Output
0 | instruction | 0 | 70,724 | 12 | 141,448 |
"Correct Solution:
```
class SegmentTree():
def __init__(self, arr, func=min, ie=2**63):
self.h = (len(arr) - 1).bit_length()
self.n = 2**self.h
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] = arr[i]
for i in range(1, self.n)[::-1]:
self.tree[i] = func(self.tree[2 * i], self.tree[2 * i + 1])
def set(self, idx, x):
idx += self.n
self.tree[idx] = x
while idx:
idx >>= 1
self.tree[idx] = self.func(self.tree[2 * idx], self.tree[2 * idx + 1])
def query(self, lt, rt):
lt += self.n
rt += self.n
vl = vr = self.ie
while rt - lt > 0:
if lt & 1:
vl = self.func(vl, self.tree[lt])
lt += 1
if rt & 1:
rt -= 1
vr = self.func(self.tree[rt], vr)
lt >>= 1
rt >>= 1
return self.func(vl, vr)
N, K = map(int, input().split())
A = list(map(int, input().split()))
res = N + 1
st = SegmentTree([0] * K)
rt = 0
for lt in range(N):
while rt < N and st.tree[1] == 0:
if A[rt] <= K:
st.set(A[rt] - 1, st.query(A[rt] - 1, A[rt]) + 1)
rt += 1
if st.tree[1] != 0:
res = min(res, rt - lt)
if A[lt] <= K:
st.set(A[lt] - 1, st.query(A[lt] - 1, A[lt]) - 1)
print(res if res <= N else 0)
``` | output | 1 | 70,724 | 12 | 141,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,833 | 12 | 141,666 |
Tags: brute force, math, sortings
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,inf
from collections import deque
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(x)
hg=lambda x,y:((y+x-1)//x)*x
pw=lambda x:1 if x==1 else 1+pw(x//2)
chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False
N=inf
n,k=R()
a=[deque() for i in range(2*10**5+7)]
v=[0]*(2*10**5+7)
sm=[0]*(2*10**5+7)
for i in sorted(R(),reverse=True):
a[i].appendleft(0)
v[i]+=1
if v[i]>k:
v[i]=k
sm[i]-=a[i].pop()
stp=0
while i:
i//=2
stp+=1
a[i].appendleft(stp)
v[i]+=1
sm[i]+=stp
if v[i]>k:
sm[i]-=a[i].pop()
v[i]=k
ans=inf
for i in range(2*10**5+7):
if v[i]==k:ans=min(sm[i],ans)
print(ans)
``` | output | 1 | 70,833 | 12 | 141,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,834 | 12 | 141,668 |
Tags: brute force, math, sortings
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
#-------------------------------------------------------------------------
n,k=map(int,input().split())
a=list(map(int,input().split()))
count=dict()
div=dict()
a.sort()
for i in range (n):
j=0
while a[i]>0:
if a[i] in count:
if count[a[i]]<k:
count[a[i]]+=1
div[a[i]]+=j
else:
count[a[i]]=1
div[a[i]]=j
a[i]//=2
j+=1
if a[i] in count:
if count[a[i]]<k:
count[a[i]]+=1
div[a[i]]+=j
else:
count[a[i]]=1
div[a[i]]=j
#print(count)
#print(div)
m=10**9
for i in count:
if count[i]==k:
m=min(m,div[i])
print(m)
``` | output | 1 | 70,834 | 12 | 141,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,835 | 12 | 141,670 |
Tags: brute force, math, sortings
Correct Solution:
```
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
f = {}
for i in a:
it = 0
while i>0:
if i in f:
f[i].append(it)
else:
f[i] = [it]
i//=2
it+=1
s = 1e10
for i in f:
if len(f[i])>=m:
s = min(s,sum(sorted(f[i])[:m]))
print(s)
``` | output | 1 | 70,835 | 12 | 141,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,836 | 12 | 141,672 |
Tags: brute force, math, sortings
Correct Solution:
```
b = {}
n, k = map(int, input().split())
a = list(map(int, input().split()))
b[0] = []
for x in a:
j = 0
while(x > 0):
if(x in b):
b[x].append(j)
else:
b[x] = [j]
x //= 2
j += 1
b[0].append(j)
ans = 10**10
for i in b:
b[i].sort()
if(len(b[i]) >= k):
ans = min(sum(b[i][:k]), ans)
print(ans)
``` | output | 1 | 70,836 | 12 | 141,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,837 | 12 | 141,674 |
Tags: brute force, math, sortings
Correct Solution:
```
import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase
# def gcd(a,b):
# if b==0:
# return a
# else:
# return gcd(b,a%b)
def inar():
return [int(k) for k in input().split()]
def main():
# mod=10**9+7
#for _ in range(int(input())):
#n=int(input())
n,k=map(int,input().split())
arr=inar()
dic=defaultdict(list)
cnt=0
for i in range(n):
cnt=0
#if len(dic[arr[i]]) == 0:
dic[arr[i]].append(cnt)
while 1:
arr[i]//=2
cnt+=1
#if len(dic[arr[i]])==0:
dic[arr[i]].append(cnt)
if arr[i]==0:
break
res=10**9
#print(dic)
for key,item in dic.items():
if len(item)<k:
continue
else:
item.sort()
sm=0
for i in range(k):
sm+=item[i]
res=min(res,sm)
print(res)
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")
if __name__ == "__main__":
main()
``` | output | 1 | 70,837 | 12 | 141,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,838 | 12 | 141,676 |
Tags: brute force, math, sortings
Correct Solution:
```
from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
n,z=invr()
l=inlt()
dp=[[] for _ in range(200001)]
for each in l:
k=each
curr=0
while(k>0):
dp[k].append(curr)
k=k//2
curr+=1
ans=10**30
for i in range(len(dp)):
dp[i]=sorted(dp[i])
for each in dp:
if len(each)>=z:
sm=0
for j in range(z):
sm+=each[j]
ans=min(ans,sm)
print(ans)
``` | output | 1 | 70,838 | 12 | 141,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,839 | 12 | 141,678 |
Tags: brute force, math, sortings
Correct Solution:
```
n,k = map(int,input().split())
l = list(map(int,input().split()))
count = [0]*((2*(10**5)) + 1)
no = [0]*((2*(10**5)) + 1)
ans = float('inf')
l.sort()
for i in l:
c = 0
e = 0
while i>0:
if no[i]<k:
count[i]+=c
no[i]+=1
c+=1
i = i//2
if i == 0:
if no[i]<k:
count[i]+=c
no[i]+=1
for i in range(len(count)):
if no[i]>=k:
ans = min(ans,count[i])
print(ans)
``` | output | 1 | 70,839 | 12 | 141,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0 | instruction | 0 | 70,840 | 12 | 141,680 |
Tags: brute force, math, sortings
Correct Solution:
```
n, k = map(int, input().split())
l = list(map(int, input().split()))
b = [[] for i in range(2*10**5+1)]
for a in l:
cnt = 0
while (a > 0):
b[a].append(cnt)
cnt += 1
a = a // 2
ans = 1000000000
for x in b:
if len(x) >= k:
x = sorted(x)
ans = min(ans, sum(x[:k]))
print(ans)
``` | output | 1 | 70,840 | 12 | 141,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
from sys import stdin
input=stdin.readline
n,k=map(int,input().split())
a=list(map(int,input().split()))
vals=[[] for i in range(2*10**5+1)]
b=[a[i] for i in range(n)]
s=set()
for i in range(n):
cnt=0
while b[i]>0:
s.add(b[i])
vals[b[i]].append(cnt)
b[i]//=2
cnt+=1
s=list(s)
ans=10**18
for x in s:
vals[x].sort()
if len(vals[x])>=k:
ans=min(ans,sum(vals[x][:k]))
print(ans)
``` | instruction | 0 | 70,841 | 12 | 141,682 |
Yes | output | 1 | 70,841 | 12 | 141,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
n,k = map(int,input().split())
a = list(map(int,input().split()))
arr = [[] for _ in range(int(2e5 +1))]
for j in a:
i = 0
while j>0:
arr[j].append(i)
i += 1
j //= 2
arr[j].append(i)
mn = -1
for i in arr:
if len(i)>=k:
sk = sum(sorted(i)[:k])
if mn>sk or mn == -1:
mn = sk
print(mn)
``` | instruction | 0 | 70,842 | 12 | 141,684 |
Yes | output | 1 | 70,842 | 12 | 141,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
from collections import defaultdict
hash1 = defaultdict(int)
hash2 = defaultdict(list)
n,k = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
ans = 10**18
for i in l:
j = i
count = 0
while True:
hash2[j].append(count)
if j == 0:
break
j//=2
count+=1
for i in hash2.keys():
if len(hash2[i])>=k:
hash2[i].sort()
ans = min(ans,sum(hash2[i][:k]))
print(ans)
``` | instruction | 0 | 70,843 | 12 | 141,686 |
Yes | output | 1 | 70,843 | 12 | 141,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
n, k = map(int, input().split())
arr = [int(z) for z in input().split()]
moves = {}
for i in range(n):
l = arr[i]
m = 0
while l:
if not moves.get(l):
moves[l] = []
moves[l].append(m)
l //= 2
m += 1
res = 10**18
for i in moves:
moves[i].sort()
if len(moves[i]) < k:
continue
res = min(res, sum(moves[i][:k]))
print(res)
``` | instruction | 0 | 70,844 | 12 | 141,688 |
Yes | output | 1 | 70,844 | 12 | 141,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())
n,k = rrd()
a = list(rrd())
cnt = [0]*400005
a.sort()
print(a)
for i in a:
cnt[i] += 1
for i in range(400002):
if i:
cnt[i] += cnt[i-1]
import math
ans = math.inf
for i in a:
ct = cnt[i]-cnt[i-1]
if ct>=k:
print(0)
exit(0)
if cnt[200000] - cnt[i*2 - 1] >= k - ct:
now = k
tot = 0
l = i
r = i
st = 0
while now > 0:
if r>200000 or l>200000:
tot = math.inf
break
p = min(cnt[r] - cnt[l-1],now)
now -= p
tot += st*p
r = r*2+1
l = l*2
if r>200000:
r = 200000
st += 1
ans = min(ans,tot)
print(ans)
``` | instruction | 0 | 70,845 | 12 | 141,690 |
No | output | 1 | 70,845 | 12 | 141,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk
"""
import sys
input = sys.stdin.buffer.readline
def solution():
n,k=map(int,input().split())
l=list(map(int,input().split()))
val=[0]*1000001
op=[0]*1000001
m=2e9
for i in range(n):
val[l[i]]+=1
for i in range(n):
cnt=0
x=l[i]
while x>0:
if val[x]>=k:
m=min(m,op[x])
cnt+=1
x//=2
op[x]+=cnt
val[x]+=1
print(m)
solution()
``` | instruction | 0 | 70,846 | 12 | 141,692 |
No | output | 1 | 70,846 | 12 | 141,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
#sys.setrecursionlimit(100000)
#^^^TAKE CARE FOR MEMORY LIMIT^^^
import random
def main():
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def binary(n):
return (bin(n).replace("0b", ""))
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countcon(s, i):
c = 0
ch = s[i]
for i in range(i, len(s)):
if (s[i] == ch):
c += 1
else:
break
return (c)
def lis(arr):
n = len(arr)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum = 0
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
def isSubSequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def maxfac(n):
root = int(n ** 0.5)
for i in range(2, root + 1):
if (n % i == 0):
return (n // i)
return (n)
def p2(n):
c=0
while(n%2==0):
n//=2
c+=1
return c
def seive(n):
primes=[True]*(n+1)
primes[1]=primes[0]=False
i=2
while(i*i<=n):
if(primes[i]==True):
for j in range(i*i,n+1,i):
primes[j]=False
i+=1
pr=[]
for i in range(0,n+1):
if(primes[i]):
pr.append(i)
return pr
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def denofactinverse(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return (pow(fac,m-2,m))
def numofact(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return(fac)
def sod(n):
s=0
while(n>0):
s+=n%10
n//=10
return s
n,k=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
val=[[] for i in range(0,200010)]
for i in range(0,n):
cv=l[i]
it=0
while(l[i]>0):
val[l[i]].append(it)
it+=1
l[i]//=2
ans=10*20
for i in range(0,len(val)):
if(len(val[i])>=k):
val[i].sort()
ans=min(ans,sum(val[i][:k]))
print(ans)
``` | instruction | 0 | 70,847 | 12 | 141,694 |
No | output | 1 | 70,847 | 12 | 141,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
n,k = map(int,input().split())
a = list(map(int,input().split()))
cnt = [[0]*20 for _ in [0]*200001]
for e in a:
k = 0
while True:
cnt[e][k] += 1
if e == 0:
break
e = e//2
k += 1
res = 10**9
for i in range(200001):
tmp = 0
p = 0
for j in range(20):
if cnt[i][j]+p >= k:
tmp += (k-p)*j
p = k
break
else:
p += cnt[i][j]
tmp += cnt[i][j]*j
if p == k:
res = min(res,tmp)
print(res)
if __name__ =='__main__':
main()
``` | instruction | 0 | 70,848 | 12 | 141,696 |
No | output | 1 | 70,848 | 12 | 141,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,862 | 12 | 141,724 |
Tags: brute force, greedy, math
Correct Solution:
```
import sys
n = int(sys.stdin.readline().split()[0])
a = list(map(int, sys.stdin.readline().split()))
b = [x for x in a]
idx = -1
while max(b) != 0:
c = [x&1 for x in b]
if c.count(1) == 1:
idx = c.index(1)
b = [x>>1 for x in b]
if idx >= 0:
tmp = a[idx]
del a[idx]
sys.stdout.write(str(tmp) + " ")
if len(a) >= 1:
sys.stdout.write(" ".join(map(str, a)))
else:
sys.stdout.write(" ".join(map(str, a)))
``` | output | 1 | 70,862 | 12 | 141,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,863 | 12 | 141,726 |
Tags: brute force, greedy, math
Correct Solution:
```
n=int(input())
arr=[[] for i in range(32)]
l=input().split()
li=[int(i) for i in l]
for i in li:
for j in range(32):
if(i&(1<<j)):
arr[j].append(i)
maxa=-1
for i in range(31,-1,-1):
if(len(arr[i])==1):
maxa=arr[i][0]
break
if(maxa==-1):
for i in li:
print(i,end=" ")
else:
done=0
print(maxa,end=" ")
for i in li:
if(i==maxa and done==0):
done=1
continue
print(i,end=" ")
print()
``` | output | 1 | 70,863 | 12 | 141,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,864 | 12 | 141,728 |
Tags: brute force, greedy, math
Correct Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
l=sorted(a,reverse=True)
x=l[0]
bits=0
while(x>0):
x= x>>1
bits+=1
num=0
for i in range(bits):
count=0
ind=0
z= 1<<bits-i-1
for j in range(len(a)):
if z&l[j] == z:
count+=1
ind=j
if count>1:
break
if count==1:
num=ind
break
l[num],l[0]=l[0],l[num]
print(*l)
``` | output | 1 | 70,864 | 12 | 141,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,865 | 12 | 141,730 |
Tags: brute force, greedy, math
Correct Solution:
```
import math
def main():
n = int(input())
a = list(map(int, input().split()))
lst = [[] for _ in range(30)]
for i in a:
nm = bin(i)[2:]
o = 0
for k in range(len(nm) - 1, -1, -1):
if nm[k] == "1":
lst[o].append(i)
o += 1
for i in range(len(lst) - 1, -1, -1):
if len(lst[i]) == 1:
for k in range(0, len(a)):
if (a[k] & (2 ** i)) == (2 ** i):
a[0], a[k] = a[k], a[0]
for c in a:
print(c, end=" ")
return
for c in a:
print(c, end=" ")
if __name__ == "__main__":
t = 1
for i in range(t):
main()
``` | output | 1 | 70,865 | 12 | 141,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,866 | 12 | 141,732 |
Tags: brute force, greedy, math
Correct Solution:
```
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int,input().split()))
bitc = [0]*32
for v in a:
i = 0
while v:
if v&1:
bitc[i]+=1
i+=1
v >>= 1
bits = 0
for i in range(32):
if bitc[i]==1:
bits = i
st = 0
for i in range(n):
if 1<<bits & a[i]:
st = i
break
s = a[st]
a = a[:st]+a[st+1:]
print(s,*a)
``` | output | 1 | 70,866 | 12 | 141,733 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,867 | 12 | 141,734 |
Tags: brute force, greedy, math
Correct Solution:
```
from sys import *
from math import *
from bisect import *
n=int(stdin.readline())
a=list(map(int,stdin.readline().split()))
for i in range(32,-1,-1):
s=x=0
for j in range(n):
if 1<<i & a[j]!=0:
x=j
s+=1
if s==1:
break
a[0],a[x]=a[x],a[0]
print(*a)
``` | output | 1 | 70,867 | 12 | 141,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,868 | 12 | 141,736 |
Tags: brute force, greedy, math
Correct Solution:
```
n = int(input())
vals = list(map(int, input().split()))
pref, suff = [0] * (n + 1), [0] * (n + 1)
for i in range(n):
pref[i + 1] = pref[i] | vals[i]
suff[n - i - 1] = suff[n - i] | vals[n - i - 1]
ret = (-float('inf'), -float('inf'))
for i, a in enumerate(vals):
b = pref[i] | suff[i + 1]
ret = max(ret, ((a | b) ^ b, i))
print(*[vals[ret[1]]] + [v for i, v in enumerate(vals) if i != ret[1]])
``` | output | 1 | 70,868 | 12 | 141,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 70,869 | 12 | 141,738 |
Tags: brute force, greedy, math
Correct Solution:
```
from math import ceil ,log2
def f(a):
mx=0
item=None
pref=[~a[0]]
for i in range(1,len(a)):
pref.append(pref[-1]&(~a[i]))
suf=[~a[-1]]
for i in range(len(a)-1-1,-1,-1):
suf.append(suf[-1]&(~a[i]))
suf=suf[::-1]
for i in range(len(a)):
ll=(1<<60)-1
rr=(1<<60)-1
if i !=0:
ll=pref[i-1]
if i!=len(a)-1:
rr=suf[i+1]
tt=(ll&rr)&a[i]
if tt>=mx:
mx=tt
item=i
mx=a.pop(item)
return [mx]+a
n = input()
row = list(map(int, input().strip().split()))
print(*f(row))
# print(t)
``` | output | 1 | 70,869 | 12 | 141,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n=int(input())
arr=list(map(int,input().split()))
ans=-1
for i in range(32,-1,-1):
s=0
ans=-1
for j in arr:
if (1<<i)&j!=0:
ans=j
s+=1
if s==1:
break
lis=[]
if ans!=-1:
lis.append(ans)
for j in arr:
if j!=ans:
lis.append(j)
else:
ans=-1
print(" ".join(str(x) for x in lis))
``` | instruction | 0 | 70,870 | 12 | 141,740 |
Yes | output | 1 | 70,870 | 12 | 141,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
input()
a=input().split()
print(a.pop(next((x for x in zip(*(f'{int(x):30b}'for
x in a))if x.count('1')==1),'1').index('1')),*a)
#JSR
``` | instruction | 0 | 70,871 | 12 | 141,742 |
Yes | output | 1 | 70,871 | 12 | 141,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
ans=[]
for i in range(32,-1,-1):
flag=-1
badflag=0
for j in range(n):
if a[j]&1<<i:
if flag==-1:
flag=j
else:
badflag=1
if badflag==1:
break
if flag!=-1 and badflag==0:
ans.append(str(a[flag]))
for j in range(n):
if j!=flag:
ans.append(str(a[j]))
break
if len(ans)==0:
for i in range(n):
ans.append(str(a[i]))
print(' '.join(ans))
``` | instruction | 0 | 70,872 | 12 | 141,744 |
Yes | output | 1 | 70,872 | 12 | 141,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
cnt=[0]*30
for i in range(n):
for j in range(30):
if l[i]&(1<<j):
cnt[j]+=1
options=[i for i in range(n)]
for i in range(29,-1,-1):
newoptions=[]
if cnt[i]==1:
for idx in options:
if l[idx]&(1<<i):
newoptions.append(idx)
if len(newoptions)>0:
options=newoptions
print(l[options[0]],end=" ")
for i in range(n):
if i!=options[0]:
print(l[i],end=" ")
``` | instruction | 0 | 70,873 | 12 | 141,746 |
Yes | output | 1 | 70,873 | 12 | 141,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
from itertools import permutations
n=int(input())
arr=list(map(int,input().split()))
def anu(x,y):
a=(x|y)-y
return a
perm=permutations(arr)
max_val=0
my_arr=[]
for j in list(perm):
parr=list(j)
x=parr[0]
for i in range(1,n):
x=anu(x,parr[i])
if x>max_val:
max_val=x
my_arr=parr
if x==0:
print(" ".join(map(str,arr)))
else:
print(" ".join(map(str,my_arr)))
``` | instruction | 0 | 70,874 | 12 | 141,748 |
No | output | 1 | 70,874 | 12 | 141,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input().strip())
A = list(map(int, input().strip().split()))
A_set = list(set(A))
print("list1",A_set)
if (len(A) == 1) or (len(A_set) == 1):
print(" ".join(list(map(str, A))))
else:
m = len(A_set)
prefix = [~A_set[0]] * m
postfix = [~A_set[-1]] * m
for i in range(1, m):
prefix[i] = prefix[i - 1] & (~A_set[i])
for i in range(m - 2, -1, -1):
postfix[i] = postfix[i + 1] & (~A_set[i])
max_ans = -1
index = -1
for i in range(1, m - 1):
ans = A_set[i] & prefix[i - 1] & postfix[i + 1]
if ans > max_ans:
max_ans = ans
index = i
# For 0
ans = A_set[0] & postfix[1]
if ans > max_ans:
max_ans = ans
index = 0
# For m-1
ans = A_set[m - 1] & prefix[m - 2]
if ans > max_ans:
max_ans = ans
index = m - 1
ans = A_set[index]
A.remove(ans)
A.insert(0, ans)
print("pref",prefix)
print("suff",postfix)
print(" ".join(list(map(str, A))))
# print(max_ans)
``` | instruction | 0 | 70,875 | 12 | 141,750 |
No | output | 1 | 70,875 | 12 | 141,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
print(*arr)
exit(0)
suff = list(reversed(suff))
l = arr[0]&suff[1]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
piv = arr[0]
else:
piv = arr[-1]
print(piv)
for i in range(1, n-1):
print('ll')
prev = curr
curr = max(curr, pre[i-1]&arr[i]&suff[i+1])
if prev != curr:
piv = arr[i]
ans = [piv]
for i in arr:
if i != piv:
ans.append(i)
print(*ans)
``` | instruction | 0 | 70,876 | 12 | 141,752 |
No | output | 1 | 70,876 | 12 | 141,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
t=int(input())
arr=list(map(int,input().split()))
x=sorted(arr)
print(x[::-1])
``` | instruction | 0 | 70,877 | 12 | 141,754 |
No | output | 1 | 70,877 | 12 | 141,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n × n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 ≤ t ≤ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 ≤ n ≤ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5 | instruction | 0 | 70,977 | 12 | 141,954 |
Tags: constructive algorithms
Correct Solution:
```
for i in range(int(input())):
n = int(input())
if n==2:
print(-1)
else:
odd = []
even = []
case = False
for i in range(1,n**2+1):
if case:
even.append(i)
else:
odd.append(i)
case = not case
arr = odd+even
prev = 0
for i in range(n):
print(*arr[prev:prev + n])
prev += n
``` | output | 1 | 70,977 | 12 | 141,955 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n × n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 ≤ t ≤ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 ≤ n ≤ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5 | instruction | 0 | 70,978 | 12 | 141,956 |
Tags: constructive algorithms
Correct Solution:
```
for test in range(int(input())):
n = int(input())
if n == 1:
print(1)
continue
elif n == 2:
print(-1)
continue
else:
# lst = list(range(1, n ** 2 + 1))
# print(lst)
ans = [[0] * n for i in range(n)]
ans[-1][0] = n ** 2
ans[0][-1] = n ** 2 - 1
q = 1
for i in range(n - 1):
k = 0
for j in range(n - i):
ans[j][i + k] = q
k += 1
q += 1
for i in range(1, n - 1):
k = 0
for j in range(n - i):
ans[i + k][k] = q
q += 1
k += 1
for i in ans:
print(*i)
``` | output | 1 | 70,978 | 12 | 141,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n × n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 ≤ t ≤ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 ≤ n ≤ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5 | instruction | 0 | 70,979 | 12 | 141,958 |
Tags: constructive algorithms
Correct Solution:
```
from io import BytesIO, IOBase
from math import sqrt
import sys,os,math
from os import path
int_inpl=lambda:list(map(int,input().split()))
int_inpm=lambda:map(int,input().split())
int_inp=lambda:int(input())
inp=lambda:input()
from collections import Counter
import heapq
testcases=int_inp()
while testcases:
testcases-=1
int_nump=int_inp()
if int_nump==2:
print(-1)
elif int_nump==1:
print(1)
else:
int_list=[[0 for i in range(int_nump)] for j in range(int_nump)]
int_sqrt_o=int_nump**2
int_matri1=0
int_matri2=0
for i in range(1,int_sqrt_o+1,2):
int_list[int_matri1][int_matri2%int_nump]=i
if int_matri2%int_nump==int_nump-1:int_matri1+=1
int_matri2+=1
for i in range(2,int_sqrt_o+1,2):
int_list[int_matri1][int_matri2%int_nump]=i
if int_matri2%int_nump==int_nump-1:int_matri1+=1
int_matri2+=1
for i in int_list:
print(*i)
``` | output | 1 | 70,979 | 12 | 141,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n × n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 ≤ t ≤ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 ≤ n ≤ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5 | instruction | 0 | 70,983 | 12 | 141,966 |
Tags: constructive algorithms
Correct Solution:
```
##### HAR HAR MAHADEV || JAI SHREE RAM #####
### @created by SHATMANYU GUPTA(shatmanyu_04) ###
mod=pow(10,9)+7;MOD=998244353
## PE -> end=" " ##
from sys import stdin,stdout ; from heapq import heapify,heappush,heappop;from bisect import bisect,bisect_left,bisect_right ; from math import *
from itertools import * ; from collections import *
sml={chr(ord("a")+i):i for i in range(26)};cap={chr(ord("A")+i):i for i in range(26)}
def get_list():return list(map(int,input().split()))
def get_int():return int(input())
def get_ints():return map(int,input().split())
def godprime(n):
for i in range(2,int(sqrt(n))+1):
if n%i==0:
return False
def godpower(b,p):
res=1
while p>0:
if p%2==0:
b=b*b
p//=2
else:
res*=b
p-=1
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def get(n):
d = []
while n > 0:
n1 = n%10
d.append(n1)
n//=10
#d.reverse()
return len(d)
for tt in range(get_int()):
n = get_int()
e = [];o =[]
for i in range(1,n*n+1):
if i%2:
o.append(i)
else:
e.append(i)
ans = e + o
mat = [[0 for i in range(n)]for i in range(n)]
for i in range(n):
for j in range(n):
mat[i][j] = ans.pop(0)
if n == 2:
print(-1)
else:
for i in mat:
print(*i)
##def dfs_path(v,strt,end,n):
## def printPath(stack):
## return len(stack)-1
## def DFS(fg,vis, x, y, stack):
## stack.append(x)
## if (x == y):
## ans = printPath(stack)
## fg = 1
## vis[x] = True
## if (len(v[x]) > 0):
## for j in v[x]:
## if (vis[j] == False):
## DFS(fg,vis, j, y, stack)
## if fg == 1:
## return ans
##
## del stack[-1]
## print("ddd")
## def DFSCall(x, y, n, stack):
## vis = [0]*(n+1)
## fg = 0
## ans2 = DFS(fg,vis, x, y, stack)
## print("terminate",ans2)
## ans1 = DFSCall(strt,end,n,[])
## return ans1
##
##for tt in range(get_int()):
## n,k,a = get_ints()
## s = get_list()
## adj = {i:[] for i in range(1,n+1)}
## for i in range(n-1):
## u,v = get_ints()
## adj[u].append(v)
## adj[v].append(u)
## d = {i:[] for i in range(1,n+1)}
## for i in range(1,n+1):
## for j in s:
## d[i].append(dfs_path(adj,i,j,n))
## print(d)
##
##
##def merge(l,strt,mid,end):
## ans = 0;i = strt;j = mid + 1
## while i < mid+1 and j < end:
## if l[i] < l[j]:
## j += 1
## ans += 1
##
##
##def mergesort(l,strt,end,c):
## if strt < end:
## mid = (strt + end)//2
## mergesort(l,strt,mid,c)
## mergesort(l,mid+1,end,c)
## c += merge(l,strt,mid,end)
## return c
##
##for tt in range(get_ints()):
## n = get_int()
## l = get_list()
``` | output | 1 | 70,983 | 12 | 141,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1.
We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it.
For a given number n, construct a square matrix n × n such that:
* Each integer from 1 to n^2 occurs in this matrix exactly once;
* If (r_1, c_1) and (r_2, c_2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer t (1 ≤ t ≤ 100). Then t test cases follow.
Each test case is characterized by one integer n (1 ≤ n ≤ 100).
Output
For each test case, output:
* -1, if the required matrix does not exist;
* the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as n lines, where each line contains n integers.
Example
Input
3
1
2
3
Output
1
-1
2 9 7
4 6 3
1 8 5
Submitted Solution:
```
import math, sys
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
from itertools import permutations
MOD = int(1e9) + 7
def solve():
n = int(input())
if n == 2:
print(-1)
return
ans = [[0 for i in range(n)] for j in range(n)]
cnt = 1
start = 0
for i in range(n):
for j in range(start, n, 2):
ans[i][j] = cnt
cnt += 1
start ^= 1
start = 1
for i in range(n):
for j in range(start, n, 2):
ans[i][j] = cnt
cnt += 1
start ^= 1
for row in ans:
print(*row)
t = 1
t = int(input())
for _ in range(t):
solve()
``` | instruction | 0 | 70,988 | 12 | 141,976 |
Yes | output | 1 | 70,988 | 12 | 141,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order.
for (int i = 1; i < n; i = i + 1)
{
int j = i;
while (j > 0 && a[j] < a[j - 1])
{
swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]
j = j - 1;
}
}
Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.
It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
Input
The first line contains a single integer n (2 ≤ n ≤ 5000) — the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive — the actual permutation.
Output
Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.
Examples
Input
5
4 0 3 1 2
Output
3 2
Input
5
1 2 3 4 0
Output
3 4
Note
In the first sample the appropriate pairs are (0, 3) and (0, 4).
In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4). | instruction | 0 | 71,083 | 12 | 142,166 |
Tags: data structures, dp, implementation, math
Correct Solution:
```
arr = [0 for i in range(5001)]
def insertion_sort(n, a):
def modify(t):
while t > 0:
arr[t] += 1
t -= t & (-t)
def query(t):
res = 0
while t < 5001:
res += arr[t]
t += t & (-t)
return res
s = 0
ans = 0
way = 0
for i in range(n):
a[i] += 1
for i in range(n):
global arr
arr = [0 for j in range(5001)]
for j in range(i + 1, n):
if a[i] < a[j]:
continue
s += 1
tmp = 1 + 2 * query(a[j])
if tmp > ans:
ans = tmp
way = 1
elif tmp == ans:
way += 1
modify(a[j])
return s - ans, way
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
result = insertion_sort(n, a)
print(*result)
``` | output | 1 | 71,083 | 12 | 142,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order.
for (int i = 1; i < n; i = i + 1)
{
int j = i;
while (j > 0 && a[j] < a[j - 1])
{
swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]
j = j - 1;
}
}
Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.
It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
Input
The first line contains a single integer n (2 ≤ n ≤ 5000) — the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive — the actual permutation.
Output
Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.
Examples
Input
5
4 0 3 1 2
Output
3 2
Input
5
1 2 3 4 0
Output
3 4
Note
In the first sample the appropriate pairs are (0, 3) and (0, 4).
In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4).
Submitted Solution:
```
def main():
n = int(input())
arr = input().split(" ")
arr = [int(a) for a in arr]
imp = 0
cnt = 0
tot = 0
for i in range(n):
tot += max(i - arr[i], 0)
#print(tot)
for i in range(n):
for j in range(i+1, n):
improvement = max(i - arr[i], 0) + max(j - arr[j], 0) - max(i - arr[j], 0) - max(j - arr[i], 0)
if improvement > imp:
imp = improvement
a = i
b = j
cnt = 1
elif improvement == imp:
cnt += 1
print(tot-imp, int(cnt))
if __name__ == "__main__": main()
``` | instruction | 0 | 71,084 | 12 | 142,168 |
No | output | 1 | 71,084 | 12 | 142,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.