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 := \lfloor\frac{a_i}{2}\rfloor$).

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 \le k \le n \le 50$) — 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, \dots, a_n$ ($1 \le a_i \le 2 \cdot 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

Difficulty: MEDIUM
Tags: Implementation

Complete search
Skill types: Complete search

Starter code:

Solutions:
l = input().split()
n = int(l[0])
k = int(l[1])
hashi = dict()
l = input().split()
li = [int(i) for i in l]
z = 0
for i in li:
	z = i
	count = 0
	while z > 0:
		if z not in hashi:
			hashi[z] = [count]
		else:
			hashi[z].append(count)
		z = z // 2
		count += 1
	if 0 not in hashi:
		hashi[0] = [count]
	else:
		hashi[0].append(count)
maxa = 10 ** 18
for i in hashi:
	if len(hashi[i]) < k:
		continue
	arr = [0 for i in range(30)]
	for j in hashi[i]:
		arr[j] += 1
	ans = 0
	z = k
	for i in range(30):
		if z <= arr[i]:
			ans = ans + z * i
			break
		ans = ans + arr[i] * i
		z -= arr[i]
	maxa = min(maxa, ans)
print(maxa)


def int_multiple():
	return [int(c) for c in input().split()]

def int_single():
	return int(input())

def str_multiple():
	return [c for c in input().split()]

def str_single():
	return input()
(n, k) = int_multiple()
l = int_multiple()
l = sorted(l)
costs = []
for i in range(200001):
	costs.append([])
for i in range(n):
	tmp = l[i]
	cnt = 0
	while tmp != 0:
		costs[tmp].append(cnt)
		tmp = int(tmp / 2)
		cnt += 1
for val in costs[1]:
	costs[0].append(val + 1)
min_cost = 9999999999999
for c in costs:
	if len(c) >= k:
		cost = sum(c[:k])
		if cost < min_cost:
			min_cost = cost
print(min_cost)


from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, k) = gil()
a = gil()

def getMaxSetBit(x):
	if x == 0:
		return 0
	return int(math.log2(x)) + 1

def getMin(x):
	b = []
	bit = getMaxSetBit(x)
	for v in a:
		if v == x:
			b.append(0)
		elif v > x:
			steps = getMaxSetBit(v) - bit
			if v >> steps == x:
				b.append(steps)
	b.sort()
	b.append(inf)
	ans = sum(b[:k])
	return ans
ans = min(range(1 + max(a)), key=lambda x: getMin(x))
print(getMin(ans))


def get_ans(n, k, array):
	logging = {0: []}
	for i in array:
		steps = 0
		temp = i
		while temp > 0:
			if temp not in logging.keys():
				logging[temp] = [steps]
			else:
				logging[temp].append(steps)
			temp = temp // 2
			steps += 1
		logging[0].append(steps)
	ans = sum(logging[0])
	for (key, values) in logging.items():
		if len(values) >= k:
			temp_ans = sum(sorted(values)[0:k])
			if temp_ans < ans:
				ans = temp_ans
	return ans
(n, k) = list(map(int, input().strip().split()))
array = list(map(int, input().strip().split()))
print(get_ans(n, k, array))


import math
import sys
input = sys.stdin.readline

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)


