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 2 \cdot 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, \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

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Mathematics

Complete search


Solutions:
import sys
from collections import Counter

def solve():
	(n, k) = list(map(int, sys.stdin.readline().split()))
	a = sorted(list(map(int, sys.stdin.readline().split())))
	cnt = Counter(a)
	opr = cnt.copy()
	opr.clear()
	result = 10 ** 7
	for val in a:
		cur_opr = 0
		while val > 0:
			if cnt[val] >= k:
				result = min(result, opr[val])
			val //= 2
			cur_opr += 1
			opr[val] += cur_opr
			cnt[val] += 1
	print(result)
solve()


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()]
b = []
for i in range(200001):
	b.append([])
for i in a:
	ctr = 0
	while i > 0:
		b[i].append(ctr)
		i //= 2
		ctr += 1
	b[i].append(ctr)
res = inf
for i in b:
	if len(i) >= k:
		i.sort()
		tmp = 0
		for j in range(k):
			tmp += i[j]
		res = min(res, tmp)
print(res)


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
out = 10000000000 + 7
d = [[] for i in range(0, max(l) + 1)]
if k != 1:
	for i in l:
		c = 0
		while i:
			d[i].append(c)
			c += 1
			i //= 2
	for i in d:
		if len(i) >= k:
			out = min(out, sum(i[:k]))
	print(out)
else:
	print(0)


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())
l = list(map(int, input().split()))
b = [[] for _ in range(max(l) + 2)]
for a in l:
	count = 0
	while a > 0:
		b[a].append(count)
		count += 1
		a = a // 2
ans = 10000000000000
for a in b:
	if len(a) >= k:
		ans = min(ans, sum(sorted(a)[:k]))
print(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))