(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
tarr = []
for i in range(n):
	t = arr[i]
	while t >= 1:
		tarr.append(t)
		t = t // 2
ans = 10 ** 9 + 7
for i in tarr:
	cnt = []
	for j in range(n):
		t = arr[j]
		cnt1 = 0
		while t // 2 >= i:
			cnt1 += 1
			t = t // 2
		if t == i:
			cnt.append(cnt1)
	cnt.sort()
	if len(cnt) >= k:
		ans = min(ans, sum(cnt[0:k]))
print(ans)


INF = int(2000000000.0)
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
a = [(x, 0) for x in a]
ans = INF
ha = {}
tail = n - 1
p = 0

def lowerbound(x):
	(l, r) = (0, tail - 1)
	while l <= r:
		mid = l + r >> 1
		if a[mid][0] >= x:
			r = mid - 1
		else:
			l = mid + 1
	return r + 1

def find(x):
	l = lowerbound(x[0])
	r = lowerbound(x[0] + 1) - 1
	while l <= r:
		mid = l + r >> 1
		if a[mid][1] <= x[1]:
			r = mid - 1
		else:
			l = mid + 1
	return r + 1
while a[tail][0]:
	flg = True
	cnt = 0
	val = a[tail][0]
	if a[tail - k + 1][0] == val:
		for j in range(k):
			cnt += a[tail - j][1]
		ans = min(ans, cnt)
	rem = k
	while a[tail][0] == val:
		if rem > 0:
			tup = (a[tail][0] // 2, a[tail][1] + 1)
			a.pop()
			a.insert(find(tup), tup)
			rem -= 1
		else:
			a.pop()
			tail -= 1
print(ans)


from collections import defaultdict
ma = defaultdict(list)

def solve(arr, n, k):
	global ma
	for a in arr:
		cnt = 0
		while a > 0:
			ma[a].append(cnt)
			a >>= 1
			cnt += 1
	ret = 10 ** 10
	for key in ma.keys():
		b = ma[key]
		if len(b) >= k:
			b.sort()
			ret = min(ret, sum(b[:k]))
	return ret

def main():
	(n, k) = list(map(int, input().strip().split()))
	arr = list(map(int, input().strip().split()))
	print(solve(arr, n, k))
main()


def fuck(num, i):
	fuck = 0
	while num >= i:
		if num == i:
			return fuck
		num //= 2
		fuck += 1
	return False
lenK = list(map(int, input().split()))
lens = lenK[0]
K = lenK[1]
nums = list(map(int, input().split()))
nums.sort()
lists = [[nums[0], 1]]
up = nums[0]
for i in nums[1:]:
	if i == up:
		lists[-1][1] += 1
	else:
		up = i
		lists.append([i, 1])
mis = -1
for i in range(len(lists)):
	thisN = lists[i][0]
	thisP = 0
	tk = K - lists[i][1]
	if tk <= 0:
		mis = 0
		break
	ji = 0
	while True:
		for j in range(i + 1, len(lists)):
			dong = fuck(lists[j][0], thisN)
			if dong != False:
				thisP += min(tk, lists[j][1]) * dong
				tk -= min(tk, lists[j][1])
			if tk == 0:
				if mis == -1 or mis > thisP:
					mis = thisP
				break
		if thisN == 0:
			break
		thisN //= 2
		ji += 1
		thisP = ji * lists[i][1]
		tk = K - lists[i][1]
print(int(mis))


def mp():
	return map(int, input().split())

def f(a, b):
	res = 0
	while b > a:
		b //= 2
		res += 1
	if b != a:
		res = -1
	return res
(n, k) = mp()
a = sorted(list(mp()))
b = set()
for i in a:
	x = i
	while x > 0:
		b.add(x)
		x //= 2
b.add(0)
tot = 10 ** 20
for x in b:
	ans = cnt = 0
	for i in range(n):
		if a[i] == x:
			cnt += 1
		elif a[i] > x:
			res = f(x, a[i])
			if res != -1:
				ans += res
				cnt += 1
		if cnt >= k:
			break
	if cnt >= k and ans < 10 ** 20:
		tot = min(tot, ans)
print(tot)


(n, k) = list(map(int, input().split()))
it = list(map(int, input().split()))
a = [[] for i in range(n)]
for i in range(n):
	j = it[i]
	a[i] = [j]
	while True:
		j = j // 2
		a[i].append(j)
		if j == 0:
			break
ss = {}
for i in a:
	for j in i:
		try:
			ss[j] += 1
		except:
			ss[j] = 1
mi = 10 ** 10
for i in ss:
	if ss[i] >= k:
		l = [-1] * n
		j = 0
		for ii in a:
			try:
				l[j] = ii.index(i)
			except:
				pass
			j += 1
		l = [i for i in l if i != -1]
		l.sort()
		l = l[:k]
		mi = min(mi, sum(l))
print(mi)


from sys import stdin
input = stdin.readline
inf = 1000 * 1000 * 1000
(n, k) = list(map(int, input().split()))
a = [int(i) for i in input().split()]
a.sort()
res = inf
for i in range(0, 200001, 1):
	b = []
	for j in a:
		tmp2 = 0
		while j > i:
			tmp2 += 1
			j //= 2
		if j == i:
			b.append(tmp2)
		else:
			b.append(inf)
	b.sort()
	tmp = 0
	for i in range(k):
		tmp += b[i]
	res = min(res, tmp)
print(res)


(n, k) = [int(x) for x in input().split(' ')]
arr = sorted([int(x) for x in input().split(' ')])
ans = 99999999999
cand = 0
while cand <= arr[-1]:
	cnt = 0
	cost = 0
	for ind in range(n):
		op = 0
		if arr[ind] < cand:
			continue
		if arr[ind] == cand:
			cnt += 1
			if cnt == k:
				break
		else:
			temp = arr[ind]
			while temp > cand:
				op += 1
				temp = temp // 2
			if temp == cand:
				cnt += 1
				cost += op
				if cnt == k:
					break
	cand += 1
	if cnt == k:
		ans = min(ans, cost)
print(ans)


(n, m) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
d = {}
for i in l:
	if i not in d:
		d[i] = 1
	else:
		d[i] += 1
e = list(d.keys())
e.append(0)
ans = 0
r = 1000000000000000
for i in range(0, 200001):
	if i in d:
		x = d[i]
	else:
		x = 0
	if x >= m:
		r = 0
		break
	ans = 0
	for j in l:
		if j == i:
			continue
		else:
			f = 0
			while j >= i:
				if j == i or j == 0:
					x += 1
					ans += f
					break
				j //= 2
				f += 1
		if x >= m:
			r = min(ans, r)
			break
print(r)


def deep(mas, pref, k):
	deepmas = []
	s = 0
	for el in mas:
		if el[:len(pref)] == pref:
			deepmas.append(el)
			if len(deepmas) <= k:
				s += len(el) - len(pref)
	if len(deepmas) >= k:
		return min(s, deep(deepmas, pref + '0', k), deep(deepmas, pref + '1', k))
	else:
		return 20000000000000000
(n, k) = map(int, input().split())
mas = list(map(int, input().split()))
mas.sort()
mas = list(map(bin, mas))
pref = '0b'
ans = deep(mas, pref, k)
print(ans)


(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
cnt = dict()
sum = dict()
res = n * 20
for x in a:
	y = x
	cur = 0
	while True:
		if y == 0:
			break
		if y not in cnt:
			cnt[y] = 0
			sum[y] = 0
		if cnt[y] < k:
			cnt[y] += 1
			sum[y] += cur
			if cnt[y] == k:
				res = min(res, sum[y])
		y >>= 1
		cur += 1
print(res)


import sys
(mod, MOD) = (1000000007, 998244353)
from collections import deque, Counter, OrderedDict, defaultdict

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
(n, k) = get_ints()
a = get_array()
l = defaultdict(list)
for i in range(n):
	x = a[i]
	c = 0
	while x > 0:
		l[x].append(c)
		x >>= 1
		c += 1
ans = 10 ** 9 + 7
for i in range(200005):
	if len(l[i]) < k:
		continue
	l[i].sort()
	ans = min(ans, sum(l[i][:k]))
print(ans)


import math
import sys
from heapq import heappop
from heapq import heappush
from heapq import heapify
from bisect import insort
from sys import stdin, stdout
from collections import defaultdict
inp = lambda : int(stdin.readline())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, stdin.readline().split()))
slst = lambda : list(sip())
arr2d = lambda x: [[int(j) for j in input().split()] for i in range(x)]
odds = lambda l: len(list(filter(lambda x: x % 2 != 0, l)))
evens = lambda l: len(list(filter(lambda x: x % 2 == 0, l)))
mod = pow(10, 9) + 7
(n, k) = map(int, input().split())
A = [int(x) for x in input().split()]
vals = defaultdict(list)
for i in range(n):
	x = A[i]
	cnt = 0
	while x > 0:
		vals[x].append(cnt)
		x = x // 2
		cnt += 1
res = pow(10, 10)
for i in range(2 * pow(10, 5) + 1):
	l = vals[i]
	l = sorted(l)
	if len(l) >= k:
		res = min(res, sum(l[:k]))
print(res)


import math

def process(A, n, e):
	B = []
	D = {}
	for i in A:
		k = i
		C = []
		while k >= 1:
			C.append(k)
			D[k] = D.get(k, 0) + 1
			k = k // 2
		B.append(C)
		E = []
	for i in D.keys():
		if D[i] >= e:
			E.append(i)
	res = 1e+30
	for i in E:
		F = []
		for q in range(len(B)):
			for t in range(len(B[q])):
				if B[q][t] == i:
					F.append(t)
					break
		F.sort()
		res = min(res, sum(F[0:e]))
	return res
(n, k) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
print(process(A, n, k))


z = []
a = []
for i in range(200010):
	a.append([])
(n, k) = [int(e) for e in input().split()]
b = [int(e) for e in input().split()]
for x in b:
	c = x
	ct = 0
	a[x].append(0)
	while c != 0:
		c >>= 1
		ct += 1
		a[c].append(ct)
ans = 10000000000
for i in range(200000):
	if len(a[i]) < k:
		continue
	a[i].sort()
	s = 0
	for j in range(k):
		s += a[i][j]
	ans = min(ans, s)
print(ans)


import os
import sys
from io import BytesIO, IOBase
from math import inf

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	ma = max(a)
	b = [[] for _ in range(ma + 1)]
	for i in a:
		(j, z) = (i, 0)
		b[j].append(z)
		while j:
			j = j // 2
			z += 1
			b[j].append(z)
	mi = inf
	for i in range(ma + 1):
		if len(b[i]) >= k:
			b[i].sort()
			mi = min(mi, sum(b[i][:k]))
	print(mi)
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')
main()


def div(x, a):
	left = -1
	right = 64
	while right - left > 1:
		mid = (right + left) // 2
		if x // pow(2, mid) <= a:
			right = mid
		else:
			left = mid
	return right
(n, k) = map(int, input().split())
x = [int(x) for x in input().split()]
x.sort()
answer = pow(10, 100)
for i in range(len(x)):
	t = x[i]
	divs = 0
	isDivisible = True
	while isDivisible:
		cnt = 1
		temp = divs
		for j in range(len(x)):
			if i == j or x[j] < t or cnt == k:
				continue
			a = div(x[j], t)
			if x[j] // pow(2, a) == t:
				cnt += 1
				temp += a
		if cnt == k:
			answer = min(temp, answer)
		if t == 0:
			isDivisible = False
		t //= 2
		divs += 1
print(answer)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
c = list(set(a))
b = [[] for i in range(200005)]
for i in a:
	temp = i
	j = 0
	b[temp].append(0)
	if temp != 1:
		while 1:
			temp = temp // 2
			j += 1
			b[temp].append(j)
			if temp == 1:
				break
res = 200005
for i in range(1, max(a) + 1):
	if len(b[i]) >= m:
		temp = sum(b[i][:m])
		res = min(res, temp)
print(res)


(n, k) = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
y = [[0] * 2 for i in range(200001)]
for i in range(n):
	y[x[i]][1] += 1
	count = 0
	while x[i] > 0:
		x[i] //= 2
		count += 1
		if y[x[i]][1] < k:
			y[x[i]][0] += count
			y[x[i]][1] += 1
ans = 123456789
for i in range(200001):
	if y[i][1] >= k:
		ans = min(ans, y[i][0])
print(ans)


def main():
	arr = list(map(int, input().split()))
	n = arr[0]
	k = arr[1]
	arr = list(map(int, input().split()))
	arr.sort()
	ma = arr[-1] + 1
	l = [[0 for j in range(2)] for i in range(ma)]
	for i in range(n):
		c = 0
		while True:
			if type(l[arr[i]]) == int:
				arr[i] = arr[i] // 2
				if arr[i] == 0:
					break
				continue
			l[arr[i]][1] += c
			l[arr[i]][0] += 1
			if l[arr[i]][0] >= k:
				l[arr[i]] = l[arr[i]][1]
			arr[i] = arr[i] // 2
			c += 1
			if arr[i] == 0:
				break
	mi = 10 ** 9
	for i in range(len(l)):
		if type(l[i]) == int:
			mi = min(mi, l[i])
	print(mi)
main()


import collections
(n, k) = list(map(int, input().split()))
A = [int(i) for i in input().split()]
ans = float('inf')
(D1, D2) = (collections.defaultdict(list), collections.defaultdict(int))
for i in range(n):
	a = A[i]
	c = 0
	D1[a].append(c)
	D2[a] += 1
	while a > 0:
		a //= 2
		c += 1
		D1[a].append(c)
		D2[a] += 1
for i in range(max(A) + 1):
	if D2[i] >= k:
		D1[i].sort()
		ans = min(ans, sum(D1[i][:k]))
print(ans)


(a, b) = list(map(int, input().split()))
array = list(map(int, input().split()))
c = b - 1
answer = []
array.sort()
arr = list(range(1, array[-1] + 1))
for it in arr:
	element = it
	current = 0
	count = 0
	for y in range(0, a):
		copare = array[y]
		if copare < element:
			pass
		elif current == b:
			answer.append(count)
			break
		else:
			moves = 0
			flag = 5
			while True:
				if copare == element:
					break
				elif copare < element:
					flag = 6
					break
				else:
					copare = int(copare // 2)
					moves += 1
			if flag == 6:
				pass
			else:
				count += moves
				current += 1
	if current == b:
		answer.append(count)
array = array[0:b]
moves = 0
for it in array:
	while True:
		if it == 0:
			break
		else:
			it = int(it // 2)
			moves += 1
answer.append(moves)
print(min(answer))


from math import log2
from collections import defaultdict
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
z = l[-1] // 2
hash = defaultdict(list)
seti = defaultdict(set)
for i in range(l[-1] + 1):
	z = i
	while True:
		seti[i].add(z)
		if z == 0:
			break
		z = z // 2
z = l[-1]
for i in range(z + 1):
	for j in range(len(l)):
		if l[j] >= i:
			temp = i
			if i == 0:
				i += 1
			ka = log2(l[j] // i)
			if temp in seti[l[j]]:
				if temp == 0:
					ka += 1
					i -= 1
				hash[i].append(int(ka))
mini = 10 ** 18
for i in hash:
	hash[i].sort()
	if len(hash[i]) >= k:
		mini = min(sum(hash[i][:k]), mini)
print(mini)


from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, k) = gil()
a = gil()
a.sort()
moves = inf

def getMoves(reach):
	global moves
	(cMoves, got) = (0, 0)
	for v in a:
		temp = 0
		while v > reach:
			v = v >> 1
			temp += 1
		if reach == v:
			got += 1
			cMoves += temp
		if got == k:
			moves = min(moves, cMoves)
			return
	return
for v in range(a[-1] + 1):
	getMoves(v)
print(moves)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		(n, e) = ria()
		a = ria()
		d = {}
		f = {}
		for i in a:
			k = i
			op = 0
			while True:
				if k in f:
					f[k].append(op)
				else:
					f[k] = [op]
				op += 1
				if k == 0:
					break
				k = k // 2
		g = 0
		v = []
		for i in f:
			if len(f[i]) >= e:
				g = max(g, i)
				v.append(i)
		ans1 = 99999999999999999999999999999999
		for i in v:
			ta = 0
			tz = sorted(f[i])
			for j in range(e):
				ta += tz[j]
			ans1 = min(ans1, ta)
		print(ans1)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


def getMoves(arr, num, k):
	count = 0
	n = len(arr)
	total_moves = 0
	for i in range(n):
		moves = 0
		curr = arr[i]
		while True:
			if curr <= num:
				break
			moves += 1
			curr = curr // 2
		if curr == num:
			total_moves += moves
			count += 1
		if count >= k:
			break
	if count >= k:
		return total_moves
	return float('inf')

def main():
	(n, k) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	min_moves = float('inf')
	arr.sort()
	for i in range(2 * 10 ** 5 + 1):
		moves = getMoves(arr, i, k)
		min_moves = min(min_moves, moves)
	print(min_moves)
main()


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
p = 2 * 10 ** 5 + 1
b = [[] for _ in range(p)]
for a in l:
	count = 0
	while a > 0:
		b[a].append(count)
		count += 1
		a = a // 2
ans = 1000000000000000
for a in b:
	if len(a) >= k:
		ans = min(ans, sum(sorted(a)[:k]))
print(ans)


(n, k) = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
ANS = [0] * (2 * 10 ** 5 + 1)
COUNT = [0] * (2 * 10 ** 5 + 1)
ANSWER = 1 << 50
for a in A:
	COUNT[a] += 1
	if COUNT[a] >= k:
		ANSWER = min(ANSWER, ANS[a])
	NOW = 0
	while a != 0:
		a //= 2
		NOW += 1
		COUNT[a] += 1
		ANS[a] += NOW
		if COUNT[a] >= k:
			ANSWER = min(ANSWER, ANS[a])
print(ANSWER)


import sys
input = sys.stdin.readline
from collections import defaultdict
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
d = defaultdict(list)
for a in l:
	cnt = 0
	while a > 0:
		d[a].append(cnt)
		cnt += 1
		a = a // 2
ans = 1000000000
for x in d.values():
	if len(x) >= k:
		x = sorted(x)
		ans = min(ans, sum(x[:k]))
print(ans)


R = lambda : map(int, input().split())
(n, k) = R()
d = {}
for x in R():
	i = 0
	while x:
		l = d.setdefault(x, [])
		l += (i,)
		x >>= 1
		i += 1
print(min((sum(sorted(d[x])[:k]) for x in d if len(d[x]) >= k)))


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
d = {}
for liczba in l:
	ll = liczba
	while ll > 0:
		d[ll] = []
		ll //= 2
for liczba in l:
	i = 0
	ll = liczba
	while ll > 0:
		d[ll].append(i)
		ll //= 2
		i += 1
wyn = 1000000000
for number in d:
	if len(d[number]) < k:
		continue
	a = d[number].copy()
	a.sort()
	wyn = min(wyn, sum(a[:k]))
print(wyn)


from collections import defaultdict
(N, K) = map(int, input().split())
(*A,) = map(int, input().split())
A.sort()
D = defaultdict(list)
for a in A:
	D[a].append(0)
	c = 0
	while a > 0:
		a >>= 1
		c += 1
		D[a].append(c)
ans = 10 ** 9
for vs in D.values():
	if len(vs) >= K:
		ans = min(ans, sum(vs[:K]))
print(ans)


from sys import stdin, stdout
from collections import Counter
import math

def rsingle_int():
	return int(stdin.readline().rstrip())

def rmult_int():
	return [int(x) for x in stdin.readline().rstrip().split()]

def rmult_str():
	return stdin.readline().rstrip().split()

def r_str():
	return stdin.readline().rstrip()

def rsingle_char():
	return stdin.read(1)

def sortFirst(val):
	return val[0]

def main():
	(n, k) = rmult_int()
	a = rmult_int()
	cnts = {}
	a.sort()
	for el in a:
		cnt = 0
		while el != 0:
			if el not in cnts:
				cnts[el] = []
			cnts[el].append(cnt)
			el = int(math.floor(el / 2))
			cnt += 1
		if el not in cnts:
			cnts[el] = []
		cnts[el].append(cnt)
	min_cost = float(math.inf)
	for el in cnts.keys():
		arr = cnts[el]
		if len(arr) >= k:
			sum_ = 0
			for i in range(k):
				sum_ += arr[i]
			if sum_ < min_cost:
				min_cost = sum_
	print(min_cost)
main()


mxn = 2 * 10 ** 5 + 1
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
bckt = [[] for i in range(mxn + 1)]
for i in range(n):
	steps = 0
	while a[i]:
		bckt[a[i]].append(steps)
		steps += 1
		a[i] //= 2
mn = 10 ** 18
for i in range(mxn + 1):
	if len(bckt[i]) >= k:
		bckt[i].sort()
		mn = min(mn, sum(bckt[i][:k]))
print(mn)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
ans = [[0, 0] for i in range(200001)]
a.sort()
for i in range(n):
	ans[a[i]][0] += 1
for i in range(n):
	s = a[i]
	d = 1
	while s > 0:
		s = s // 2
		if ans[s][0] < k:
			ans[s][0] += 1
			ans[s][1] += d
		d += 1
mi = 100000000
for i in range(len(ans)):
	if ans[i][0] >= k:
		if ans[i][1] < mi:
			mi = ans[i][1]
print(mi)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict

def main():
	(n, k) = map(int, input().split(' '))
	a = list(map(int, input().split(' ')))
	dic = defaultdict(lambda : [])
	for x in range(n):
		cnt = 0
		while a[x] != 0:
			dic[a[x]].append(cnt)
			a[x] = a[x] // 2
			cnt += 1
		dic[0].append(cnt)
	ans = int(1e+100)
	for y in dic.values():
		if len(y) >= k:
			ans = min(ans, sum(sorted(y)[:k]))
	print(ans)
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')
main()


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
d = dict()
c = 0
f = 0
a = [0 for i in range(200001)]
min1 = -1
while l[-1] != 0:
	for i in range(f, len(l)):
		if l[i] in d:
			d[l[i]] += 1
		else:
			d[l[i]] = 1
		a[l[i]] += c
		if d[l[i]] >= k:
			if min1 == -1:
				min1 = a[l[i]]
			else:
				min1 = min(min1, a[l[i]])
		if l[i] == 0:
			f = i + 1
		l[i] = l[i] // 2
	c += 1
print(min1)


from collections import defaultdict

def solve(arr, k):
	c = defaultdict(list)
	for i in arr:
		j = 0
		while i:
			c[i].append(j)
			i //= 2
			j += 1
		c[i].append(j)
	c = {key: sorted(v) for (key, v) in c.items() if len(v) >= k}
	return min((sum((v[i] for i in range(k))) for v in c.values()))
(_, k) = [int(i) for i in input().split()]
arr = [int(i) for i in input().split()]
print(solve(arr, k))


(n, k1) = map(int, input().split())
li = list(map(int, input().split()))
d = {}
for i in li:
	k = 0
	while i != 0:
		try:
			d[i].append(k)
		except KeyError:
			d[i] = [k]
		k += 1
		i = i // 2
mi = 100000000
for i in d.values():
	if len(i) >= k1:
		i.sort()
		mi = min(mi, sum(i[:k1]))
print(mi)


import sys

def main():

	def input():
		return sys.stdin.readline()[:-1]
	(n, l) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = 10000
	for e in range(0, max(a) + 1):
		d = []
		t = 0
		for k in range(n):
			s = 0
			b = 0
			if a[k] == e:
				d.append(0)
			elif a[k] > e:
				b = a[k]
				while b > e:
					b //= 2
					s += 1
				if b == e:
					d.append(s)
				else:
					d.append(10000)
			elif a[k] < e:
				d.append(10000)
		ans = min(ans, sum(sorted(d)[:l]))
	print(ans)
main()


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
b = {}
c = {}
mm = 100000000000.0
for i in range(n):
	k = a[i]
	t = 0
	while k > 0:
		if k not in b or b[k] < m:
			b[k] = b.get(k, 0) + 1
			c[k] = c.get(k, 0) + t
			if b[k] == m:
				mm = min(mm, c[k])
		t += 1
		k //= 2
	else:
		if 0 not in b or b[0] < m:
			b[0] = b.get(0, 0) + 1
			c[0] = c.get(0, 0) + t
		if b[0] == m:
			mm = min(mm, c[0])
print(mm)


from math import log
(n, k) = list(map(int, input().split()))
arr = list(map(int, input().split()))
ans = 0
a = [[] for i in range(200001)]
for i in range(n):
	x = arr[i]
	l = 0
	while True:
		a[x].append(l)
		if x == 0:
			break
		x //= 2
		l += 1
mn = 1000000000
for i in range(len(a)):
	a[i].sort()
	if len(a[i]) >= k:
		mn = min(mn, sum(a[i][:k]))
print(mn)


import sys
input = sys.stdin.buffer.readline

def solution():
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	m = 2000000000.0
	for i in range(max(l) + 1):
		a = []
		for j in l:
			x = j
			cnt = 0
			while x > i:
				x //= 2
				cnt += 1
			if x == i:
				a.append(cnt)
		if len(a) >= k:
			a.sort()
			s = sum(a[0:k])
			m = min(m, s)
		i += 1
	print(m)
solution()


ans = {}
(n, k) = (int(s) for s in input().split())
l = [int(s) for s in input().split()]
l.sort()
for i in range(n):
	x = l[i]
	count = 0
	while x > 0:
		if x in ans:
			if ans[x][0] < k:
				ans[x][0] += 1
				ans[x][1] += count
		else:
			ans[x] = [1, count]
		count += 1
		x = x // 2
	if 0 in ans:
		if ans[0][0] < k:
			ans[0][0] += 1
			ans[0][1] += count
	else:
		ans[x] = [1, count]
ansm = 1000000000007
for i in ans:
	if ans[i][0] >= k:
		ansm = min(ansm, ans[i][1])
print(ansm)


(n, k) = map(int, input().split())
from collections import defaultdict
nums = list(map(int, input().split()))
cc = defaultdict(int)
aa = defaultdict(list)
for num in nums:
	o = num
	i = 0
	while o != 0:
		cc[o] += 1
		aa[o].append(i)
		i += 1
		o //= 2
candidates = [name for (name, count) in cc.items() if count >= k]
m = float('inf')
for name in candidates:
	m = min(m, sum(sorted(aa[name])[:k]))
print(m)


from collections import defaultdict as dd
(n, k) = map(int, input().split())
g = dd(list)
for i in map(int, input().split()):
	cnt = 0
	while i > 0:
		g[i].append(cnt)
		i //= 2
		cnt += 1
	g[0].append(cnt)
ans = 999999999999999999999
for i in g:
	if len(g[i]) >= k:
		ans = min(ans, sum(sorted(g[i])[:k]))
print(ans)


from collections import defaultdict as dc
(x, y) = map(int, input().split())
coun = dc(lambda : 0)
steps = dc(lambda : 0)
s = list(map(int, input().split()))
s.sort()
for n in s:
	coun[n] += 1
	if coun[n] == y:
		print(0)
		exit(0)
res = 10 ** 9
for n in s:
	p = n
	stp = 0
	while p:
		p //= 2
		stp += 1
		coun[p] += 1
		steps[p] += stp
		if coun[p] == y:
			res = min(res, steps[p])
print(res)


R = lambda : map(int, input().split())
(n, k) = R()
L = sorted(R())
ma = max(L) + 1
f = [0] * ma
dp = [0 for i in range(ma)]
res = 10 ** 9
for (j, i) in enumerate(L):
	p = i
	c = 0
	while p:
		dp[p] += c
		f[p] += 1
		if f[p] >= k:
			res = min(res, dp[p])
		p //= 2
		c += 1
print(res)


(n, k) = [int(s) for s in input().split(' ')]
A = [int(s) for s in input().split(' ')]
divs = [0] * len(A)
maximum = max(A)
ans = float('inf')
while maximum > 0:
	if A.count(max(A)) >= k:
		D = [divs[i] for i in range(len(A)) if A[i] == maximum]
		D.sort()
		ans = min(ans, sum(D[:k]))
	max_index = A.index(max(A))
	A[max_index] = int(A[max_index] / 2)
	maximum = max(A)
	divs[max_index] += 1
D = [divs[i] for i in range(len(A)) if A[i] == maximum]
D.sort()
ans = min(ans, sum(D[:k]))
print(ans)


from itertools import islice
(_, k) = tuple(map(int, input().split()))
arr = list(map(int, input().split()))
counts = [None] * (2 * 10 ** 5 + 1)

def append_counts(xx, cnt):
	if counts[xx] is None:
		counts[xx] = []
	counts[xx].append(cnt)
for a in arr:
	cur = 0
	x = a
	while x > 0:
		append_counts(x, cur)
		x //= 2
		cur += 1
result = 2 * 10 ** 7
for i in counts:
	if i and len(i) >= k:
		i.sort()
		result = min(result, sum(islice(i, 0, k)))
print(result)


from collections import defaultdict as dd
(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
d = dd(list)
for x in a:
	i = 0
	while x:
		d[x].append(i)
		x //= 2
		i += 1
ans = 999999999999
for i in d:
	if len(d[i]) >= k:
		d[i].sort()
		ans = min(ans, sum(d[i][0:k]))
print(ans)


MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
(n, m) = I()
l = I()
l.sort()
ans = MOD
o = [0] * 300000
d = [0] * 300000
for i in range(n):
	k = l[i]
	o[k] += 1
	if o[k] == m:
		ans = min(ans, d[k])
	i = 0
	while k > 0:
		i += 1
		k //= 2
		o[k] += 1
		d[k] += i
		if o[k] == m:
			ans = min(ans, d[k])
print(ans)


(N, K) = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
lk = [0] * 1000000
for n in l:
	t = n
	while t != 0:
		lk[t] += 1
		t //= 2
lk[0] = 99999999
g = 0
mn = 9999999
for i in range(len(lk) - 1, -1, -1):
	if lk[i] >= K:
		g = i
		ed = []
		for n in l:
			if n < g:
				ed.append(9999999)
			elif n == g:
				ed.append(0)
			else:
				t = n
				c = 0
				while True:
					t //= 2
					c += 1
					if t <= g:
						if t == g:
							ed.append(c)
						else:
							ed.append(9999999)
						break
		ed.sort()
		mn = min(mn, sum(ed[:K]))
print(mn)


from sys import stdin, stdout
from collections import defaultdict
from collections import deque
import math
import copy
(N, K) = [int(x) for x in stdin.readline().split()]
arr = [int(x) for x in stdin.readline().split()]
arr.sort()
freq = {}
for i in range(N):
	num = arr[i]
	if num not in freq:
		freq[num] = []
	round = 0
	freq[num].append(0)
	while num != 0:
		round += 1
		num = num // 2
		if num not in freq:
			freq[num] = []
		freq[num].append(round)
res = 999999999999
for key in freq:
	if len(freq[key]) < K:
		continue
	else:
		s = sum(freq[key][:K])
		res = min(res, s)
print(res)


import math
from heapq import merge
(n, k) = list(map(int, input().split()))
maxN = 2 * 10 ** 5 + 10
cnt = [list() for i in range(0, maxN + 1)]
a = list(map(int, input().split()))
for c in a:
	cnt[c].append(0)
best = 1000000000
for i in range(maxN - 1, -1, -1):
	if 2 * i < maxN:
		cnt[2 * i] = [x + 1 for x in cnt[2 * i]]
		for p in cnt[2 * i]:
			p += 1
	if 2 * i + 1 < maxN:
		cnt[2 * i + 1] = [x + 1 for x in cnt[2 * i + 1]]
	if 2 * i < maxN:
		cnt[i] = list(merge(cnt[i], list(merge(cnt[2 * i], cnt[2 * i + 1]))))
	while len(cnt[i]) > k:
		cnt[i].pop()
	if len(cnt[i]) == k:
		best = min(best, sum(cnt[i]))
print(best)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

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):
	(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))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def solve():
	(n, k) = sep()
	ar = lis()
	d = defaultdict(list)
	for i in range(n):
		t = ar[i]
		s = 0
		while t > 0:
			d[t].append(s)
			s += 1
			t //= 2
		d[0].append(s)
	m = 99999999999999999999
	for i in d.keys():
		if len(d[i]) >= k:
			d[i].sort()
			t = sum(d[i][:k])
			m = min(t, m)
	print(m)
solve()


n = list(map(int, input().split()))
n[0]
k = n[1]
a = list(map(int, input().split()))
dicta = {}
dictb = {}
for j in a:
	if j in dicta:
		dicta[j] += 1
	else:
		dicta[j] = 1
	if j not in dictb:
		dictb[j] = 0
b = 0
for j in dicta:
	if dicta[j] >= k:
		b = 1
		break
if b == 1:
	print(0)
else:
	minimum = 2 * 10 ** 5 + 1
	for i in range(20):
		tmp = []
		for l in a:
			j = l // 2
			if j in dicta:
				dicta[j] += 1
				dictb[j] += i + 1
				if dicta[j] >= k:
					if dictb[j] < minimum:
						minimum = dictb[j]
			elif j > 0:
				dicta[j] = 1
				dictb[j] = i + 1
			tmp.append(j)
		a = tmp
		for j in dicta:
			if dicta[j] >= k:
				if dictb[j] < minimum:
					minimum = dictb[j]
	print(minimum)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
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
mod = pow(10, 9) + 7
mod2 = 998244353

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)]
(n, k) = sp()
arr = l()
arr.sort()
answer = inf
for i in range(1, 200001):
	res = 0
	cnt = 0
	for j in range(n):
		if arr[j] < i:
			continue
		c = 0
		temp = arr[j]
		while temp > i:
			temp //= 2
			c += 1
		if temp == i:
			res += c
			cnt += 1
		if cnt == k:
			break
	if cnt == k:
		answer = min(answer, res)