(n, m) = map(int, input().split())
s = str(input())
a = [int(i) for i in s.split()]
b = [0] * 200001
c = [0] * 200001
a.sort()
for elem in a:
	b[elem] += 1
	count = 0
	while elem != 0 and b[elem // 2] < m:
		elem //= 2
		count += 1
		c[elem] += count
		b[elem] += 1
ans = 10000000000
for i in range(len(b)):
	if b[i] >= m:
		if ans > c[i]:
			ans = c[i]
print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

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

def getint():
	return int(input())

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

def getint1():
	return list(map(lambda x: int(x) - 1, input().split()))

def main():
	(n, k) = getints()
	a = Counter(getints())
	ma = max(a)
	v = max(2, math.ceil(math.log2(ma))) + 1
	b = {i: [0] * v for i in range(ma + 1)}
	for i in b:
		if i in a:
			b[i][0] = a[i]
	del a
	for i in b:
		c = i
		pos = 1
		if b[c][0]:
			c //= 2
			while c:
				b[c][pos] += b[i][0]
				pos += 1
				c //= 2
			b[c][pos] += b[i][0]
	out = 99999999999999
	for i in b:
		s = 0
		j = 0
		l = b[i]
		mv = 0
		while j < v and s < k:
			left = k - s
			freq = min(l[j], left)
			mv += j * freq
			j += 1
			s += freq
		if s >= k:
			out = min(out, mv)
	print(out)
main()


from collections import defaultdict, Counter
(n, k) = map(int, input().split())
List = [int(x) for x in input().split()]
List.sort()
count = Counter(List)
for i in count.keys():
	if count[i] >= k:
		print(0)
		exit()
reached = [0] * 200001
cost = [0] * 200001
for i in range(n):
	val = List[i]
	curr_cost = 0
	while val:
		val >>= 1
		curr_cost += 1
		if reached[val] < k - count[val]:
			cost[val] += curr_cost
			reached[val] += 1
ans = 10000000000
for i in range(200001):
	if reached[i] == k - count[i]:
		ans = min(ans, cost[i])
print(ans)


def main():
	(n, m) = map(int, input().split())
	(aa, bb) = ([m] * 200001, [0] * 200001)
	for i in sorted(map(int, input().split())):
		aa[i] -= 1
		t = 0
		while i:
			t += 1
			i //= 2
			if aa[i] <= 0:
				continue
			aa[i] -= 1
			bb[i] += t
	print(min((b for (a, b) in zip(aa, bb) if a <= 0)))
main()


(n, k) = list(map(int, input().split()))
A = list(map(int, input().split()))
G = []
for _ in range(2 * 10 ** 5 + 100):
	G.append([])
c = 0
for i in A:
	if len(G[i]) < k:
		G[i].append(0)
while True:
	c += 1
	f = True
	for i in range(n):
		if A[i]:
			A[i] //= 2
			if len(G[A[i]]) < k:
				G[A[i]].append(c)
		if A[i]:
			f = False
	if f:
		break
ans = 10 ** 9
for t in G:
	if len(t) == k:
		ans = min(ans, sum(t))
print(ans)


from sys import stdin
from copy import deepcopy
from collections import deque, defaultdict

def get_arr(num):
	if num in freq:
		if len(freq[num]) >= k:
			return sum(freq[num][:k])
		else:
			return float('inf')
	else:
		return float('inf')

def get_min(arr):
	for i in freq:
		if freq[i] >= k:
			return 0
	return float('inf')
(n, k) = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
arr.sort()
freq = defaultdict(list)
for num in arr:
	count = 0
	while num > 0:
		freq[num].append(count)
		num //= 2
		count += 1
	freq[0].append(count)
for i in freq:
	freq[i].sort()
ans = float('inf')
m = max(arr)
for i in range(0, m + 1):
	ans = min(ans, get_arr(i))
print(ans)


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()
for i in a:
	cnt[i] += 1
for i in range(400002):
	if i:
		cnt[i] += cnt[i - 1]
mx = a[-1]
import math
ans = math.inf
for i in range(1, mx + 1):
	now = k
	tot = 0
	l = i
	r = i
	st = 0
	while now:
		if 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
		st += 1
	ans = min(ans, tot)
print(ans)


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 = list(map(int, input().split()))
a.sort()
d1 = {}
d2 = {}
ans = 10 ** 9
for i in range(n):
	num = a[i]
	c = 0
	while num > 0:
		d1[num] = c if num not in d1 else d1[num] + c
		d2[num] = 1 if num not in d2 else d2[num] + 1
		if d2[num] == k:
			ans = min(ans, d1[num])
		c += 1
		num //= 2
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 math
import sys
from collections import Counter
from collections import defaultdict
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_dict = defaultdict(list)
	for e in keys:
		v = e
		shifts = 0
		while v > 0:
			base_number_dict[v].extend([shifts] * number_counter[e])
			shifts += 1
			v //= 2
	res = float('inf')
	for key in base_number_dict.keys():
		elems = sorted(base_number_dict[key])
		if len(elems) < k:
			continue
		op_count = sum(elems[: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)


(n, k) = list(map(int, input().split()))
l = list(map(int, input().split()))
s = [[] for i in range(2 * 10 ** 5 + 10)]
for i in l:
	c = 0
	while i:
		s[i].append(c)
		c += 1
		i //= 2
val = 10 ** 9
for i in s:
	if len(i) >= k:
		val = min(val, sum(sorted(i)[:k]))
print(val)


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


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)


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 sys
(n, k) = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
xs = [0]
for i in range(n):
	x = a[i]
	while x != 0:
		xs.append(x)
		x = x // 2
xs = list(set(xs))
op_cnts = dict()
for x in xs:
	op_cnts[x] = []
for i in range(n):
	cnt = 0
	start = a[i]
	while True:
		if start in op_cnts:
			op_cnts[start].append(cnt)
		cnt += 1
		if start == 0:
			break
		start = start // 2
minVal = sys.maxsize
for x in xs:
	if len(op_cnts[x]) >= k:
		op_cnts[x] = sorted(op_cnts[x])
for x in xs:
	if len(op_cnts[x]) >= k:
		sumVal = 0
		for j in range(k):
			sumVal += op_cnts[x][j]
		minVal = min(minVal, sumVal)
print(minVal)


from sys import stdin

def input():
	return next(stdin)

def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	aa.sort()
	valmap = {}
	for a in aa:
		add_to_map(a, 0, k, valmap)
		i = 0
		while a > 0:
			i += 1
			a = a // 2
			add_to_map(a, i, k, valmap)
	min = 20 * k
	for vl in valmap.values():
		if len(vl) == k and sum(vl) < min:
			min = sum(vl)
	print(min)

def add_to_map(a, i, k, valmap):
	if a in valmap:
		if len(valmap[a]) < k:
			valmap[a].append(i)
	else:
		valmap[a] = [i]
main()


def main():
	(n, k) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	nums = [[0 for i in range(2)] for j in range(2 * 10 ** 5 + 1)]
	arr.sort()
	for i in arr:
		moves = 0
		while i >= 0:
			if nums[i][0] == k:
				break
			nums[i][0] += 1
			nums[i][1] += moves
			moves += 1
			i = i // 2
			if i == 0:
				nums[i][0] += 1
				nums[i][1] += moves
				break
	min_moves = float('inf')
	for i in range(2 * 10 ** 5 + 1):
		if nums[i][0] >= k:
			min_moves = min(min_moves, nums[i][1])
	print(min_moves)
main()


import sys
import bisect
import heapq
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
(n, k) = Ri()
a = Ri()
arr = [[] for i in range(2 * 10 ** 5 + 1)]
for i in a:
	cnt = 0
	while i > 0:
		arr[i].append(cnt)
		i = i // 2
		cnt += 1
ans = INF
for i in range(2 * 10 ** 5):
	if len(arr[i]) >= k:
		arr[i].sort()
		summ = sum(arr[i][:k])
		ans = min(ans, summ)
if ans == INF:
	print(-1)
else:
	print(ans)


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)


from sys import stdin

def input():
	return next(stdin)

def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	aa.sort()
	valmap = {}
	for a in aa:
		add_to_map(a, 0, k, valmap)
		i = 0
		while a > 0:
			i += 1
			a = a // 2
			add_to_map(a, i, k, valmap)
	result = min((s for (c, s) in valmap.values() if c == k))
	print(result)

def add_to_map(a, i, k, valmap):
	if a in valmap:
		if valmap[a][0] < k:
			valmap[a][0] += 1
			valmap[a][1] += i
	else:
		valmap[a] = [1, i]
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
from collections import defaultdict
(n, k) = map(int, input().split())
vals = list(map(int, input().split()))
vals.sort()
dict1 = defaultdict(list)
if vals[-1] == 0:
	print(0)
else:
	minsofar = 10 ** 10
	for s in range(len(vals)):
		temp = vals[s]
		count = 0
		while temp > 0:
			if len(dict1[temp]) == 0:
				dict1[temp] = [count]
			else:
				dict1[temp].append(dict1[temp][-1] + count)
			temp = temp // 2
			count += 1
	for s in dict1:
		if len(dict1[s]) >= k:
			minsofar = min(minsofar, dict1[s][k - 1])
	print(minsofar)


from collections import defaultdict
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
vals = defaultdict(list)
ctn = defaultdict(int)
for el in a:
	cur = 0
	while el > 0:
		vals[el].append(cur)
		ctn[el] += 1
		el //= 2
		cur += 1
ans = 99999999999
for (kk, ct) in ctn.items():
	if ct >= k:
		ans = min(ans, sum(sorted(vals[kk])[:k]))
print(ans)


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


from math import *
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = [0 for i in range(200001)]
d = dict()
m = 1000000000.0
a.sort()
for i in range(n):
	ct = 0
	while a[i] != 0:
		if a[i] not in d:
			d[a[i]] = 1
		else:
			d[a[i]] += 1
		l[a[i]] += ct
		if d[a[i]] == k:
			m = min(m, l[a[i]])
		a[i] //= 2
		ct += 1
print(m)


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


def find(A, K):
	counting = [[] for i in range(max(A) + 1)]
	okay = [0] * (max(A) + 1)
	for i in range(len(A)):
		count = 0
		temp = A[i]
		while temp > 0:
			counting[temp] += [count]
			okay[temp] += 1
			temp = temp // 2
			count += 1
		counting[temp] += [count]
		okay[temp] += 1
	MIN = float('inf')
	for i in range(len(okay)):
		if okay[i] >= K:
			counting[i] = sorted(counting[i])
			MIN = min(MIN, sum(counting[i][:K]))
	return MIN
(n, K) = list(map(int, input().strip().split(' ')))
A = list(map(int, input().strip().split(' ')))
print(find(A, K))


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, m) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
c = list(set(a))
b = [[] for i in range(2 * 100000 + 1)]
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 = 2 * 1000000000000000
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())
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)


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


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


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


from collections import defaultdict
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
rec = defaultdict(list)
for i in arr:
	op = 0
	while i > 0:
		rec[i].append(op)
		op += 1
		i = i // 2
ans = 999999999
for i in rec:
	if len(rec[i]) >= k:
		rec[i].sort()
		ans = min(ans, sum(rec[i][:k]))
print(ans)


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


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)


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


def main():
	((n, m), d) = (map(int, input().split()), {})
	for i in map(int, input().split()):
		t = 0
		while i:
			d.setdefault(i, [1000000000]).append(t)
			i >>= 1
			t += 1
	print(min((sum(sorted(v)[:m]) for v in d.values())))
main()


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)


from sys import setcheckinterval, stdin
setcheckinterval(1000)
iin = lambda : int(stdin.readline())
lin = lambda : list(map(int, stdin.readline().split()))
from collections import defaultdict
(n, k) = lin()
a = lin()
a.sort()
sol = [[0, 0] for i in range(2 * 10 ** 5 + 1)]
for i in a:
	ch = 0
	x = i
	if sol[i][0] < k:
		sol[i][0] += 1
	while x > 0:
		x //= 2
		ch += 1
		if sol[x][0] < k:
			sol[x][0] += 1
			sol[x][1] += ch
ans = 99999999999
for (i, j) in sol:
	if i >= k:
		ans = min(ans, j)
print(ans)


import sys
input = sys.stdin.buffer.readline

def solution():
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	l.sort()
	val = [0] * 1000001
	op = [0] * 1000001
	m = 2000000000.0
	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()


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)