out(answer)


(n, k) = [int(i) for i in input().split()]
a = sorted([int(i) for i in input().split()])
numbers = [[0, 0] for i in range(a[-1] + 1)]
for i in range(n):
	op = 0
	while a[i] > 0:
		if numbers[a[i]][0] < k:
			numbers[a[i]][0] += 1
			numbers[a[i]][1] += op
		a[i] //= 2
		op += 1
	numbers[0][0] += 1
	numbers[0][1] += op
ans = numbers[0][1]
for number in numbers:
	if number[0] >= k and number[1] < ans:
		ans = number[1]
print(ans)


from sys import stdin
from collections import defaultdict
input = stdin.readline
(n, k) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
d = defaultdict(list)
operations = 0
for i in range(n):
	x = a[i]
	d[x].append(0)
	c = 0
	while x > 0:
		x //= 2
		c += 1
		d[x].append(c)
	d[0].append(c + 1)
b = [list(sorted(i)) for i in d.values()]
ans = float('inf')
for i in b:
	if len(i) < k:
		continue
	s = 0
	for j in range(k):
		s += i[j]
	ans = min(ans, s)
print(ans)


def get_num_operations(m, x):
	if x < m:
		return big_number
	if x == m:
		return 0
	return 1 + get_num_operations(m, int(x / 2))
big_number = 10000000
(n, k) = map(int, input().split())
elements_array = list(map(int, input().split()))
answer_elements = set()
answer_elements.add(0)
for element in elements_array:
	while element > 0:
		answer_elements.add(element)
		element = int(element / 2)
max_element = int(max(elements_array))
best_result = big_number
for m in answer_elements:
	cur_results_array = list()
	k_elements = 0
	for element in elements_array:
		cur_operations = get_num_operations(m, element)
		cur_results_array.append(cur_operations)
	cur_results_array.sort()
	cur_operations = sum(cur_results_array[:k])
	best_result = min(best_result, cur_operations)
print(best_result)


import collections
import functools
import math
import sys
import bisect

def In():
	return map(int, sys.stdin.readline().split())
input = sys.stdin.readline

def eqdiv():
	(n, k) = In()
	cost = [0] * int(100000.0 * 2 + 10)
	count = cost[:]
	l = list(In())
	l.sort()
	for i in l:
		i = int(i)
		pos = 0
		while i:
			if count[i] < k:
				count[i] += 1
				cost[i] += pos
			pos += 1
			i //= 2
	ans = float('inf')
	for i in range(len(cost)):
		if count[i] == k and cost[i] < ans:
			ans = min(ans, cost[i])
	return ans
print(eqdiv())