vals = [[] for i in range(200 * 1000 + 11)]
ans = 10 ** 19 + 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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
arr = [[] for _ in range(int(200000.0 + 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)


from sys import stdin, stdout
input = stdin.readline
t = 1
for _ in range(t):
	(n, p) = map(int, input().split())
	a = [int(x) for x in input().split()]
	vals = set()
	dict = {}
	for i in a:
		k = 0
		while i:
			if i in dict:
				dict[i].append(k)
			else:
				dict[i] = [k]
			vals.add(i)
			i //= 2
			k += 1
	ans = float('inf')
	for i in dict:
		if len(dict[i]) >= p:
			ans = min(ans, sum(sorted(dict[i])[:p]))
	print(ans)


def amount_divide():
	amount_dividers = [[] for _ in range(2 * 10 ** 5 + 1)]
	for i in range(n):
		num = arr[i]
		j = 0
		while num > 0:
			amount_dividers[num].append(j)
			num //= 2
			j += 1
		amount_dividers[0].append(j)
	ans = 10 ** 15
	for list1 in amount_dividers:
		if len(list1) >= k:
			ans = min(ans, sum(sorted(list1)[:k]))
	return ans
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
print(amount_divide())


import sys
from collections import defaultdict

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
(N, K) = MAP()
A = LIST()
vals = defaultdict(list)
for a in A:
	cnt = 0
	while a > 0:
		vals[a].append(cnt)
		a //= 2
		cnt += 1
	vals[0].append(cnt)
ans = INF
for li in vals.values():
	li.sort()
	if len(li) >= K:
		ans = min(ans, sum(li[: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)


from collections import defaultdict
import sys
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
value = [0]
mapping = defaultdict(list)
for j in range(n):
	x = l[j]
	count = 0
	while True:
		mapping[x].append(count)
		if x == 0:
			break
		x = x // 2
		count += 1
for i in mapping:
	mapping[i].sort()
total = sys.maxsize
for i in mapping:
	if len(mapping[i]) >= m:
		total = min(total, sum(mapping[i][0:m]))
print(total)


import sys

def answer(n, k, a):
	mxa = max(a)
	costs = [[] for _ in range(mxa + 1)]
	for i in range(n):
		temp = a[i]
		cost = 0
		while temp > 0:
			costs[temp].append(cost)
			temp //= 2
			cost += 1
	best = 10 ** 7
	for i in range(1, mxa + 1):
		if len(costs[i]) >= k:
			costs[i].sort()
			best = min(best, sum(costs[i][:k]))
	return best

def main():
	(n, k) = map(int, sys.stdin.readline().split())
	a = list(map(int, sys.stdin.readline().split()))
	print(answer(n, k, a))
	return
main()


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)


from sys import stdin
from collections import *

def arr_inp(n):
	if n == 1:
		return [int(x) for x in stdin.readline().split()]
	elif n == 2:
		return [float(x) for x in stdin.readline().split()]
	else:
		return [str(x) for x in stdin.readline().split()]

def divide(x):
	num = 0
	mem[x][0] += 1
	while x:
		x //= 2
		num += 1
		if mem[x][0] < k:
			mem[x][0] += 1
			mem[x][1] += num
(n, k) = arr_inp(1)
(a, mem) = (sorted(arr_inp(1)), defaultdict(lambda : [0, 0]))
(c, ans) = (Counter(a), float('inf'))
for i in range(n):
	divide(a[i])
for i in range(max(a) + 1):
	if mem[i][0] >= k:
		ans = min(ans, mem[i][1])
print(ans)


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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
cnt = [[] for i in range(2 * 10 ** 5 + 10)]
for num in a:
	tmp_cnt = 0
	while True:
		if num == 0:
			cnt[num].append(tmp_cnt)
			break
		else:
			cnt[num].append(tmp_cnt)
			num = num // 2
			tmp_cnt += 1
ans = 10 ** 9 + 7
for cnt_i in cnt:
	if len(cnt_i) < k:
		continue
	else:
		cnt_i = sorted(cnt_i)
		ans = min(ans, sum(cnt_i[0:k]))
print(ans)


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


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)


(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
a.sort()
d = {}
for i in range(len(a)):
	temp = a[i]
	curr = 0
	while temp:
		if temp not in d or d[temp][0] < k:
			if temp in d:
				d[temp][0] += 1
				d[temp][1] += curr
			else:
				d[temp] = [1, curr]
		curr += 1
		temp = temp >> 1
ans = 10000000000000000
for i in d:
	if d[i][0] >= k:
		ans = min(ans, d[i][1])
print(ans)


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()))
m = max(a) + 1
b = [0] * m
c = [0] * m
for i in a:
	x = i
	cnt = 0
	while x > 0:
		if c[x] < k:
			b[x] += cnt
			c[x] += 1
		x //= 2
		cnt += 1
	if c[0] < k:
		b[0] += cnt
		c[0] += 1
ans = b[0]
for i in range(1, m):
	if c[i] == k:
		ans = min(ans, b[i])
print(ans)


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


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
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)