(n, k) = map(int, input().split())
a = list(map(int, input().split()))

def check(x, y):
	if x > y:
		return -1
	cnt = 0
	while x < y:
		cnt += 1
		y = y // 2
	if x == y:
		return cnt
	else:
		return -1

def find(x):
	ans = []
	for i in range(n):
		c = check(x, a[i])
		if c != -1:
			ans += [c]
	if len(ans) >= k:
		return sum(sorted(ans)[:k])
	else:
		return -1
l = 0
r = 2 * 10 ** 5 + 1
ret = 10 ** 18
for i in range(r):
	v = find(i)
	if v != -1:
		ret = min(ret, v)
print(ret)


(n, k) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
a1 = sorted(a)
l = [[0 for i in range(n)] for j in range(20)]
d = {}
for j in range(n):
	x = 1
	for i in range(20):
		if i == 0:
			l[i][j] = a[j]
			if a[j] not in d:
				d[a[j]] = 1
			else:
				d[a[j]] += 1
		else:
			l[i][j] = a[j] // 2
			a[j] = a[j] // 2
			if a[j] not in d:
				d[a[j]] = 1
			else:
				d[a[j]] += 1
value = 10 ** 5
d1 = sorted(list(d.keys()))[::-1]
for y in range(len(d1)):
	if d1[y] != 0:
		temp = 0
		temp_ans = 0
		for i in range(20):
			for j in range(n):
				if l[i][j] == d1[y]:
					if temp < k:
						temp += 1
						temp_ans += i
					else:
						break
		if temp == k:
			value = min(value, temp_ans)
	else:
		temp_ans = 0
		for j in range(k):
			for i in range(1, 20):
				x = 2
				if a1[j] // x != 0:
					a1[j] = a1[j] // x
				else:
					temp_ans += i - 1
		value = min(temp_ans, value)
print(value)


ll = lambda : list(map(int, input().split()))
testcases = 1

def step(s, e):
	if s == e:
		return 0
	elif s < e:
		return -1
	count = 0
	while s > e:
		count += 1
		s = s // 2
		if s == e:
			return count
	return -1
for _ in range(testcases):
	[n, k] = ll()
	a = ll()
	a.sort()
	minres = 999999999
	t = a[-1]
	ix = -1
	for i in range(1, t + 1):
		steps = []
		for j in a:
			x = step(j, i)
			if x != -1:
				steps.append(x)
		if len(steps) < k:
			continue
		steps.sort()
		if minres > sum(steps[:k]):
			minres = sum(steps[:k])
			ix = i
	print(minres)


class TrieNode:
	limit = 0
	min_cost = 32 * 200000

	def __init__(self):
		self.nodes = [None, None]
		self.count = 0
		self.cost = 0

	def add(self, word, pos=0):
		delta = len(word) - pos
		self.count += 1
		self.cost += delta
		if self.count == TrieNode.limit:
			TrieNode.min_cost = min(self.cost, TrieNode.min_cost)
		if delta:
			if not self.nodes[word[pos]]:
				self.nodes[word[pos]] = TrieNode()
			self.nodes[word[pos]].add(word, pos + 1)

def convert(word):
	return list(map(int, format(word, 'b')))
(n, TrieNode.limit) = map(int, input().split())
x = sorted(map(int, input().split()))
root = TrieNode()
for w in x:
	root.add(convert(w))
print(TrieNode.min_cost)