from collections import *
(n, k) = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
A.sort()
d = defaultdict(lambda : [0, 0])
for i in A:
	num = i
	stp = 0
	while num > 0:
		if d[num][0] < k:
			d[num][0] += 1
			d[num][1] += stp
		num = num // 2
		stp += 1
	if d[num][0] < k:
		d[num][0] += 1
		d[num][1] += stp
mn = 10 ** 20
for i in d:
	if d[i][0] >= k:
		mn = min(d[i][1], mn)
print(mn)


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


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def parseFraction(data):
	idx = data.index('/')
	return [int(data[:idx]), int(data[idx + 1:])]

def main():
	(n, k) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	maxVal = a[0]
	for i in range(1, n):
		maxVal = max(maxVal, a[i])
	a = sorted(a)
	cnt = [0 for i in range(maxVal + 1)]
	required = [0 for i in range(maxVal + 1)]
	ret = 10 ** 9
	for i in range(n):
		curr = a[i]
		operation = 0
		while curr > 0:
			cnt[curr] += 1
			required[curr] += operation
			if cnt[curr] >= k:
				ret = min(ret, required[curr])
			curr //= 2
			operation += 1
		cnt[curr] += 1
		required[curr] += operation
		if cnt[curr] >= k:
			ret = min(ret, required[curr])
	sys.stdout.write(str(ret) + '\n')
main()


(n, k) = map(int, input().split())
x = list(map(int, input().split()))
q = []
for i in range(200001):
	q.append([0, 0])
x.sort()
for i in range(n):
	a = x[i]
	q[a][0] += 1
	c = 0
	while a:
		a = a // 2
		c = c + 1
		if q[a][0] < k:
			q[a][0] += 1
			q[a][1] += c
q.sort(key=lambda x: x[1])
for i in q:
	if i[0] >= k:
		print(i[1])
		break


(n, k) = tuple(map(int, input().split()))
a = list(map(int, input().split()))
a1 = sorted(a)
a = 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]
		else:
			l[i][j] = a[j] // 2
			a[j] = a[j] // 2
value = 10 ** 9
for i in range(20):
	for j in range(n):
		if l[i][j] != 0:
			if l[i][j] not in d:
				d[l[i][j]] = [1, i]
			elif d[l[i][j]][0] < k:
				d[l[i][j]][0] += 1
				d[l[i][j]][1] += i
for i in d:
	if d[i][0] >= k:
		value = min(value, d[i][1])
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)


(n, k) = map(int, input().split())
x = [int(x) for x in input().split()]
counter = [[] for _ in range(max(x) + 1)]
for i in x:
	cnt = 0
	divisible = True
	while divisible:
		counter[i].append(cnt)
		if i == 0:
			divisible = False
		i //= 2
		cnt += 1
answer = pow(10, 10)
for i in counter:
	if len(i) >= k:
		answer = min(answer, sum(sorted(i)[0:k]))
print(answer)


from sys import stdin

def input():
	return next(stdin)

def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	aa.sort()
	valmap = [[0, 0] for _ in range(200001)]
	for a in aa:
		if add_to_map(a, 0, k, valmap):
			i = 0
			while a > 0:
				i += 1
				a = a // 2
				if not add_to_map(a, i, k, valmap):
					break
	result = min((s for (c, s) in valmap if c == k))
	print(result)

def add_to_map(a, i, k, valmap):
	if valmap[a][0] < k:
		valmap[a][0] += 1
		valmap[a][1] += i
		return True
	else:
		return False
main()


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


import sys
input = lambda : sys.stdin.readline().strip()
(n, k) = map(int, input().split())
ls = list(map(int, input().split()))
ls.sort()
arr = []
elem = {}
minSteps = {}
for x in range(ls[-1] + 1):
	elem[x] = 0
	minSteps[x] = 0
for i in ls:
	steps = 0
	while i != 0:
		if elem[i] != k:
			elem[i] += 1
			minSteps[i] += steps
		i //= 2
		steps += 1
	if elem[i] != k:
		elem[i] += 1
		minSteps[i] += steps
m = 1000000000000
for (key, value) in elem.items():
	if value == k:
		m = min(m, minSteps[key])
print(m)


import sys
[n, k] = [int(i) for i in sys.stdin.readline().split()]
a = [int(j) for j in sys.stdin.readline().split()]
arr = []
a.sort()
prev = -2
for i in range(n):
	if prev != a[i]:
		arr.append([a[i], 1])
	else:
		arr[-1][1] += 1
	prev = a[i]
done = 0
for j in range(len(arr)):
	if arr[j][1] >= k:
		done = 1
		break
if done == 1:
	print(0)