(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = [[] for i in range(2 * 10 ** 5 + 1)]
for i in a:
	j = 0
	while i:
		b[i].append(j)
		j += 1
		i //= 2
	b[0].append(j)
ans = 10 ** 15
for i in b:
	if len(i) >= k:
		ans = min(ans, sum(sorted(i)[:k]))
print(ans)


def main():
	(n, k) = readIntArr()
	a = readIntArr()
	finalVal = [[] for _ in range(200001)]
	for x in a:
		cnts = 0
		while True:
			finalVal[x].append(cnts)
			x >>= 1
			cnts += 1
			if x == 0:
				finalVal[x].append(cnts)
				break
	ans = inf
	for i in range(200001):
		if len(finalVal[i]) >= k:
			finalVal[i].sort()
			total = 0
			for j in range(k):
				total += finalVal[i][j]
			ans = min(ans, total)
	print(ans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import math
import random
import sys
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
m = {}
for i in range(n):
	d = a[i]
	while d != 0:
		m[d] = 1
		d //= 2
answer = 10 ** 9
for key in m:
	r = []
	for i in range(n):
		d = a[i]
		cost = 0
		while d > key:
			cost += 1
			d //= 2
		if d == key:
			r.append(cost)
	if len(r) >= k:
		r.sort()
		answer = min(answer, sum(r[0:k]))
print(answer)


from sys import stdin
inp = stdin.readline
(n, k) = [int(x) for x in inp().strip().split()]
a = [int(x) for x in inp().strip().split()]
a.sort()
d = {}
ans = -1
for i in a:
	j = 0
	while i != 0:
		if d.get(i, 0) == 0:
			d[i] = [1, j]
		elif d[i][0] < k:
			d[i][0] += 1
			d[i][1] += j
		if d[i][0] == k:
			if ans == -1:
				ans = d[i][1]
				break
			else:
				ans = min(ans, d[i][1])
				break
		i //= 2
		j += 1
print(ans)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
d = {}
for i in a:
	d[i] = d.get(i, 0) + 1
if max(d.values()) >= k:
	print(0)
	exit()
a = sorted(a)
d = max(a)
b = [0] * (d + 1)
dp = [0] * (d + 1)
for _ in range(n):
	i = a[_]
	if b[i] >= k:
		continue
	b[i] += 1
	tc = 0
	while i != 0:
		if b[i // 2] >= k:
			i //= 2
		else:
			tc += 1
			b[i // 2] += 1
			dp[i // 2] += tc
			i //= 2
ans = 1431132213123133123213213231323
for i in range(1, d + 1):
	if b[i] >= k:
		ans = min(ans, dp[i])
print(ans)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
mp = collections.defaultdict(int)
dp = collections.defaultdict(int)
ans = float('inf')
for (i, cr) in enumerate(arr):
	c = cr
	sc = 0
	while c:
		mp[c] += 1
		if mp[c] <= k:
			dp[c] += sc
		if mp[c] == k:
			ans = min(ans, dp[c])
		c //= 2
		sc += 1
print(ans)


def divide(n, x):
	res = 0
	while n > x:
		n = n // 2
		res += 1
	return (res, n)

def comp(x, a, idx):
	add = 0
	inc = 0
	check = x
	res = 1000000000
	flag = 0
	for j in range(idx + 1, n):
		if inc >= k - 1:
			flag = 1
			res = min(res, add)
			break
		(count, x) = divide(a[j], check)
		if x == check:
			add += count
			inc += 1
	if inc >= k - 1:
		flag = 1
		res = min(res, add)
	if flag == 0:
		return -1
	else:
		return res
(n, k) = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
a = sorted(a)
res = 1000000000
for i in range(n):
	counter = 0
	temp = 0
	lol = a[i]
	while lol > 0:
		temp = comp(lol, a, i)
		if temp >= 0:
			res = min(res, temp + counter)
		lol = lol // 2
		counter += 1
print(res)


b = {}
(n, k) = list(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 ** 6
for i in b:
	b[i].sort()
	if len(b[i]) >= k:
		ans = min(sum(b[i][:k]), ans)
print(ans)


from math import inf
nk = input().split()
n = int(nk[0])
k = int(nk[1])
a = [int(ai) for ai in input().split()]
possibilities = []
for ai in a:
	moves = 0
	while ai != 0:
		possibilities.append((ai, moves))
		ai = ai // 2
		moves += 1
	possibilities.append((ai, moves))
possibilities.sort()
i = 0
minOps = inf
while i < len(possibilities):
	same = possibilities[i][0]
	sameElems = 0
	operations = 0
	j = i
	while j < len(possibilities) and possibilities[j][0] == same:
		sameElems += 1
		operations += possibilities[j][1]
		if sameElems == k:
			break
		j += 1
	if sameElems == k and operations < minOps:
		minOps = operations
	j = i
	while j < len(possibilities) and possibilities[j][0] == same:
		j += 1
	i = j
print(minOps)


(n, k) = map(int, input().split())
x = [int(n) for n in input().split()]
a = []
m = {}
ans = 10000000000
for i in x:
	c = 0
	t = i
	while t:
		if t not in m:
			m[t] = []
		m[t].append(c)
		t //= 2
		c += 1
for i in m:
	if len(m[i]) >= k:
		a = sorted(m[i])
		ans = min(ans, sum(a[:k]))
print(ans)


from bisect import *
from math import *
from collections import *
from heapq import *
from itertools import *
inf = 10 ** 18
mod = 10 ** 9 + 7
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
if k == 1:
	print(0)
	exit()
a.sort()
sett = set([])
for i in range(n):
	temp = a[i]
	while temp:
		sett.add(temp)
		temp //= 2
sett.add(0)
minn_ans = inf
for i in sett:
	arr = []
	for j in range(n):
		temp = a[j]
		cnt = 0
		while temp != i:
			if temp == 0:
				break
			cnt += 1
			temp //= 2
		if temp == i:
			arr.append(cnt)
	arr.sort()
	if len(arr) >= k:
		minn_ans = min(minn_ans, sum(arr[0:k]))
print(minn_ans)


from collections import Counter

def two(n):
	t = []
	while n:
		t.append(n)
		n //= 2
	return t + [0]

def f(a, k):
	cnt = Counter(a)
	cnt[0] = 0
	a = sorted(a)
	dct = {}
	ans = float('inf')
	for i in set(a):
		dct[i] = two(i)
	for val in range(2 * 10 ** 5):
		ct = cnt[val]
		if ct >= k:
			return 0
		tans = 0
		for i in a:
			if i != val:
				if val in dct[i]:
					tans += dct[i].index(val)
					ct += 1
					if ct >= k:
						ans = min(ans, tans)
						break
		if ct >= k:
			ans = min(ans, tans)
	return ans
(a, b) = map(int, input().strip().split())
l = list(map(int, input().strip().split()))
print(f(l, b))


(n, k) = map(int, input().split())
a_list = sorted(map(int, input().split()))
nums = [0 for i in range(1 + 2 * 10 ** 5)]
counts = [0 for i in range(1 + 2 * 10 ** 5)]
for a in a_list:
	count = 0
	nums[a] += 1
	while a != 0:
		a = a // 2
		count += 1
		if nums[a] < k:
			nums[a] += 1
			counts[a] += count
counts2 = [counts[i] for (i, num) in enumerate(nums) if num >= k]
out = min(counts2)
print(out)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

def inar():
	return [int(k) for k in input().split()]

def main():
	(n, k) = map(int, input().split())
	arr = inar()
	dic = defaultdict(list)
	cnt = 0
	for i in range(n):
		cnt = 0
		dic[arr[i]].append(cnt)
		while 1:
			arr[i] //= 2
			cnt += 1
			dic[arr[i]].append(cnt)
			if arr[i] == 0:
				break
	res = 10 ** 9
	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')
main()


(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)


(n, k) = [int(x) for x in input().split()]
nums = sorted([int(x) for x in input().split()])
count = [0 for _ in range(2 * 100000 + 10)]
ops = [0 for _ in range(2 * 100000 + 10)]
for num in nums:
	op = 0
	while num > 0:
		ops[num] += op if count[num] < k else 0
		count[num] += 1
		num = num // 2
		op += 1
	ops[num] += op if count[num] < k else 0
	count[num] += 1
minn = 0
minop = ops[0]
for i in range(2 * 100000 + 1):
	if count[i] >= k and ops[i] < minop:
		minn = i
		minop = ops[i]
print(minop)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
ans = 10 ** 10
for i in range(2 * 10 ** 5 + 1):
	x = []
	for j in range(n):
		t = a[j]
		if t < i:
			x.append(10 ** 9)
		else:
			c = 0
			while t > i:
				t = t // 2
				c = c + 1
			if t == i:
				x.append(c)
			else:
				x.append(10 ** 9)
	x.sort()
	ans = min(ans, sum(x[:k]))
print(ans)


import math as mt
import sys, string
input = sys.stdin.readline
from collections import defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
(n, k) = M()
l = L()
x = set()
for i in l:
	r = i
	while r:
		x.add(r)
		r = r // 2
		x.add(r)
ans1 = 10 ** 10
for i in x:
	h = []
	for j in range(len(l)):
		ans = 0
		d = l[j]
		if d >= i:
			while d > i:
				d //= 2
				ans += 1
		if d == i:
			h.append(ans)
	if len(h) >= k:
		h.sort()
		ans1 = min(ans1, sum(h[:k]))
print(ans1)


from __future__ import division, print_function
from sys import stdin, stdout
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
import heapq
from math import ceil, floor, log, sqrt, factorial, pow, pi, gcd
from fractions import Fraction

def ii():
	return int(input())

def si():
	return str(input())

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def fii():
	return int(stdin.readline())

def fsi():
	return str(stdin.readline())

def fmi():
	return map(int, stdin.readline().split())

def fli():
	return list(fmi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[0]

def sort2(l):
	return sorted(l, key=getKey)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000

def dfs(v, c):
	if visited[v]:
		if col[v] != c:
			print('-1')
			exit()
		return
	col[v] = c
	visited[v] = 1
	for i in graph[v]:
		dfs(i, c ^ 1)

def bfs(d, v):
	q = []
	q.append(v)
	visited[v] = 1
	while len(q) != 0:
		x = q[0]
		q.pop(0)
		for i in d[x]:
			if visited[i] != 1:
				visited[i] = 1
				q.append(i)
		print(x)

def make_graph(e):
	d = defaultdict(list)
	for i in range(e):
		(x, y) = mi()
		d[x].append(y)
		d[y].append(x)
	return d

def gr2(n):
	d = defaultdict(list)
	for i in range(n):
		(x, y) = mi()
		d[x].append(y)
	return d

def connected_components(graph):
	seen = set()

	def dfs(v):
		vs = set([v])
		component = []
		while vs:
			v = vs.pop()
			seen.add(v)
			vs |= set(graph[v]) - seen
			component.append(v)
		return component
	ans = []
	for v in graph:
		if v not in seen:
			d = dfs(v)
			ans.append(d)
	return ans

def primeFactors(n):
	s = set()
	while n % 2 == 0:
		s.add(2)
		n = n // 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			s.add(i)
			n = n // i
	if n > 2:
		s.add(n)
	return s

def find_all(a_str, sub):
	start = 0
	while True:
		start = a_str.find(sub, start)
		if start == -1:
			return
		yield start
		start += len(sub)

def Prime(x):
	if x < 2:
		return False
	for i in range(2, int(sqrt(x)) + 1):
		if x % i == 0:
			return False
	return True
(n, k) = mi()
l = li()
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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
m = max(a)
val = [[] for _ in range(m + 1)]
lenvals = [0 for _ in range(m + 1)]
for el in a:
	temp = el
	c = 0
	val[temp].append(c)
	lenvals[temp] += 1
	while temp > 1:
		temp //= 2
		c += 1
		val[temp].append(c)
		lenvals[temp] += 1
ans = float('inf')
for i in range(1, m + 1):
	if lenvals[i] >= k:
		val[i].sort()
		ans = min(ans, sum(val[i][:k]))
print(ans)


import heapq
import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 2 * pow(10, 5)
h = [[] for _ in range(l + 1)]
for i in a:
	cnt = 0
	j = i
	while j:
		heapq.heappush(h[j], cnt)
		j //= 2
		cnt += 1
	heapq.heappush(h[j], cnt)
ans = 1145141919810
for h0 in h:
	if len(h0) < k:
		continue
	cnt = 0
	for _ in range(k):
		cnt += heapq.heappop(h0)
	ans = min(ans, cnt)
print(ans)


(n, k) = tuple(map(int, input().split()))
arr = list(map(int, input().split()))
arr.sort()
karms = []
for i in arr:
	t = []
	while i > 0:
		t.append(i)
		i //= 2
	t.append(0)
	karms.append(t)
ans = 1000000000000000.0
for i in range(0, arr[-1] + 1):
	count = 0
	for karm in karms:
		if i in karm:
			count += 1
		if count == k:
			break
	if count < k:
		continue
	adds = []
	for karm in karms:
		if i not in karm:
			continue
		adds.append(karm.index(i))
		if len(adds) == k:
			break
	ans = min(ans, sum(adds))
print(ans)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections as col
import math, string
from functools import reduce

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	(N, K) = getInts()
	A = getInts()
	vals = col.defaultdict(list)
	for i in range(N):
		x = A[i]
		curr = 0
		while x:
			vals[x].append(curr)
			x //= 2
			curr += 1
	ans = 10 ** 9
	for i in range(1, 200001):
		vals[i].sort()
		if len(vals[i]) < K:
			continue
		ans = min(ans, sum(vals[i][:K]))
	return ans
print(solve())


import sys
from collections import defaultdict
(n, k) = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
dic = defaultdict(list)
arr.sort()
for i in range(n):
	num = arr[i]
	count = 0
	while num > 0:
		dic[num].append(count)
		num = num >> 1
		count += 1
ans = float('inf')
for i in dic:
	if len(dic[i]) >= k:
		ans = min(ans, sum(dic[i][:k]))
print(ans)


def I():
	return int(input())

def IS():
	return input()

def IL():
	return list(map(int, input().split()))

def IM():
	return list(map(int, input().split()))
(n, k) = IM()
l = IL()
from collections import Counter
c = Counter(l)
if max(c.values()) >= k:
	print(0)
	return
l.sort()
from collections import defaultdict
d = defaultdict(list)
for i in range(n):
	curr = l[i]
	while curr:
		d[l[i], i].append(curr)
		curr //= 2
	d[l[i], i].append(0)
mini = 10 ** 9

def check(i):
	to_make = i
	tot = []
	for j in range(n):
		if i not in d[l[j], j]:
			pass
		else:
			tot.append(d[l[j], j].index(i))
	if len(tot) < k:
		return 10 ** 9
	else:
		tot.sort()
		return sum(tot[:k])
d1 = defaultdict(int)
for i in d:
	a = d[i]
	for a1 in a:
		d1[a1] += 1
cand = [i for i in d1 if d1[i] >= k]
for i in l:
	mini = min(mini, check(i))
for i in range(1000):
	mini = min(mini, check(i))
for i in cand:
	mini = min(mini, check(i))
print(mini)


from collections import defaultdict as DD
import sys
MOD = pow(10, 9) + 7

def IN(f=0):
	if f == 0:
		return [int(i) for i in sys.stdin.readline().split()]
	else:
		return int(sys.stdin.readline())
(n, k) = IN()
a = IN()
b = []
d = DD(list)
for x in a:
	i = 0
	while x != 0:
		d[x].append(i)
		x = x // 2
		i += 1
	d[0].append(i)
ans = 9999999999999
for x in d:
	if len(d[x]) >= k:
		r = d[x]
		r.sort()
		ans = min(ans, sum(r[:k]))
print(ans)


(n, k) = (int(i) for i in input().split())
a = [int(i) for i in input().split()]
a.sort()
ans = -1
for i in range(a[-1] + 1):
	num = 0
	for j in range(n):
		if a[j] >= i:
			break
	count = 0
	while num < k and j < n:
		y = a[j]
		x = i
		count1 = 0
		while y > x:
			y //= 2
			count1 += 1
		if y == x:
			num += 1
			count += count1
		j += 1
	if ans == -1 or (count < ans and num == k):
		ans = count
print(ans)


(n, k) = map(int, input().split())
lis = sorted(map(int, input().split()))
aa = [[0] * 2 for i in range(200001)]
for i in range(n):
	a = lis[i]
	c = 0
	while a >= 0:
		if aa[a][0] < k:
			aa[a][0] += 1
			aa[a][1] += c
		c += 1
		if a == 0:
			break
		a = a // 2
m = 1000000000
for i in range(200001):
	if aa[i][0] == k:
		m = min(m, aa[i][1])
print(m)


def reduce(n):
	a = []
	while n > 0:
		n = n // 2
		a.append(n)
	return a
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(set(a))
b.sort()
from collections import defaultdict
(c, d) = (defaultdict(int), defaultdict(int))
c[0] = 0
d[0] = 0
for i in a:
	c[i] += 1
	d[i] = 0
for i in b:
	(p, q) = (c[i], d[i])
	t = reduce(i)
	t.reverse()
	w = 1
	while t != []:
		r = t.pop()
		x = c[r]
		if x >= k:
			w = w + 1
			continue
		else:
			if x + p <= k:
				c[r] = x + p
				d[r] += w * p
			else:
				z = k - x
				c[r] = k
				d[r] += z * w
			w = w + 1
mi = float('inf')
for i in c:
	if c[i] >= k:
		if d[i] < mi:
			mi = d[i]
print(mi)


from sys import stdin, stdout
(n, k) = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))
ans = 200000
for x in range(0, 200001):
	cnt = 0
	b = []
	for V in a:
		v = V
		num = 0
		while v > x:
			v //= 2
			num += 1
		if v != x:
			num = 200000
		b.append(num)
	b.sort()
	for i in range(k):
		cnt += b[i]
	ans = min(ans, cnt)
stdout.write('%d\n' % ans)


(n, k) = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
B = [0] * (2 * 10 ** 5 + 1)
C = [0] * (2 * 10 ** 5 + 1)
for i in range(n):
	a = A[i]
	cnt = 0
	while a:
		if C[a] < k:
			B[a] += cnt
			C[a] += 1
		a = a // 2
		cnt += 1
	if C[a] < k:
		B[a] += cnt
		C[a] += 1
ans = 10 ** 18
for i in range(len(C)):
	if C[i] >= k:
		ans = min(B[i], ans)
print(ans)


import sys
import math
numlog = dict()
(n, k) = list(map(int, sys.stdin.readline().rstrip().split()))
num = list(map(int, sys.stdin.readline().rstrip().split()))
cnt = list()
for i in range(200001):
	cnt.append([])
for i in range(n):
	t = num[i]
	val = 0
	while t > 0:
		cnt[t].append(val)
		t //= 2
		val += 1
res = 9876543210
for i in range(200001):
	if len(cnt[i]) < k:
		continue
	cnt[i].sort()
	res = min(res, sum(cnt[i][:k]))
print(res)


import math
import operator
import sys
from collections import Counter
from typing import List
input = sys.stdin.readline

def get_degree(n: int):
	return int(math.floor(math.log2(n)))

def solve(n: int, k: int, a: List[int]) -> int:
	number_counter = Counter(a)
	keys = sorted(number_counter.keys())
	base_number_counter = Counter()
	for e in keys:
		v = e
		while v > 0:
			base_number_counter[v] += number_counter[e]
			v //= 2
	values = sorted(filter(lambda x: x[1] >= k, base_number_counter.items()), key=operator.itemgetter(1, 0))
	res = float('inf')
	for (value, count) in values:
		c = 0
		op_count = 0
		for e in keys:
			if c >= k:
				break
			v = e
			shifts = 0
			while v > value:
				v //= 2
				shifts += 1
			if v == value:
				raise_count = min(k - c, number_counter[e])
				c += raise_count
				op_count += raise_count * shifts
		if c >= k:
			res = min(res, op_count)
	return res
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
res = solve(n, k, a)
print(res)


from sys import stdin
input = stdin.readline
(n, k) = map(int, input().split())
arr = [*map(int, input().split())]
cnt = [0 for i in range(200001)]
for i in range(n):
	cnt[arr[i]] += 1
arr.sort()
p = [[] for i in range(200001)]
for i in range(n):
	t = 1
	while arr[i]:
		arr[i] //= 2
		p[arr[i]].append(t)
		t += 1
ans = 1e+18
for i in range(200001):
	if cnt[i] + len(p[i]) >= k:
		ans = min(ans, sum(p[i][:max(0, k - cnt[i])]))
print(ans)


(n, k) = list(map(int, input().split()))
arr = list(map(int, input().split()))
value_lists = [[] for _ in range(2 * 10 ** 5 + 1)]
for val in arr:
	turn = 0
	while val != 1:
		value_lists[val].append(turn)
		val //= 2
		turn += 1
	value_lists[val].append(turn)
mindist = 999999999
for turns_val in value_lists:
	if len(turns_val) < k:
		continue
	turns_val.sort()
	mindist = min(mindist, sum(turns_val[:k]))
print(mindist)


import math
(n, k) = map(int, input().split())
l = [int(i) for i in input().split()]
l.sort()
moves = [0] * 200001
freq = [0] * 200001
ans = 1000000000.0
for i in l:
	freq[i] += 1
for i in range(len(l)):
	count = 0
	a = l[i]
	while a > 1:
		a = a // 2
		count += 1
		if freq[a] < k:
			freq[a] += 1
			moves[a] += count
for i in range(len(freq)):
	if freq[i] >= k:
		ans = min(ans, moves[i])
print(ans)


from collections import defaultdict as dd
t = 1
d = dd(list)
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	arr.sort()
	for i in range(n):
		j = arr[i]
		d[j] += [0]
		co = 1
		while j != 0:
			j = j // 2
			if j in d:
				d[j] += [d[j][-1] + co]
			else:
				d[j] += [co]
			co += 1
	mini = 999999
	for i in d:
		if len(d[i]) >= k:
			mini = min(d[i][k - 1], mini)
	print(mini)


t = 1
for j in range(t):
	(n, k) = list(map(int, input().strip().split()))
	a = list(map(int, input().strip().split()))
	arr = []
	for i in range(2 * 10 ** 5 + 2):
		arr.append([])
	for i in a:
		x = 0
		xx = i
		arr[xx].append(x)
		while xx:
			xx = xx // 2
			x += 1
			arr[xx].append(x)
	op = sum(arr[0])
	for i in arr:
		if len(i) < k:
			continue
		x = i.copy()
		x.sort()
		op = min(op, sum(x[:k]))
	print(op)


vals = [[] for i in range(200 * 1000 + 11)]
ans = 10 ** 5 + 7
(n, k) = map(int, input().split())
(*a,) = map(int, input().split())
for i in range(n):
	x = a[i]
	cur = 0
	while x > 0:
		vals[x].append(cur)
		x //= 2
		cur += 1
for i in range(200 * 1000):
	new = vals[i]
	new.sort()
	if len(new) < k:
		continue
	ans = min(ans, sum(new[:k]))
print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math

def main():
	(n, k) = map(int, input().split(' '))
	a = list(map(int, input().split(' ')))
	if max(Counter(a).values()) >= k:
		print(0)
	else:
		ans = sum(sorted([math.ceil(math.log(x, 2)) for x in a])[:k])
		for x in range(n):
			tmpx = a[x]
			tempadd = 0
			while tmpx > 0:
				temp = []
				for y in range(n):
					if x != y:
						dat = a[y]
						cnt = 0
						while tmpx < dat:
							dat = dat // 2
							cnt += 1
						temp.append(cnt if tmpx == dat else 99999999)
				temp.sort()
				ans = min(ans, sum(temp[0:k - 1]) + tempadd)
				tmpx = tmpx // 2
				tempadd += 1
		print(ans)
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')
main()


(n, k) = map(int, input().split())
s = [int(x) for x in input().split()]
kk = []
uni = dict()
for i in range(0, len(s)):
	N = 2 * s[i]
	c = -1
	while N > 0:
		c += 1
		N = N // 2
		if uni.get(N) == None:
			uni[N] = [c]
			kk.append(N)
		else:
			uni[N].append(c)
ans = 20 * n
for i in kk:
	l = uni[i]
	if len(l) >= k:
		l = sorted(l)
		sumu = 0
		for j in range(k):
			sumu += l[j]
		ans = min(ans, sumu)
print(ans)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
num = [0] * (2 * 10 ** 5 + 1)
count = [0] * (2 * 10 ** 5 + 1)
a.sort()
for i in a:
	j = i
	t = 0
	while j != 0:
		if num[j] < k:
			num[j] += 1
			j = int(j / 2)
			t += 1
			if num[j] < k:
				count[j] += t
		else:
			j = int(j // 2)
m = 100000000
for i in range(len(num)):
	if num[i] == k:
		if count[i] < m:
			m = count[i]
print(m)


(n, k) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = []
for i in range(n):
	b.append([a[i], 0])
	a[i] //= 2
	j = 1
	while a[i] > 0:
		b.append([a[i], j])
		a[i] //= 2
		j += 1
	b.append([a[i], j])
b = sorted(b, key=lambda x: (x[0], x[1]))
minop = 0
su = 0
for i in range(k):
	su += b[i][1]
minop = float('inf')
if b[0][0] == b[k - 1][0]:
	minop = su
for i in range(1, len(b) - k + 1):
	if b[i][0] != b[i + k - 1][0]:
		su += b[i + k - 1][1]
		su -= b[i - 1][1]
		continue
	su += b[i + k - 1][1]
	su -= b[i - 1][1]
	if su < minop:
		minop = su
print(minop)


import heapq
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = [[-1 for i in range(2 * 10 ** 5 + 1)] for j in range(n)]
	l = []
	for i in range(n):
		c = 0
		while True:
			l.append(a[i])
			d[i][a[i]] = c
			if a[i] == 0:
				break
			a[i] //= 2
			c += 1
	ans = float('inf')
	for v in set(l):
		tans = 0
		cnt = 0
		val = []
		heapq.heapify(val)
		for i in range(n):
			if d[i][v] != -1 and cnt != k:
				tans += d[i][v]
				heapq.heappush(val, -d[i][v])
				cnt += 1
			elif d[i][v] != -1 and cnt == k:
				z = -heapq.heappop(val)
				if d[i][v] < z:
					tans -= z
					tans += d[i][v]
					heapq.heappush(val, -d[i][v])
				else:
					heapq.heappush(val, -z)
		if cnt < k:
			continue
		ans = min(ans, tans)
	print(ans)
main()


(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 = 10000000000.0
for i in f:
	if len(f[i]) >= m:
		s = min(s, sum(sorted(f[i])[:m]))
print(s)


from collections import defaultdict
(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
costs = defaultdict(lambda : [])
for ai in a:
	cost = 0
	costs[ai].append(cost)
	while ai != 0:
		ai //= 2
		cost += 1
		costs[ai].append(cost)
min_cost = 99999999
for (key, item) in costs.items():
	if len(item) >= k:
		k_cost = sum(sorted(item[:k]))
		if k_cost < min_cost:
			min_cost = k_cost
print(min_cost)


import sys
import io, os
import math
gcd = math.gcd
sqrt = math.sqrt
ceil = math.ceil
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def strinp(testcases):
	k = 5
	if testcases == -1 or testcases == 1:
		k = 1
	f = str(input())
	f = f[2:len(f) - k]
	return f

def main():
	arr = list(map(int, input().split()))
	n = arr[0]
	k = arr[1]
	arr = list(map(int, input().split()))
	a = max(arr)
	mi = 10 ** 9
	for i in range(a + 1):
		l = []
		for j in range(n):
			c = 0
			f = arr[j]
			while f > i:
				f = f // 2
				c += 1
			if f != i:
				l.append(10 ** 10)
			else:
				l.append(c)
		l.sort()
		s = 0
		for j in range(k):
			s += l[j]
		mi = min(mi, s)
	print(mi)
main()


import math
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
steps = [0] * 200005
count = [0] * 200005
ans = []
for i in range(n):
	x = a[i]
	for j in range(math.floor(math.log2(a[i]) + 2)):
		if count[x] == k:
			ans.append(steps[x])
		count[x] += 1
		steps[x] += j
		x = x // 2
for i in range(200005):
	if count[i] == k:
		ans.append(steps[i])
print(min(ans))