else:
	count_arr = []
	for w in range(200001):
		count_arr.append([0, 0])
	ans = sys.maxsize
	for h in range(n):
		count_arr[a[h]][1] += 1
	for g in range(n):
		tmp = a[g]
		tmp //= 2
		step = 1
		while tmp != 0:
			count_arr[tmp][0] += step
			count_arr[tmp][1] += 1
			if count_arr[tmp][1] >= k:
				ans = min(ans, count_arr[tmp][0])
			step += 1
			tmp //= 2
		count_arr[0][0] += step
		count_arr[0][1] += 1
		if count_arr[0][1] >= k:
			ans = min(ans, count_arr[0][0])
	print(ans)


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


MAX = 2 * 10 ** 5

def main():
	(n, k) = list(map(int, input().split()))
	a = sorted(map(int, input().split()))
	ops = [0] * (MAX + 1)
	ks = [0] * (MAX + 1)
	for x in a:
		c = x
		j = 0
		while True:
			if ks[c] < k:
				ops[c] += j
				ks[c] += 1
			if c == 0:
				break
			c //= 2
			j += 1
	min_ops = float('inf')
	for i in range(MAX + 1):
		if ks[i] == k:
			min_ops = min(ops[i], min_ops)
	print(min_ops)
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) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a.sort()
ind = [0] * 200001
cnt = [0] * 200001
ans = []
for key in a:
	ind[key] += 1
tr = False
for key in a:
	if ind[key] >= k:
		ans.append(cnt[key])
	cnnt = 1
	while key > 1:
		key //= 2
		ind[key] += 1
		cnt[key] += cnnt
		if ind[key] >= k:
			ans.append(cnt[key])
		cnnt += 1
print(min(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 math, sys, bisect, heapq, os
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
from functools import lru_cache
pr = lambda x: x

def input():
	return sys.stdin.readline().rstrip('\r\n')
aj = lambda : list(map(int, input().split()))

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])

def solve():
	(n, k) = aj()
	A = aj()
	C = Counter(A)
	xx = C.most_common(1)[0][1]
	if xx >= k:
		print(0)
		exit(0)
	A.sort()
	C = Counter()
	Ans = Counter()
	ans = 1000000000.0
	for i in A:
		C[i] += 1
		if C[i] >= k:
			ans = min(ans, Ans[i])
		s = 0
		while i != 0:
			i = i // 2
			s += 1
			C[i] += 1
			Ans[i] += s
			if C[i] >= k:
				ans = min(ans, Ans[i])
	print(ans)
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
	from aj import *
except:
	pass
solve()


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

def main():
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	c = dict()
	mx = 0
	for item in arr:
		if item not in c:
			c[item] = 0
		c[item] += 1
		if mx < item:
			mx = item
		if c[item] >= k:
			print(0)
			exit()
	l = [[] for _ in range(mx + 1)]
	arr.sort()
	z = 0
	while z < n:
		t = arr[z]
		zz = 0
		while t:
			l[t] += [zz for _ in range(c[arr[z]])]
			zz += 1
			t //= 2
		z += c[arr[z]]
	ans = inf
	for item in l:
		if len(item) >= k:
			ans = min(ans, sum(item[: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()


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)


from collections import defaultdict
from math import floor
d = defaultdict(list)
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
for i in a:
	(c, tmp) = (0, i)
	while True:
		d[tmp].append(c)
		if tmp == 0:
			break
		tmp = floor(tmp / 2)
		c += 1
mn = 2 * 10 ** 18
for ke in d:
	ans = 0
	l = len(d[ke])
	if l < k:
		continue
	fin = sorted(d[ke])
	ans = sum(fin[:k])
	mn = min(mn, ans)
print(mn)


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 collections import defaultdict as dfd
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
d = dfd(int)
value = None
ans = 999999999
cost = [[] for i in range(max(arr) + 1)]
for i in arr:
	d[i] += 1
	cost[i].append(0)
	j = i
	propogate = 0
	while j > 0:
		j //= 2
		d[j] += 1
		propogate += 1
		cost[j].append(propogate)
for (i, j) in d.items():
	if j >= k:
		cost[i].sort()
		ans = min(ans, sum(cost[i][:k]))
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 = 999999999999
	for i in d:
		if len(d[i]) >= k:
			mini = min(d[i][k - 1], mini)
	print(mini)


def inti_dic(d, no, opertions):
	if no in d:
		a = d[no]
		if a[0] < k:
			a[0] += 1
			a[1] += op
			d[no] = a
	else:
		d[no] = [1, opertions]
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
d = {}
arr = sorted(arr)
for i in arr:
	(no, op) = (i, 0)
	inti_dic(d, no, op)
	while no != 0:
		no = no // 2
		op += 1
		inti_dic(d, no, op)
minn = 10 ** 15
for i in d:
	a = d[i]
	if a[0] >= k:
		minn = min(a[1], minn)
print(minn)


import sys
import math
input = sys.stdin.readline
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
l = [[0 for i in range(2)] for j in range(2 * 10 ** 5 + 1)]
for i in range(n):
	l[arr[i]][1] += 1
	cnt = 0
	while arr[i] > 0:
		arr[i] = arr[i] // 2
		cnt += 1
		if l[arr[i]][1] < k:
			l[arr[i]][0] += cnt
			l[arr[i]][1] += 1
ans = 100000000000
for i in range(len(l)):
	if l[i][1] >= k:
		ans = min(ans, l[i][0])
print(ans)


import sys, math
input = sys.stdin.readline

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

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

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

def getStr():
	return input().strip()
(n, k) = getVars()
a = getList()
d = {}
for x in a:
	x2 = x
	num = 0
	while x2 > 0:
		if x2 not in d:
			d[x2] = []
		d[x2].append(num)
		x2 //= 2
		num += 1
minS = -1
for key in d:
	if len(d[key]) >= k:
		dKey = d[key].copy()
		dKey.sort()
		s = sum(dKey[:k])
		if minS == -1:
			minS = s
		else:
			minS = min(minS, s)
print(minS)


from math import inf
nk = input().split()
n = int(nk[0])
k = int(nk[1])
a = [int(ai) for ai in input().split()]
a.sort()
possibilities = {}
for ai in a:
	moves = 0
	while ai != 0:
		if ai not in possibilities:
			possibilities[ai] = (1, moves)
		else:
			curr = possibilities[ai]
			if curr[0] != k:
				possibilities[ai] = (curr[0] + 1, curr[1] + moves)
		ai = ai // 2
		moves += 1
minOps = inf
for i in possibilities:
	curr = possibilities[i]
	if curr[0] == k:
		if curr[1] < minOps:
			minOps = curr[1]
print(minOps)


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)


from collections import defaultdict
from sys import stdin
input = stdin.readline
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
dct = defaultdict(lambda : [])
for x in arr:
	i = 0
	while x > 0:
		dct[x].append(i)
		x //= 2
		i += 1
ndct = {}
for (key, v) in dct.items():
	if len(v) >= k:
		v.sort()
		ndct[key] = sum(v[:k])
print(min((v for (_, v) in ndct.items())))


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


(n, k) = [int(j) for j in input().split()]
l = [int(j) for j in input().split()]
num = int(2 * 100000.0 + 5)
arr = [[] for i in range(num)]
for i in range(n):
	cnt = 0
	tmp = l[i]
	while tmp > 0:
		arr[tmp].append(cnt)
		tmp = tmp // 2
		cnt += 1
ans = 1000000000000.0
for i in range(1, num):
	if len(arr[i]) >= k:
		arr[i].sort()
		ans = min(ans, sum(arr[i][:k]))
print(ans)


import math
(n, k) = map(int, input().split())
numbers = list(map(int, input().split()))
divisors = {}
for v in numbers:
	cnt = 0
	if not v in divisors.keys():
		divisors[v] = []
	while v > 0:
		if not v in divisors.keys():
			divisors[v] = []
		divisors[v].append(cnt)
		v //= 2
		cnt += 1
	if not v in divisors.keys():
		divisors[v] = []
	divisors[v].append(cnt)
answer = 2 ** 64
for cnt in filter(None, divisors.values()):
	cnt.sort()
	if len(cnt) >= k and len(cnt) > 0:
		answer = min(answer, sum(cnt[:k]))
print(answer)


def cal_dis(num, val):
	count = 0
	while num > 0:
		if val[num] == 0:
			val[num] = []
		val[num].append(count)
		num = num // 2
		count += 1
	return (count, val)
(n, k) = (int(x) for x in input().split())
seq = [int(x) for x in input().split()]
ans = 1000000000.0
val = 200009 * [0]
for ele in seq:
	(count, val) = cal_dis(ele, val)
for lis in val:
	if lis != 0:
		if lis.__len__() >= k:
			lis.sort()
			sum = 0
			for ele in lis[:k]:
				sum += ele
			ans = min(ans, sum)
print(ans)


import sys
input = sys.stdin.readline
MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input().strip('\n'))
si = lambda : input().strip('\n')
dgl = lambda : list(map(int, input().strip('\n')))
f = lambda : map(int, input().strip('\n').split())
il = lambda : list(map(int, input().strip('\n').split()))
ls = lambda : list(input().strip('\n'))
lsi = lambda : [int(i) for i in ls()]
let = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(1):
	(n, k) = f()
	l = il()
	mx = max(l)
	cost = [[] for i in range(mx + 1)]
	for i in l:
		x = 0
		while i > 0:
			cost[i].append(x)
			x += 1
			i //= 2
		cost[0].append(x)
	mn = 10 ** 15
	for i in range(mx + 1):
		if len(cost[i]) >= k:
			cost[i].sort()
			mn = min(mn, sum(cost[i][:k]))
	print(mn)


(n, k) = map(int, input().split())
x = [int(n) for n in input().split()]
a = []
m = {}
ans = 10000000000
if k != 1:
	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)
else:
	c = 0
	print(c)


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

def main():
	(n, k) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	arr = sorted(arr)
	mxm = arr[-1]
	req = [0 for i in range(mxm + 1)]
	cnt = [0 for i in range(mxm + 1)]
	ans = inf
	for curr in arr:
		zz = 0
		while curr:
			cnt[curr] += 1
			req[curr] += zz
			if cnt[curr] >= k:
				ans = min(ans, req[curr])
			curr //= 2
			zz += 1
		cnt[curr] += 1
		req[curr] += zz
		if cnt[curr] >= k:
			ans = min(ans, req[curr])
	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()


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)


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


from sys import stdin
(n, k) = [int(i) for i in stdin.readline().strip().split()]
a = [int(i) for i in stdin.readline().strip().split()]
p = [19 * [0] for _ in range(max(a) + 1)]
nums = set()
for m in a:
	for i in range(19):
		p[m >> i][i] += 1
		nums.add(m >> i)
		if m >> i == 0:
			break
res = 10000000000000000000
for m in nums:
	d = p[m]
	sum = 0
	steps = 0
	for i in range(19):
		if sum + d[i] >= k:
			add = (k - sum) * i
			steps += add
			res = min(steps, res)
			break
		else:
			sum += d[i]
			steps += i * d[i]
print(res)


from collections import Counter, defaultdict
from math import inf
(n, k) = map(int, input().split())
a = [int(x) for x in input().split()]
z = defaultdict(list)
for i in a:
	c = 0
	while i:
		z[i].append(c)
		c += 1
		i >>= 1
an = inf
for i in z:
	if len(z[i]) >= k:
		z[i].sort()
		s = 0
		for j in range(k):
			s += z[i][j]
		an = min(s, an)
print(an)


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


(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())
L = sorted(list(map(int, input().split())))
M = [[] for i in range(L[-1] + 1)]
for i in range(n):
	ct = 0
	a = L[i]
	while True:
		M[a] += [ct]
		ct += 1
		a //= 2
		if a == 0:
			M[0] += [ct]
			break
ans = None
for m in M:
	if len(m) < k:
		continue
	if ans == None:
		ans = sum(m[:k])
	else:
		ans = min(ans, sum(m[:k]))
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)


import bisect
from itertools import accumulate, count
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
from sys import maxsize
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

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

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def SieveOfEratosthenes(n):
	prime = []
	primes = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if primes[p] == True:
			prime.append(p)
			for i in range(p * p, n + 1, p):
				primes[i] = False
		p += 1
	return prime

def primefactors(n):
	fac = []
	while n % 2 == 0:
		fac.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 2):
		while n % i == 0:
			fac.append(i)
			n = n // i
	if n > 1:
		fac.append(n)
	return sorted(fac)

def factors(n):
	fac = set()
	fac.add(1)
	fac.add(n)
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			fac.add(i)
			fac.add(n // i)
	return list(fac)

def modInverse(a, m):
	m0 = m
	y = 0
	x = 1
	if m == 1:
		return 0
	while a > 1:
		q = a // m
		t = m
		m = a % m
		a = t
		t = y
		y = x - q * y
		x = t
	if x < 0:
		x = x + m0
	return x
(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
dic = {}
f = -1
dic = {}
for i in range(0, len(a)):
	temp = a[i]
	count = 0
	while temp:
		if temp in dic:
			dic[temp].append(count)
		else:
			dic[temp] = [count]
		count += 1
		temp = temp // 2
fans = 1e+18
for i in dic:
	if len(dic[i]) >= k:
		fans = min(fans, sum(sorted(dic[i])[:k]))
print(fans)


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)


(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 sys import stdin

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

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

def linput():
	return list(map(int, stdin.readline().split()))
(n, k) = minput()
a = linput()
mn = float('inf')
d = [[] for _ in range(200001)]
for i in range(n):
	temp = a[i]
	c = 0
	while temp:
		d[temp].append(c)
		c += 1
		temp //= 2
for i in range(200001):
	if len(d[i]) >= k:
		d[i].sort()
		mn = min(mn, sum(d[i][:k]))
print(mn)


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

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)
		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
m = 10 ** 9
for i in count:
	if count[i] == k:
		m = min(m, div[i])
print(m)


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


from sys import stdin, stdout

def __starting_point():
	(n, k) = list(map(int, stdin.readline().split()))
	a = list(map(int, stdin.readline().split()))
	num = [[] for i in range(200005)]
	ans = 200000 * 100
	for x in a:
		cnt = 0
		while x > 0:
			num[x].append(cnt)
			x //= 2
			cnt += 1
		num[x].append(cnt)
	for i in range(200001):
		if len(num[i]) < k:
			continue
		num[i].sort()
		cnt = 0
		for j in range(k):
			cnt += num[i][j]
		ans = min(ans, cnt)
	stdout.write('%d\n' % ans)
__starting_point()