You are given the array $a$ consisting of $n$ elements and the integer $k \le n$.

You want to obtain at least $k$ equal elements in the array $a$. In one move, you can make one of the following two operations:

  Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $a$ is $mn$ then you choose such index $i$ that $a_i = mn$ and set $a_i := a_i + 1$);  take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $a$ is $mx$ then you choose such index $i$ that $a_i = mx$ and set $a_i := a_i - 1$). 

Your task is to calculate the minimum number of moves required to obtain at least $k$ equal elements in the array.


-----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 $a$ and the required number of equal elements.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$.


-----Output-----

Print one integer — the minimum number of moves required to obtain at least $k$ equal elements in the array.


-----Examples-----
Input
6 5
1 2 2 4 2 3

Output
3

Input
7 5
3 3 2 1 1 1 3

Output
4

Source: codeforces | Difficulty: HARD
Tags: Greedy algorithms


Solutions:
MAX = 2 * 10 ** 5

def main():
	(n, k) = 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()


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)


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


import sys

def convert_to_bin(x):
	res = ''
	while x > 0:
		if x % 2 == 0:
			res += '0'
		else:
			res += '1'
		x = x // 2
	return res[::-1]
in_file = sys.stdin
(n, k) = map(int, in_file.readline().strip().split())
A = list(map(int, in_file.readline().strip().split()))
A = [convert_to_bin(a) for a in A]
lookup = {}
kids = []
parent = []
count = []
best = []
for a in A:
	t = ''
	for i in range(len(a)):
		prev = t
		t += a[i]
		if t not in lookup:
			lookup[t] = len(kids)
			if i != 0:
				kids[lookup[prev]].append(len(kids))
				parent.append(lookup[prev])
			else:
				parent.append(-1)
			kids.append([])
			count.append(0)
			best.append([-1 for i in range(k + 1)])
			best[-1][0] = 0
		if i == len(a) - 1:
			count[lookup[t]] += 1

def dp(i, k):
	if k < 0:
		return 0
	if best[i][k] != -1:
		return best[i][k]
	if count[i] >= k:
		best[i][k] = 0
		return 0
	best[i][k] = (len(A) + 1) * (len(A) + 1) * (len(A) + 1)
	if len(kids[i]) == 1:
		best[i][k] = k - count[i] + dp(kids[i][0], k - count[i])
	elif len(kids[i]) == 2:
		for j in range(k - count[i] + 1):
			best[i][k] = min(best[i][k], k - count[i] + dp(kids[i][0], j) + dp(kids[i][1], k - count[i] - j))
	return best[i][k]
m = (len(A) + 1) * (len(A) + 1) * (len(A) + 1)
for i in range(len(kids)):
	if m > dp(i, k):
		m = dp(i, k)
sys.stdout.write(str(m))
sys.stdout.flush()


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


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


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


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)


import sys, os, io
import math, bisect, operator
(inf, mod) = (float('inf'), 10 ** 9 + 7)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int, input().split()))
(n, k) = Neo()
A = Neo()
c = []
d = [[0, c.copy()] for i in range(max(A) + 1)]
Ans = inf
for i in A:
	t = 0
	while True:
		d[i][0] += 1
		d[i][1].append(t)
		if i == 0:
			break
		t += 1
		i = i // 2
for (i, j) in d:
	if i >= k:
		Ans = min(Ans, sum(sorted(j)[:k]))
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()))
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)


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) = map(int, input().split(' '))
a = [int(i) for i in input().split(' ')]
h = max(a)
a.sort()
a1 = [0] * 200010
a2 = [0] * 200010
for i in range(len(a)):
	sum = 0
	while a[i]:
		if a1[a[i]] < k:
			a1[a[i]] += 1
			a2[a[i]] += sum
		a[i] = a[i] // 2
		sum += 1
answ = 10000000000
for i in range(h + 1):
	if a1[i] == k:
		answ = min(answ, a2[i])
print(answ)


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


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)


(N, K) = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
lk = [0] * (2 * 10 ** 5 + 1)
ts = []
for i in range(2 * 10 ** 5 + 1):
	ts.append([9999999])
for n in l:
	t = n
	c = 0
	while True:
		if t == 0:
			break
		lk[t] += 1
		ts[t].append(c)
		t //= 2
		c += 1
mn = 9999999
for i in range(len(lk) - 1, -1, -1):
	if lk[i] >= K:
		ts[i].sort()
		mn = min(mn, sum(ts[i][:K]))
print(mn)


import sys, bisect
from math import log2 as log
mod = int(1000000000.0) + 7
inf = int(10000000000.0)
input = sys.stdin.readline
(n, k) = map(int, input().split())
lis = sorted(map(int, input().split()))
last = int(200000.0) + 1
answer = inf
for i in range(1, last):
	(x, y) = (bisect.bisect_left(lis, i), bisect.bisect_right(lis, i))
	f = y - x
	ans = 0
	for j in range(y, n):
		tt = lis[j]
		c = 0
		while tt != 1:
			if tt == i:
				break
			tt = tt // 2
			c += 1
		if tt == i:
			f += 1
			ans += c
		if f >= k:
			break
	if f >= k:
		answer = min(answer, ans)
print(answer)


from sys import stdin
input = stdin.readline
inf = 1000 * 1000 * 1000
(n, k) = 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, 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)


import sys
import copy
sys.setrecursionlimit(1000000)
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
B = [[] for i in range(200200)]
for i in range(n):
	cnt = 0
	while a[i] > 0:
		B[a[i]].append(cnt)
		cnt += 1
		a[i] //= 2
	B[a[i]].append(cnt)
ans = 1e+20
for i in range(len(B)):
	if len(B[i]) >= k:
		B[i].sort()
		ans = min(ans, sum(B[i][0: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()


def check(a, b):
	answ = 0
	while 1:
		if a == b:
			return answ
		if a > b:
			answ += 1
			a //= 2
		else:
			return -1
a = [int(i) for i in input().split()]
n = a[0]
k = a[1]
mas = [int(i) for i in input().split()]
steps = 10000000
for b in range(0, max(mas) + 1):
	buf = []
	for i in mas:
		tmp = check(i, b)
		if tmp >= 0:
			buf.append(tmp)
	if len(buf) >= k:
		buf.sort()
		Bsum = 0
		for i in range(k):
			Bsum += buf[i]
		if steps > Bsum:
			steps = Bsum
print(steps)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
vals = []
for i in range(0, 200001):
	vals.append([])
for i in range(0, len(a)):
	x = a[i]
	curr = 0
	while x > 0:
		vals[x].append(curr)
		x = x // 2
		curr = curr + 1
ans = 1000000000.0
for i in range(0, 200001):
	if len(vals[i]) >= k:
		vals[i].sort()
		sum = 0
		for j in range(0, k):
			sum = sum + vals[i][j]
		ans = min(ans, sum)
print(ans)


import sys
input = sys.stdin.readline
from collections import defaultdict
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
dl = defaultdict(list)
for i in range(n):
	ai = a[i]
	cnt = 0
	while True:
		dl[ai].append(cnt)
		if ai == 0:
			break
		ai //= 2
		cnt += 1
ans = 10 ** 18
for l in dl.values():
	if len(l) < k:
		continue
	l.sort()
	ans = min(ans, sum(l[:k]))
print(ans)


from collections import Counter
from math import *
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
ans = float('inf')
res = []
for i in a:
	while i > 0:
		res.append(i)
		i //= 2
for i in res:
	arr = []
	for j in range(n):
		x = a[j]
		count = 0
		while x > i:
			x //= 2
			count += 1
		if x == i:
			arr.append(count)
	if len(arr) < k:
		continue
	arr.sort()
	ans = min(ans, sum(arr[:k]))
print(ans)


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


(n, k) = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]
dics = []
for i in range(20):
	dics.append({})
for d in data:
	ln = len(bin(d)) - 2
	for i in range(ln, -1, -1):
		if d not in dics[i]:
			dics[i][d] = [0] * 20
			dics[i][d][ln - i] = 1
		else:
			dics[i][d][ln - i] += 1
		d >>= 1
mn = 1 << 30
for i in range(20):
	dic = dics[i].values()
	found = False
	for d in dic:
		if sum(d) >= k:
			found = True
			left = k
			val = 0
			for i in range(20):
				if d[i] >= left:
					val += i * left
					break
				else:
					val += i * d[i]
					left -= d[i]
			if val < mn:
				mn = val
	if not found:
		break
print(mn)


from collections import Counter
import sys
from itertools import accumulate

def go():
	(n, k) = list(map(int, input().split()))
	a = sorted(map(int, input().split()))
	c = Counter(a)
	if max(c.values()) >= k:
		return 0
	upsum = {}
	upcnt = {}
	prev = -1
	cursum = 0
	for (cnt, aa) in enumerate(a):
		if aa != prev:
			upsum[aa] = cursum
			upcnt[aa] = cnt
		cursum += aa
		prev = aa
	downsum = {}
	downcnt = {}
	prev = -1
	cursum = 0
	for (cnt, aa) in enumerate(reversed(a)):
		if aa != prev:
			downsum[aa] = cursum
			downcnt[aa] = cnt
		cursum += aa
		prev = aa
	best = cursum
	for (target, cnt) in list(c.items()):
		need = k - cnt
		if upcnt[target] >= need:
			best = min(best, (target - 1) * upcnt[target] - upsum[target] + need)
		if downcnt[target] >= need:
			best = min(best, downsum[target] - (target + 1) * downcnt[target] + need)
		best = min(best, (target - 1) * upcnt[target] - upsum[target] + downsum[target] - (target + 1) * downcnt[target] + need)
	return best
t = 1
for _ in range(t):
	print(go())


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


def get(a):
	return max([a.count(i) for i in set(a)])
(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = a.copy()
can = set()
can.add(0)
for i in range(n):
	while b[i] != 0:
		can.add(b[i])
		b[i] //= 2
can = list(can)
ans = []
for i in range(len(can)):
	b = a.copy()
	local_ans = 0
	count = 0
	for j in range(n):
		now_count = 0
		while b[j] > can[i]:
			b[j] //= 2
			now_count += 1
		if b[j] == can[i]:
			count += now_count
			local_ans += 1
		if local_ans >= k:
			break
	if local_ans >= k:
		ans.append(count)
print(min(ans))


from collections import Counter
(n, k) = map(int, input().split())
xs = sorted(map(int, input().split()))
c = Counter(xs)
csuml = 0
lcnt = 0
csumr = sum(xs)
rcnt = len(xs)
ans = csumr
for (x, cnt) in sorted(c.items()):
	r = max(0, k - cnt)
	if not r:
		ans = 0
		break
	csumr -= x * cnt
	rcnt -= cnt
	ansl = lcnt * (x - 1) - csuml + min(lcnt, r)
	if lcnt < r:
		ansl += csumr - rcnt * (x + 1) + r - lcnt
	ansr = csumr - rcnt * (x + 1) + min(rcnt, r)
	if rcnt < r:
		ansr += lcnt * (x - 1) - csuml + r - rcnt
	ans = min(ans, ansl, ansr)
	csuml += x * cnt
	lcnt += cnt
print(ans)


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


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


from sys import stdin, stdout

def write(_s):
	stdout.write(_s)

def write_int(_s):
	stdout.write(str(_s))

def write_list(_l):
	stdout.write(' '.join(map(str, _l)))

def read():
	return stdin.readline().split(' ')

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

def read_int_l():
	return map(int, stdin.readline().split(' '))
(n, k) = read_int_l()
a = sorted(read_int_l())
pref_sum = [0] * (n + 1)
for i in range(n):
	pref_sum[i + 1] += pref_sum[i] + a[i]
min_moves = float('inf')
n_to_left = 0
while n_to_left < n:
	n_to_right = n_to_left
	while n_to_right < n and a[n_to_right] == a[n_to_left]:
		n_to_right += 1
	curr_element = a[n_to_left]
	same_element_count = n_to_right - n_to_left
	cost_left = n_to_left * (curr_element - 1) - pref_sum[n_to_left]
	cost_right = pref_sum[n] - pref_sum[n_to_right] - (curr_element + 1) * (n - n_to_right)
	if same_element_count >= k:
		min_moves = 0
	if same_element_count + n_to_left >= k:
		min_moves = min(min_moves, cost_left + (k - same_element_count))
	if same_element_count + (n - n_to_right) >= k:
		min_moves = min(min_moves, cost_right + (k - same_element_count))
	min_moves = min(min_moves, cost_left + cost_right + (k - same_element_count))
	n_to_left = n_to_right
write_int(max(min_moves, 0))


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


(n, k) = map(int, input().split())
a = [int(o) for o in input().split()]
arr = [[] for i in range(200005)]
for i in range(n):
	lol = a[i]
	j = 0
	arr[lol].append(j)
	while lol != 0:
		lol //= 2
		j += 1
		arr[lol].append(j)
ans = []
for i in range(200005):
	if len(arr[i]) >= k:
		arr[i].sort()
		ans.append(sum(arr[i][:k]))
print(min(ans))


(n, k) = map(int, input().split())
t = list(map(int, input().split()))
t = sorted(t)
if n == k and k == 2:
	print(abs(t[0] - t[1]))
	exit(0)
if t[0] == t[-1]:
	print(0)
	exit(0)
t_sum_r = [t[-1]]
for x in range(0, n - k + 1):
	if t[x] == t[x + k - 1]:
		print(0)
		exit(0)
for x in range(2, n + 1):
	t_sum_r.append(t[-x] + t_sum_r[x - 2])
t_sum_l = 0
sum_l = t[0]
wyn = 10 ** 16
curr_wyn_l = 10 ** 16
curr_wyn_r = 10 ** 16
curr_wyn_lr = 10 ** 16
curr_min = 10 ** 16
for x in range(1, n - 1):
	cost_l = x * (t[x] - 1) - sum_l + 1
	cost_r = t_sum_r[-x - 2] - (n - x - 1) * (t[x] + 1) + 1
	el_l = x
	el_r = n - x - 1
	sum_l += t[x]
	if el_l + 1 >= k:
		curr_wyn_l = cost_l + (k - 2)
	if el_r + 1 >= k:
		curr_wyn_r = cost_r + (k - 2)
	curr_wyn_lr = cost_l + cost_r + (k - 3)
	curr_min = min(curr_wyn_lr, curr_wyn_l, curr_wyn_r)
	if curr_min <= wyn:
		wyn = curr_min
print(wyn)


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)


import math
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
a = sorted(l)
mans = 10000000
for k in range(0, n - m + 1):
	x = int(math.log(a[k], 2))
	for i in range(x + 2):
		ans = i
		equal = a[k] // 2 ** i
		count = 1
		flag = 0
		for j in range(k + 1, n):
			temp = a[j]
			op = 0
			if count == m:
				break
			else:
				while temp > equal:
					temp = temp // 2
					op += 1
				if temp == equal:
					count += 1
					ans += op
		if count != m:
			flag = 1
		if flag == 0:
			if ans < mans:
				mans = ans
print(mans)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
b = [[] for i in range(2 * 10 ** 5 + 1)]
for i in a:
	cnt = 0
	while i > 0:
		b[i].append(cnt)
		cnt += 1
		i //= 2
ans = int(1000000000.0)
for a in b:
	if len(a) >= k:
		ans = min(ans, sum(sorted(a)[:k]))
print(ans)


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


from collections import Counter
from bisect import bisect, bisect_left
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a = Counter(a)
c = sorted(Counter(a).items())
keys = sorted(Counter(a).keys())
m = len(c)
l_cum = [c[0][0] * c[0][1]]
l_cnt = [c[0][1]]
for i in range(1, m):
	l_cum.append(l_cum[-1] + c[i][0] * c[i][1])
	l_cnt.append(l_cnt[-1] + c[i][1])
r_cum = [0 for _ in range(m)]
r_cum[-1] = c[-1][0] * c[-1][1]
r_cnt = [0 for _ in range(m)]
r_cnt[-1] = c[-1][1]
for i in range(m - 2, -1, -1):
	r_cum[i] = r_cum[i + 1] + c[i][0] * c[i][1]
	r_cnt[i] = r_cnt[i + 1] + c[i][1]
ans = 10 ** 20
for i in range(m):
	c_num = a[keys[i]]
	if c_num >= k:
		ans = 0
		break
	if i > 0:
		l_res = (keys[i] - 1) * l_cnt[i - 1] - l_cum[i - 1]
		l_num = l_cnt[i - 1]
	else:
		l_res = 10 ** 30
		l_num = 0
	if i < m - 1:
		r_res = r_cum[i + 1] - (keys[i] + 1) * r_cnt[i + 1]
		r_num = r_cnt[i + 1]
	else:
		r_res = 10 ** 30
		r_num = 0
	if c_num + l_num < k and c_num + r_num < k:
		ans = min(ans, l_res + r_res + k - c_num)
	elif c_num + l_num < k:
		ans = min(ans, r_res + k - c_num)
	elif c_num + r_num < k:
		ans = min(ans, l_res + k - c_num)
	else:
		ans = min(ans, min(r_res, l_res) + k - c_num)
print(ans)


from sys import stdin, gettrace
from collections import Counter

def input():
	return stdin.buffer.readline()

def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	aac = sorted(Counter(aa).most_common())
	lac = len(aac)
	prefcount = 0
	prefcost = 0
	prefcosts = [0] * lac
	prefcounts = [0] * lac
	pa = 0
	for (i, (a, c)) in enumerate(aac):
		prefcost += prefcount * (a - pa)
		prefcount += c
		prefcosts[i] = prefcost
		prefcounts[i] = prefcount
		pa = a
	sufcount = 0
	sufcost = 0
	sufcosts = [0] * lac
	sufcounts = [0] * lac
	pa = 0
	for (i, (a, c)) in enumerate(aac[::-1], 1):
		if c >= k:
			print(0)
			return
		sufcost += sufcount * (pa - a)
		sufcount += c
		sufcosts[lac - i] = sufcost
		sufcounts[lac - i] = sufcount
		pa = a
	best = int(1e+19)
	for i in range(lac):
		if prefcounts[i] >= k:
			lc = prefcosts[i - 1] + (aac[i][0] - aac[i - 1][0] - 1) * prefcounts[i - 1] + k - aac[i][1]
		else:
			lc = prefcosts[i] + sufcosts[i + 1] + sufcounts[i + 1] * (aac[i + 1][0] - aac[i][0] - 1) + k - prefcounts[i]
		if sufcounts[i] >= k:
			rc = sufcosts[i + 1] + (aac[i + 1][0] - aac[i][0] - 1) * sufcounts[i + 1] + k - aac[i][1]
		else:
			rc = sufcosts[i] + prefcosts[i - 1] + prefcounts[i - 1] * (aac[i][0] - aac[i - 1][0] - 1) + k - sufcounts[i]
		best = min(lc, rc, best)
	print(best)
main()


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


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
from collections import defaultdict
(n, k) = RMI()
vals = RMI()
valids = defaultdict(list)
for i in vals:
	has = 0
	while i != 0:
		valids[i].append(has)
		has += 1
		i //= 2
mins = max_val
for i in valids.values():
	if len(i) >= k:
		i.sort()
		mins = min(mins, sum(i[:k]))
print(mins)


import math
l = [int(i) for i in input().split(' ')]
n = l[0]
k = l[1]
ln = [int(i) for i in input().split(' ')]
ln = sorted(ln)
m = 1000000000

def findPart(n, a, d):
	s1 = []
	s2 = []
	s3 = []
	for i in range(0, len(a)):
		n = math.floor(math.log(a[i], 2)) + 1
		if n - d < 0:
			s3.append(a[i])
			continue
		bt = a[i] & 1 << n - d
		if bt == 0:
			s1.append(a[i])
		else:
			s2.append(a[i])
	ops = []
	for i in range(0, len(a)):
		n = math.floor(math.log(a[i], 2)) + 1
		ops.append(n - (d - 1))
	m = sum(ops[:k])
	if len(a) - len(s3) >= k:
		if len(s1) >= k and len(s2) >= k:
			m = min(m, findPart(n * 2, s1, d + 1), findPart(n * 2 + 1, s2, d + 1))
		elif len(s1) >= k:
			m = min(m, findPart(n * 2, s1, d + 1))
		elif len(s2) >= k:
			m = min(m, findPart(n * 2 + 1, s2, d + 1))
	return m
print(findPart(1, ln, 2))


def main():
	(m, n) = [int(v) for v in input().split()]
	vals = [int(v) for v in input().split()]
	data = []
	for v in vals:
		res = {}
		d = v
		count = 0
		while d != 0:
			res[d] = count
			count += 1
			d = d // 2
		res[d] = count
		data.append(res)
	all_vals = set()
	for d in data:
		all_vals.update(set(d.keys()))
	results = {}
	for k in all_vals:
		sorted_res = sorted([d[k] for d in data if k in d])
		if len(sorted_res) >= n:
			results[k] = sum(sorted_res[0:n])
	print(min(results.values()))
main()


from collections import *
(n, k) = map(int, input().split())
l = sorted(list(map(int, input().split())))
mini = None
d = defaultdict(lambda : [0, 0])
for i in l:
	cnt = 0
	while i > 0:
		d[i][0] += 1
		d[i][1] += cnt
		if d[i][0] == k:
			mini = d[i][1] if mini == None else min(mini, d[i][1])
		cnt += 1
		i //= 2
print(mini)


(N, K) = map(int, input().split())
X = sorted(list(map(int, input().split())))
import sys
input = sys.stdin.readline
d = dict()
for x in X:
	if x not in d:
		d[x] = 0
	d[x] += 1
	if d[x] >= K:
		print(0)
		sys.exit()
L = [0] * N
b = X[0]
for i in range(1, N):
	L[i] = (X[i] - b) * i + L[i - 1]
	b = X[i]
R = [0] * N
b = X[-1]
for i in range(N - 2, -1, -1):
	R[i] = (b - X[i]) * (N - 1 - i) + R[i + 1]
	b = X[i]
r = 10 ** 18
for i in range(N):
	cr = 10 ** 18
	if i + 1 >= K:
		cr = min(cr, L[i] - (i + 1 - K))
	if N - i >= K:
		cr = min(cr, R[i] - (N - i - K))
	if i + 1 < K and N - i < K:
		cr = min(cr, L[i] + R[i] - (N - K))
	cr = max(cr, 0)
	r = min(cr, r)
print(r)


(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 = input().split()
for i in range(n):
	a[i] = int(a[i])
a.sort()
a1 = []
for j in range(n):
	a1.append(a[j])
b = [0 for i in range(2 * 10 ** 5 + 1)]
b1 = [0 for i in range(2 * 10 ** 5 + 1)]
for j in range(n):
	q = 0
	while a[j]:
		if b[a[j]] < k:
			b[a[j]] += 1
			b1[a[j]] += q
		a[j] = a[j] // 2
		q += 1
c = []
for j in range(2 * 10 ** 5 + 1):
	if b[j] == k:
		c.append(b1[j])
count = 0
for i in range(k):
	while a1[i] != 0:
		count += 1
		a1[i] = a1[i] // 2
if len(c) > 0:
	print(min(count, min(c)))
else:
	print(count)


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)


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)


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)


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


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

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

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
cou = defaultdict(int)
su = 0
cnt = 0
su1 = sum(l)
cnt1 = n
fi = sum(l)
sumq = fi
for i in range(n):
	cou[l[i]] += 1
	if cou[l[i]] >= k:
		print(0)
		sys.exit(0)
for i in range(n):
	if i == 0:
		ans = sumq - (l[0] + 1) * n + k
		fi = min(fi, ans)
		cnt1 -= cou[l[0]]
		su1 -= cou[l[0]] * l[0]
	elif i == n - 1:
		ans = (l[-1] - 1) * n - sumq + k
		fi = min(fi, ans)
	else:
		if l[i] != l[i - 1]:
			cnt += cou[l[i - 1]]
			su += l[i - 1] * cou[l[i - 1]]
			cnt1 -= cou[l[i]]
			su1 -= l[i] * cou[l[i]]
		ans = (l[i] - 1) * cnt - su
		ans1 = su1 - (l[i] + 1) * cnt1
		tot = ans + ans1 + (k - cou[l[i]])
		if cnt1 >= k - cou[l[i]]:
			tot = min(tot, ans1 + (k - cou[l[i]]))
		if cnt >= k - cou[l[i]]:
			tot = min(tot, ans + (k - cou[l[i]]))
		fi = min(fi, tot)
print(fi)


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)


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)


import sys
from collections import defaultdict as dd

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

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

def fi():
	return int(input())

def si():
	return list(input().rstrip())

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

def bo(i):
	return ord(i) - ord('a')
(n, k) = mi()
a = li()
a.sort()
pre = [0] * (n + 1)
suf = [0] * (n + 1)
d = dd(lambda : 0)
vis = dd(lambda : 0)
for i in range(n):
	pre[i] += pre[i - 1] + a[i]
	d[a[i]] += 1
for i in range(n - 1, -1, -1):
	suf[i] = suf[(i + 1) % n] + a[i]
mini = 10 ** 18
for i in range(n):
	if vis[a[i]]:
		continue
	p = k - d[a[i]]
	vis[a[i]] = 1
	f = 0
	if p <= 0:
		mini = 0
		break
	if i >= p:
		f = 1
		c = (a[i] - 1) * i - pre[i - 1]
		c += p
		mini = min(mini, c)
	if i + d[a[i]] >= n:
		continue
	if n - i - d[a[i]] >= p:
		f = 1
		z = n - i - d[a[i]]
		c = -(a[i] + 1) * z + suf[i + d[a[i]]]
		c += p
		mini = min(mini, c)
	if not f:
		z = n - i - d[a[i]]
		c = -(a[i] + 1) * z + suf[i + d[a[i]]] + (a[i] - 1) * i - pre[i - 1] + p
		mini = min(mini, c)
print(mini)


from heapq import *
from collections import *
import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

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

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

def MI1():
	return map(int1, sys.stdin.readline().split())

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

def LI1():
	return list(map(int1, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	(n, k) = MI()
	cnt = Counter(LI())
	aa = []
	cc = []
	for (a, c) in sorted(cnt.items()):
		aa.append(a)
		cc.append(c)
		if c >= k:
			print(0)
			exit()
	n = len(aa)
	cl = [0] * n
	sc = 0
	sa = 0
	for i in range(n):
		cl[i] = (aa[i] - 1) * sc - sa
		sc += cc[i]
		sa += cc[i] * aa[i]
	cr = [0] * n
	sc = 0
	sa = 0
	for i in range(n - 1, -1, -1):
		cr[i] = sa - (aa[i] + 1) * sc
		sc += cc[i]
		sa += cc[i] * aa[i]
	ans = 10 ** 16
	s = 0
	for i in range(n):
		s += cc[i]
		if s < k:
			cur = cl[i] + cr[i] + k - cc[i]
		else:
			cur = cl[i] + k - cc[i]
		if cur < ans:
			ans = cur
		if s >= k:
			break
	s = 0
	for i in range(n - 1, -1, -1):
		s += cc[i]
		if s < k:
			cur = cl[i] + cr[i] + k - cc[i]
		else:
			cur = cr[i] + k - cc[i]
		if cur < ans:
			ans = cur
		if s >= k:
			break
	print(max(ans, 0))
main()


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)


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


(n, k) = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]
dics = []
for i in range(20):
	dics.append({})
for d in data:
	ln = len(bin(d)) - 2
	for i in range(ln, -1, -1):
		if d not in dics[i]:
			dics[i][d] = [ln - i]
		else:
			dics[i][d].append(ln - i)
		d >>= 1
mn = 1 << 50
for i in range(20):
	dic = dics[i].values()
	for d in dic:
		if len(d) >= k:
			d.sort()
			val = sum(d[:k])
			if val < mn:
				mn = val
print(mn)


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


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


from collections import defaultdict
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
d = defaultdict(lambda : [])
for i in a:
	s = 0
	while i != 0:
		d[i] = d[i] + [s]
		s = s + 1
		i = i // 2
		if i == 0:
			d[0] = d[0] + [s]
k = list(d.keys())
for i in range(0, len(k)):
	d[k[i]] = sorted(list(d[k[i]]))
mn = 9999999999999999
for i in range(0, len(k)):
	if len(d[k[i]]) >= m:
		mn = min(mn, sum(d[k[i]][0:m]))
print(mn)


import os
import sys
from math import *
from collections import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
(n, k) = value()
a = array()
ans = defaultdict(list)
for i in a:
	c = 0
	ans[i].append(c)
	while i:
		c += 1
		i //= 2
		ans[i].append(c)
steps = inf
for i in ans:
	if len(ans[i]) >= k:
		steps = min(steps, sum(sorted(ans[i])[:k]))
print(steps)


import unittest
import traceback
import pprint

def compress_list(a):
	x = []
	cur = a[0]
	num = 1
	for i in range(1, len(a)):
		if a[i] == cur:
			num += 1
		else:
			x.append([cur, num])
			cur = a[i]
			num = 1
	x.append([cur, num])
	return x

def solve(n, k, a):
	a = sorted(a)
	a = compress_list(a)
	min_ret = 200000000
	x = {0: [0 for i in range(0, 20)]}
	for (cur, num) in a:
		if num >= k:
			return 0
		idx = 0
		while cur > 0:
			if cur not in x:
				x[cur] = [0 for i in range(0, 20)]
			x[cur][idx] += num
			cur = cur // 2
			idx += 1
	for (cur, ll) in x.items():
		snum = 0
		scnt = 0
		for (idx, num) in enumerate(ll):
			if snum + num >= k:
				ret = scnt + (k - snum) * idx
				min_ret = min(min_ret, ret)
				break
			snum += num
			scnt += num * idx
			if scnt >= min_ret:
				break
	return min_ret

class TestCase(unittest.TestCase):

	def test1(self):
		n = 5
		k = 3
		a = [2, 2, 3, 3, 5]
		self.assertEqual(solve(n, k, a), 1)

	def test2(self):
		n = 5
		k = 3
		a = [1, 2, 2, 4, 5]
		self.assertEqual(solve(n, k, a), 1)

	def test3(self):
		n = 5
		k = 3
		a = [1, 2, 3, 4, 5]
		self.assertEqual(solve(n, k, a), 2)

	def test4(self):
		n = 5
		k = 3
		a = [1, 2, 3, 3, 3]
		self.assertEqual(solve(n, k, a), 0)

	def test5(self):
		n = 10
		k = 4
		a = [4, 4, 8, 17, 25, 30, 99, 68, 89, 200]
		self.assertEqual(solve(n, k, a), 3)

	def test6(self):
		n = 1
		k = 1
		a = [1337]
		self.assertEqual(solve(n, k, a), 0)
(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
try:
	print(solve(n, k, a))
except Exception as e:
	print(e, traceback.format_exc())


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


from collections import deque
import collections
import sys

def inp():
	return sys.stdin.readline().strip()
(n, k) = map(int, inp().split())
a = list(map(int, inp().split()))
d = collections.Counter(a)
b = list(d.keys())
mn = float('inf')
b.sort()
for i in range(max(b) + 1):
	val = d.get(i, 0)
	ans = 0
	for j in b:
		if j > i:
			ct = 0
			temp = j
			while temp > i:
				temp //= 2
				ct += 1
			if temp == i:
				if val < k and d[j] + val >= k:
					req = k - val
					val = k
					ans += req * ct
					break
				else:
					val += d[j]
					ans += d[j] * ct
	if val >= k:
		mn = min(ans, mn)
print(mn)


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)


(n, k) = [int(i) for i in input().split()]
lst = [int(i) for i in input().split()]

def light(k, lst):
	nums = [0 for j in range(1 + 2 * 10 ** 5)]
	counts = [0 for j in range(1 + 2 * 10 ** 5)]
	for elem in lst:
		count = 0
		nums[elem] += 1
		while elem != 0:
			elem //= 2
			count += 1
			if nums[elem] < k:
				nums[elem] += 1
				counts[elem] += count
	return min([counts[i] for (i, num) in enumerate(nums) if num >= k])
print(light(k, sorted(lst)))


import sys

def main():

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


(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

def i():
	return sys.stdin.readline()[:-1]

def count(l, i):
	return sum((x == i for x in i))
(l, desiredSame) = map(int, i().split())
nums = list(map(int, i().split()))
pos = set()
pos.add(0)
for item in nums:
	while item > 0:
		pos.add(item)
		item >>= 1
currMin = 9000
for x in pos:
	distance = []
	for item in nums:
		shift = 0
		while item > x:
			shift += 1
			item >>= 1
		if item == x:
			distance.append(shift)
	if len(distance) >= desiredSame:
		currMin = min(currMin, sum(sorted(distance)[:desiredSame]))
print(currMin)


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


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


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 collections import Counter as Cn
(n, k) = map(int, input().split())
a = sorted(map(int, input().split()))
arr = Cn(a)
lsum = 0
lcnt = 0
rsum = sum(a)
rcnt = len(a)
ans = 10 ** 18
for (val, cnt) in sorted(arr.items()):
	req = max(0, k - cnt)
	if req == 0:
		ans = 0
		break
	rcnt = rcnt - cnt
	rsum = rsum - val * cnt
	lr = min(req, lcnt)
	rr = max(0, req - lr)
	ta = (val - 1) * lcnt - lsum + lr
	if lr < req:
		ta += rsum - (val + 1) * rcnt + rr
	ans = min(ans, ta)
	rr = min(rcnt, req)
	lr = max(0, req - rr)
	ta = rsum - (val + 1) * rcnt + rr
	if rr < req:
		ta += (val - 1) * lcnt - lsum + lr
	ans = min(ans, ta)
	lcnt += cnt
	lsum += cnt * val
print(ans)


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)


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:
		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.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
			return True
		else:
			return False
	else:
		valmap[a] = [1, i]
		return True
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)


def main():
	import sys
	input = sys.stdin.readline
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	A.sort()
	A.append(0)
	l1 = [0] * n
	for i in range(1, n):
		l1[i] = l1[i - 1] + (A[i] - A[i - 1]) * i
	l2 = [0] * n
	for i in range(1, n):
		l2[n - i - 1] = l2[n - i] + (A[n - i] - A[n - i - 1]) * i
	ans = float('INF')
	c = 1
	for i in range(n):
		if A[i + 1] == A[i]:
			c += 1
		else:
			c1 = i - c + 1
			c2 = n - i - 1
			if c >= k:
				ans = 0
			elif c + c1 >= k or c + c2 >= k:
				if c + c1 >= k:
					ans = min(ans, l1[i] - c - c1 + k)
				if c + c2 >= k:
					ans = min(ans, l2[i] - c - c2 + k)
			else:
				ans = min(ans, l1[i] + l2[i] - n + k)
			c = 1
	print(ans)

def __starting_point():
	main()
__starting_point()


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
dp = [[] for i in range(200005)]
mp = {}
cnt = 0
for i in a:
	if i not in mp:
		mp[i] = 0
	else:
		mp[i] += 1
		cnt = max(cnt, mp[i])
if cnt >= k:
	print(0)
else:
	for i in a:
		cnt = 0
		x = i
		while x:
			dp[x].append(cnt)
			x = x // 2
			cnt += 1
		dp[x].append(cnt)
	ans = 10000000000000000000000000000000000000000000000
	for i in range(200005):
		if len(dp[i]) < k:
			continue
		else:
			cnt = 0
			dp[i] = sorted(dp[i])
			for j in range(k):
				cnt += dp[i][j]
			ans = min(ans, cnt)
	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)))


from collections import Counter
(n, k) = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
mp = Counter(arr)
sum_arr = sum(arr)
ans = 10 ** 18
keys = sorted(mp.keys())
cur_sum = 0
l_count = 0
for key in keys:
	value = mp[key]
	if value >= k:
		ans = 0
		break
	tmp_k = k - value
	if l_count < tmp_k:
		ans1 = ans
	else:
		ans1 = (key - 1) * l_count - cur_sum + tmp_k
	if n - l_count >= k:
		ans2 = sum_arr - cur_sum - key * value - (key + 1) * (n - l_count - value) + tmp_k
	else:
		ans2 = ans
	ans3 = (key - 1) * l_count - cur_sum + sum_arr - cur_sum - key * value - (key + 1) * (n - l_count - value) + tmp_k
	ans = min(ans, ans1, ans2, ans3)
	cur_sum += key * value
	l_count += value
print(ans)


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


import collections
(n, k) = 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)


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

def IS():
	return input()

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

def IM():
	return map(int, input().split())
(n, k) = IM()
l = IL()
from collections import Counter
c = Counter(l)
if max(c.values()) >= k:
	print(0)
	exit()
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

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


def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	vals = list(zip(aa, [0] * n))
	for a in aa:
		i = 0
		while a > 0:
			i += 1
			a = a // 2
			vals.append((a, i))
	vals.sort()
	val = -1
	min = 20 * k
	for (a, i) in vals:
		if a != val:
			vcount = 1
			vsum = i
			val = a
		elif vcount < k:
			vcount += 1
			vsum += i
		if vcount == k and vsum < min:
			min = vsum
	print(min)
main()


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 ** 5
for ke in d:
	ans = 0
	l = len(d[ke])
	if l < k:
		continue
	fin = sorted(d[ke])
	for i in range(k):
		ans += fin[i]
	mn = min(mn, ans)
print(mn)


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()
a.sort()
mn = float('inf')
p = []
for i in range(n):
	temp = a[i]
	while temp:
		p.append(temp)
		temp //= 2
p = list(set(p))
for i in range(len(p)):
	c = p[i]
	op = []
	for j in range(n):
		cnt = 0
		temp = a[j]
		while temp > c:
			temp //= 2
			cnt += 1
		if temp == c:
			op.append(cnt)
	if len(op) >= k:
		op.sort()
		mn = min(mn, sum(op[:k]))
c = 0
for i in range(k):
	while a[i]:
		a[i] //= 2
		c += 1
mn = min(mn, c)
print(mn)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
r = max(a) + 1
values = [[] for i in range(r)]
for i in a:
	cur = 0
	values[i].append(0)
	while i != 0:
		i //= 2
		cur += 1
		values[i].append(cur)
ans = float('inf')
for i in values:
	if len(i) < k:
		continue
	else:
		i.sort()
		ans = min(ans, sum(i[:k]))
print(ans)


from sys import stdin, stdout
(n, k) = 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)


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)


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)


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)


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)


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)


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


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

def solve(aux):
	count = 0
	for i in range(1, len(aux)):
		while True:
			if aux[i] > aux[i - 1]:
				aux[i] //= 2
				count += 1
			elif aux[i] < aux[i - 1]:
				aux[i - 1] //= 2
				count += i
			else:
				break
	return count

def get_arr(num, arr):
	aux = []
	for i in range(len(arr)):
		count = 0
		c = arr[i]
		while True:
			if c > num:
				c //= 2
				count += 1
			elif c < num:
				aux.append(float('inf'))
				break
			else:
				aux.append(count)
				break
	aux.sort()
	return aux
(n, k) = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
m = max(arr)
ans = float('inf')
for i in range(0, m + 1):
	aux = get_arr(i, arr)
	ans = min(ans, sum(aux[:k]))
print(ans)


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


import sys
input = lambda : sys.stdin.readline().strip()
(n, k) = map(int, input().split())
ls = list(map(int, input().split()))
ls.sort()
arr = []
for i in ls:
	while i != 0:
		arr.append(i)
		i //= 2
	arr.append(0)
arr = list(set(arr))
arr.sort()
cnts = []
m = 10000000000000000000
for x in arr:
	cnts = []
	for i in ls:
		cnt = 0
		while i > x:
			i //= 2
			cnt += 1
		if i == x:
			cnts.append(cnt)
	cnts.sort()
	S = 0
	try:
		for i in range(k):
			S += cnts[i]
		m = min(m, S)
	except:
		pass
print(m)


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)


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) = map(int, input().split())
ar = list(map(int, input().split()))
dic = {}
for i in range(n):
	if not ar[i] in dic:
		dic[ar[i]] = [0]
	else:
		dic[ar[i]].append(0)
	count = 0
	while ar[i]:
		ar[i] //= 2
		count += 1
		if not ar[i] in dic:
			dic[ar[i]] = [count]
		else:
			dic[ar[i]].append(count)
ans = float('inf')
for i in dic:
	if len(dic[i]) >= k:
		dic[i].sort()
		ans = min(ans, sum(dic[i][:k]))
print(ans)


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


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


import sys
input = sys.stdin.readline

def main():
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	M = max(A)
	scores = [[] for _ in range(M + 1)]
	for a in A:
		c = 0
		while a > 0:
			scores[a].append(c)
			a //= 2
			c += 1
		scores[0].append(c)
	for (a, L) in enumerate(scores):
		if len(L) < K:
			continue
		L.sort()
		if a == 0:
			ans = sum(L[:K])
		else:
			ans = min(ans, sum(L[:K]))
	print(ans)
main()


import sys
from array import array
from typing import List, Tuple, TypeVar, Generic, Sequence, Union

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	from itertools import accumulate
	from collections import Counter
	(n, k) = map(int, input().split())
	a = sorted(map(int, input().split()))
	if Counter(a).most_common(1)[0][1] >= k:
		print(0)
		exit()
	acc = [0] + list(accumulate(a))
	ans = 10 ** 18
	for i in range(n):
		if i >= k - 1:
			ans = min(ans, (a[i] - 1) * i - acc[i] + k - 1)
		if n - i - 1 >= k - 1:
			ans = min(ans, acc[-1] - acc[i + 1] - (a[i] + 1) * (n - i - 1) + k - 1)
		ans = min(ans, (a[i] - 1) * i - acc[i] + (acc[-1] - acc[i + 1]) - (a[i] + 1) * (n - i - 1) + k - 1)
	print(ans)
main()


N = int(200000.0 + 7)
D = 20

def testList(dp):
	dp[1][5] = 77
	for i in range(0, 5):
		print('dp[{0}]={1}'.format(i, dp[i]))
(n, k) = map(int, input().strip().split())
numberList = list(map(int, input().strip().split()))
maxn = max(numberList)
numCount = [0] * N
dp = [[0 for i in range(D)] for j in range(N)]
for i in numberList:
	numCount[i] += 1
res = int(2147483647)
for i in range(maxn, -1, -1):
	dp[i][0] = numCount[i]
	if i * 2 <= maxn:
		for d in range(1, 20):
			dp[i][d] += dp[i * 2][d - 1]
	if i * 2 + 1 <= maxn:
		for d in range(1, 20):
			dp[i][d] += dp[i * 2 + 1][d - 1]
	equ_cnt = 0
	equ_res = 0
	for d in range(0, 20):
		if equ_cnt + dp[i][d] < k:
			equ_res += d * dp[i][d]
			equ_cnt += dp[i][d]
		else:
			equ_res += d * (k - equ_cnt)
			equ_cnt += k - equ_cnt
			res = min(res, equ_res)
			break
print(res)


(n, k) = map(int, input().split())
fuad = list(map(int, input().split()))
fuad.sort()
steps = {}
num = {}
ans = 200000000
for a in fuad:
	cnt = 0
	x = a
	while 1:
		num[x] = num.get(x, 0) + 1
		steps[x] = steps.get(x, 0) + cnt
		cnt += 1
		if num[x] == k:
			ans = min(ans, steps[x])
		x //= 2
		if x == 0:
			break
print(ans)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 998244353

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k))))
from collections import deque, defaultdict
import heapq

def solution(a, n, k):
	d = defaultdict(int)
	for x in a:
		d[x] += 1
	so = [(x, d[x]) for x in d]
	so.sort()
	for (x, y) in so:
		if y >= k:
			return 0
	m = len(so)
	total = so[0][1]
	fo = [0]
	for i in range(1, m):
		fo.append(fo[-1] + total * (so[i][0] - so[i - 1][0]))
		total += so[i][1]
	total = so[-1][1]
	ba = [0 for i in range(m)]
	ba[m - 1] = 0
	for i in range(m - 2, -1, -1):
		ba[i] = ba[i + 1] + total * (so[i + 1][0] - so[i][0])
		total += so[i][1]
	total_fo = [0]
	for x in so:
		total_fo.append(total_fo[-1] + x[1])
	total_ba = [0 for i in range(m + 1)]
	for i in range(m - 2, -1, -1):
		total_ba[i] = total_ba[i + 1] + so[i + 1][1]
	mn = 10 ** 15
	for i in range(m):
		if total_ba[i] + so[i][1] >= k:
			mn = min(mn, max(ba[i] - (total_ba[i] + so[i][1] - k), 0))
		if total_fo[i] + so[i][1] >= k:
			mn = min(mn, max(fo[i] - (total_fo[i] + so[i][1] - k), 0))
		mn = min(mn, max(fo[i] + ba[i] - (total_fo[i] + total_ba[i] + so[i][1] - k), 0))
	return mn

def main():
	T = 1
	for i in range(T):
		(n, k) = ria()
		a = ria()
		x = solution(a, n, k)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
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) = 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)


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


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
tr = {}
for i in range(2 * 10 ** 5 + 1):
	tr[i] = [0, 0]
for i in a:
	j = 0
	while i != 0:
		if tr[i][0] != k:
			tr[i][0] += 1
			tr[i][1] += j
		j += 1
		i = i // 2
ans = float('inf')
for i in range(2 * 10 ** 5 + 1):
	if tr[i][0] == k:
		if ans > tr[i][1]:
			ans = tr[i][1]
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 math
(n, k) = map(int, input().split())
numbers = list(map(int, input().split()))
answer = 2 ** 64
for p in range(18):
	m = 2 ** p
	for w in numbers:
		x = int(w / m)
		cnt = []
		for v in numbers:
			cur = 0
			while v > 0 and v != x:
				v //= 2
				cur += 1
			if v == x:
				cnt.append(cur)
		cnt.sort()
		if len(cnt) >= k:
			answer = min(answer, sum(cnt[:k]))
print(answer)


import sys
input = sys.stdin.readline
(n, k) = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
ops = [0] * 200007
for i in range(n):
	alph = A[i]
	while alph > 0:
		ops[alph] += 1
		alph //= 2
	ops[0] += 1
ans = float('inf')
for i in range(200007):
	if ops[i] >= k:
		count = 0
		numOps = 0
		for j in range(n):
			if count == k:
				break
			alph = A[j]
			tmpOps = 0
			while alph > i:
				alph //= 2
				tmpOps += 1
			if alph == i:
				count += 1
				numOps += tmpOps
		ans = min(ans, numOps)
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 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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
v = [[] for _ in range(5 * 10 ** 5 + 5)]
for i in range(n):
	cnt = 0
	while a[i] != 0:
		v[a[i]].append(cnt)
		a[i] //= 2
		cnt += 1
	v[0].append(cnt)
minc = 10 ** 11
for i in range(5 * 10 ** 5 + 5):
	if len(v[i]) >= k:
		v[i].sort()
		minc = min(minc, sum(v[i][:k]))
print(minc)


(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
(sums, suf, q1) = ([0] * n, [n] * n, n)
for q in range(n - 2, -1, -1):
	sums[q] = sums[q + 1]
	if a[q] != a[q1 - 1]:
		sums[q] += (n - q1) * (a[q1 - 1] - a[q]) + (q1 - q - 1) * (a[q1 - 1] - a[q] - 1)
		q1 = q + 1
	suf[q] = q1
(ans, sum1, q1) = (sums[0] + k - suf[0] if suf[0] < k else 0, 0, -1)
for q in range(1, n):
	if a[q] != a[q1 + 1]:
		sum1 += (q1 + 1) * (a[q] - a[q1 + 1]) + (q - q1 - 1) * (a[q] - a[q1 + 1] - 1)
		q1 = q - 1
	if suf[q] - q1 - 1 >= k:
		ans = 0
		break
	if k <= suf[q]:
		ans = min(ans, sum1 + k - suf[q] + q1 + 1)
	if k < n - q1:
		ans = min(ans, sums[q] + k - suf[q] + q1 + 1)
	ans = min(ans, sum1 + sums[q] + k - suf[q] + q1 + 1)
print(ans)


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)


import math
(n, k) = map(int, input().split())
numbers = list(map(int, input().split()))
divisors = set()
divisors.add(0)
numbers.sort(reverse=True)
for p in range(18):
	m = 2 ** p
	for v in numbers:
		while v > 0:
			divisors.add(v)
			v //= 2
answer = 2 ** 64
for d in divisors:
	cnt = []
	for v in numbers:
		cur = 0
		while v > 0 and v != d:
			v //= 2
			cur += 1
		if v == d:
			cnt.append(cur)
	cnt.sort()
	if len(cnt) >= k:
		answer = min(answer, sum(cnt[:k]))
print(answer)


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)


[n, k] = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
a.sort()
a.insert(0, 0)
a.append(0)
pref = [0] * (n + 2)
suff = [0] * (n + 2)
for i in range(1, n + 1):
	pref[i] = pref[i - 1] + a[i]
for i in range(n, 0, -1):
	suff[i] = suff[i + 1] + a[i]
ans = 1e+18
for i in range(1, n + 1):
	if a[i] == a[i - 1]:
		continue
	l = i
	r = i
	while a[r + 1] == a[l]:
		r = r + 1
	cur = r - l + 1
	if cur >= k:
		ans = 0
		break
	need = k - cur
	if need <= n - r:
		foo = suff[r + 1] - (a[i] + 1) * (n - r)
		foo += need
		ans = min(ans, foo)
	if need <= l - 1:
		foo = (l - 1) * (a[i] - 1) - pref[l - 1]
		foo += need
		ans = min(ans, foo)
	foo = suff[r + 1] - (a[i] + 1) * (n - r) + (l - 1) * (a[i] - 1) - pref[l - 1]
	foo += need
	ans = min(ans, foo)
print(ans)


from math import log
(n, k) = 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)


(n, m) = map(int, input().split())
data = list(map(int, input().split()))
data.sort()
last = -120
CONST = 2 * 10 ** 5 + 1
ans = 10 ** 15
for i in range(CONST):
	(c, kol) = (0, 0)
	if data[-1] < i:
		break
	for j in data:
		if kol == m:
			ans = min(ans, c)
			break
		if j > i:
			k = 0
			t = j
			while t > i:
				t //= 2
				k += 1
			if t == i:
				c += k
				kol += 1
		elif j == i:
			kol += 1
	if kol == m:
		ans = min(ans, c)
print(ans)


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 heapq
R = lambda : map(int, input().split())
(n, k) = R()
nums = list(R())
res = 2 * 10 ** 7
for toNum in range(max(nums) + 1):
	gcnt = []
	for num in nums:
		cnt = 0
		while num > toNum:
			num = num >> 1
			cnt += 1
		if num == toNum:
			gcnt.append(cnt)
	if len(gcnt) >= k:
		res = min(res, sum(heapq.nsmallest(k, gcnt)))
print(res)


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


from collections import defaultdict

def arrinp():
	return [*map(int, input().split(' '))]

def mulinp():
	return map(int, input().split(' '))

def intinp():
	return int(input())

def solution():
	(n, k) = mulinp()
	arr = []
	for i in sorted(arrinp()):
		if not arr or arr[-1][0] != i:
			arr.append([i, 1])
		else:
			arr[-1][1] += 1
	costSum = []
	countSum = []
	for (i, count) in arr:
		if costSum:
			costSum.append(costSum[-1] + count * i)
			countSum.append(countSum[-1] + count)
		else:
			costSum.append(count * i)
			countSum.append(count)
	if len(arr) > 1 and k > arr[0][1] and (k > arr[-1][1]):
		res = min(costSum[-1] - costSum[0] - (countSum[-1] - countSum[0]) * arr[0][0] - countSum[-1] + k, arr[-1][0] * countSum[-2] - costSum[-2] - countSum[-1] + k)
	else:
		res = 0
	for i in range(1, len(arr) - 1):
		cost = 0
		fromLeft = arr[i][0] * countSum[i] - costSum[i]
		fromRight = costSum[-1] - costSum[i] - arr[i][0] * (countSum[-1] - countSum[i])
		if countSum[i] < k:
			cost = fromLeft + fromRight + k - countSum[-1]
		elif arr[i][1] < k:
			cost = fromLeft + k - countSum[i]
		if countSum[-1] - countSum[i - 1] >= k and arr[i][1] < k:
			cost = min(cost, fromRight + k - countSum[-1] + countSum[i - 1])
		if res > cost:
			res = cost
	print(res)
testcases = 1
for _ in range(testcases):
	solution()


(n, k) = [int(i) for i in input().split()]
lst = [int(i) for i in input().split()]

def hard(n, k, lst):
	(a, result) = ([[] for i in range(1 + 2 * 10 ** 5)], 0)
	for i in range(n):
		(x, l) = (lst[i], 0)
		while True:
			a[x].append(l)
			if x == 0:
				break
			x //= 2
			l += 1
	maximum = 1000000000
	for i in range(len(a)):
		a[i].sort()
		if len(a[i]) >= k:
			maximum = min(maximum, sum(a[i][:k]))
	return maximum
print(hard(n, k, lst))


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)


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


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 array
import bisect
import math
import os
import random
import re
import sys
from typing import List, Any
sys.setrecursionlimit(10000)
INIT = -1
INF = 10 ** 18
n: int
k: int
a: List[int]
pre: List[int]

def printf(format: str, *args):
	sys.stdout.write(format % args)

def lo(l: int, r: int, x: int) -> int:
	if r <= l:
		return 0
	cnt = r - l
	got = pre[r - 1]
	want = x * cnt + l * (x - 1)
	return want - got

def hi(l: int, r: int, x: int) -> int:
	if r <= l:
		return 0
	cnt = r - l
	got = pre[n - 1]
	if l > 0:
		got -= pre[l - 1]
	want = cnt * x + (n - r) * (x + 1)
	return got - want

def main():
	global n, k, a, pre
	[n, k] = list(map(int, input().strip().split(' ')))
	a = list(map(int, input().strip().split(' ')))
	a.sort()
	pre = array.array('q', [0]) * n
	for i in range(n):
		if i > 0:
			pre[i] = pre[i - 1]
		pre[i] += a[i]
	ans = INF
	for i in range(n):
		x = a[i]
		l = bisect.bisect_left(a, x, 0, i)
		r = bisect.bisect_right(a, x, i, n) - 1
		lgot = i - l
		rgot = r - i
		got = 1 + lgot + rgot
		if got >= k:
			ans = 0
			break
		lneed = k - got
		lcost = 0
		lcan = min(l, lneed)
		lneed -= lcan
		lcost = lo(l - lcan, l, x)
		if lneed > 0:
			lcost += hi(r, r + lneed + 1, x)
		ans = min(ans, lcost)
		rneed = k - got
		rcan = min(n - 1 - r, rneed)
		rneed -= rcan
		rcost = hi(r, r + rcan + 1, x)
		if rneed > 0:
			rcost += lo(l - rneed, l, x)
		ans = min(ans, rcost)
	print(ans)
main()


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

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

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

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def err(x):
	print(x)
	exit()
(n, k) = inpl()
a = inpl()
a.sort()
c = Counter(a)
if max(c.values()) >= k:
	err(0)
aa = [0] + list(itertools.accumulate(a))
res = INF
for x in a:
	want = k - c[x]
	left_cnt = bisect_left(a, x)
	mi_cost = (x - 1) * left_cnt - aa[left_cnt]
	if left_cnt >= want:
		res = min(res, mi_cost + want)
	right_cnt = n - bisect_right(a, x)
	ma_cost = aa[-1] - aa[-right_cnt - 1] - (x + 1) * right_cnt
	if right_cnt >= want:
		res = min(res, ma_cost + want)
	res = min(res, mi_cost + ma_cost + want)
print(res)


def main():
	(n, k) = 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()


(_, k) = map(int, input().split())
arr = map(int, input().split())
number = dict()
A = list()
for n in arr:
	cnt = 0
	B = dict()
	while True:
		B[n] = cnt
		if n not in number:
			number[n] = 0
		number[n] += 1
		cnt += 1
		n //= 2
		if n == 0:
			break
	A.append(B)
best = 1000000000
for n in range(0, 200000):
	if n not in number or number[n] < k:
		continue
	temp = []
	for m in A:
		if n not in m:
			continue
		temp.append(m[n])
	if len(temp) < k:
		break
	temp = sorted(temp)
	best = min(best, sum(temp[:k]))
print(best)


def count(a, b):
	k = 0
	while a > b:
		a = a // 2
		k += 1
	if a == b:
		return k
	else:
		return None
(n, k) = input().split()
n = int(n)
k = int(k)
s = list(input().split(' '))
for i in range(n):
	s[i] = int(s[i])
s.sort()
number_of_operations = []
for i in range(1, max(s) + 1):
	sum = 0
	quantity = 0
	for number in s:
		try:
			sum += count(number, i)
			quantity += 1
		except TypeError:
			continue
		if quantity == k:
			number_of_operations.append(sum)
			break
print(min(number_of_operations))


(n, k) = [int(p) for p in input().split()]
arr = [int(p) for p in input().split()]
arr.sort()
span = [-k] * (max(arr) + 1)
cost = [0] * (max(arr) + 1)
for i in range(n):
	j = 0
	while True:
		if span[arr[i]] != 0:
			span[arr[i]] += 1
			cost[arr[i]] += j
		arr[i] //= 2
		j += 1
		if arr[i] == 0:
			if span[arr[i]] != 0:
				span[arr[i]] += 1
				cost[arr[i]] += j
			break
ans = float('inf')
for i in range(len(span)):
	if span[i] == 0:
		ans = min(ans, cost[i])
print(ans)


import sys

class Node:

	def __init__(self, val):
		self.val = val
		self.left = None
		self.right = None
		self.cnt

def main():
	(n, m) = [int(s) for s in sys.stdin.readline().strip().split()]
	xs = sorted((int(s) for s in sys.stdin.readline().strip().split()))
	mmm = max(xs) + 1
	prefix = [0 for _ in range(mmm)]
	costs = [0 for _ in range(mmm)]
	for x in xs:
		c = 0
		while x > 0:
			if prefix[x] < m:
				costs[x] += c
			prefix[x] += 1
			c += 1
			x //= 2
		if prefix[0] < m:
			costs[0] += c
		prefix[0] += 1
	best = None
	for i in range(mmm):
		if prefix[i] >= m:
			s = costs[i]
			if best is None:
				best = s
			else:
				best = min(best, s)
	print(best)
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')
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
r = [[] for i in range(max(l) + 1)]
t = max(l) + 1
for i in range(n):
	c = 0
	while l[i] > 0:
		r[l[i]].append(c)
		c += 1
		l[i] //= 2
ans = 999999999999999999999999999
for i in range(t):
	if len(r[i]) >= k:
		r[i].sort()
		ans = min(ans, sum(r[i][:k]))
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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
pos = []
for i in range(n):
	x = a[i]
	while x > 0:
		pos.append(x)
		x //= 2
ans = 1000000000
for res in pos:
	cnt = []
	for i in range(n):
		x = a[i]
		cur = 0
		while x > res:
			x //= 2
			cur += 1
		if x == res:
			cnt.append(cur)
	if len(cnt) < k:
		continue
	cnt.sort()
	ans = min(ans, sum(cnt[:k]))
print(ans)


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


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 RL():
	return map(int, sys.stdin.readline().rstrip().split())

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

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, k) = RL()
	arr = RLL()
	ct = list(Counter(arr).items())
	ct.sort()
	sm = [0]
	nsm = [0]
	for (i, v) in ct:
		sm.append(sm[-1] + i * v)
		nsm.append(nsm[-1] + v)
	res = INF
	for (i, pair) in enumerate(ct):
		(v, num) = pair
		cost = (v - 1) * nsm[i] - sm[i]
		cost1 = -(v + 1) * (nsm[-1] - nsm[i + 1]) + sm[-1] - sm[i + 1]
		pre = nsm[i]
		suf = nsm[-1] - nsm[i + 1]
		need = k - num
		if need <= 0:
			res = 0
			break
		if pre >= need:
			res = min(res, cost + need)
		if suf >= need:
			res = min(res, cost1 + need)
		if suf + pre >= need:
			res = min(res, cost1 + cost + need)
	print(res)
main()


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, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
a.sort(reverse=True)
val1 = k
val2 = k
lista = [0 for i in range(n)]
i = 0
while i < n:
	j = 0
	while a[i] == a[i + j]:
		j = j + 1
		if i + j == n:
			break
	lista[i] = j
	i = i + j
if max(lista) >= k:
	print(0)
	exit()
for i in range(n):
	if a[i] == a[k - 1]:
		val1 = val1 - 1
		if val1 == 0:
			break
	elif a[i] > a[k - 1]:
		val1 = val1 + a[i] - a[k - 1] - 1
for i in range(n):
	if a[i] == a[n - k]:
		val2 = val2 - 1
		if val2 == 0:
			break
	elif a[i] < a[n - k]:
		val2 = val2 + a[n - k] - 1 - a[i]

def fun(l, b, h):
	val34prov = h
	for i in range(len(b)):
		if b[i] == l:
			val34prov = val34prov - 1
			if val34prov == 0:
				return 0
		elif b[i] > l:
			val34prov = val34prov + b[i] - l - 1
		else:
			val34prov = val34prov + l - 1 - b[i]
	return val34prov
if k <= n / 2:
	print(min(val1, val2))
else:
	val3 = fun(a[n // 2], a, k)
	if n % 2 == 1:
		print(min(val1, val2, val3))
	else:
		val4 = fun(a[n // 2 - 1], a, k)
		print(min(val1, val2, val3, val4))


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
poss = []
for i in range(n):
	x = a[i]
	while x > 0:
		if x in poss:
			pass
		else:
			poss.append(x)
		x = x // 2
Ans = float('inf')
for res in poss:
	cnt = []
	ans = 0
	for x in a:
		cur = 0
		while x > res:
			x = x // 2
			cur += 1
		if x == res:
			cnt.append(cur)
	if len(cnt) < k:
		continue
	else:
		cnt = sorted(cnt)
		i = 0
		while i < k:
			ans += cnt[i]
			i += 1
	Ans = min(ans, Ans)
print(Ans)


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)


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()
	G = defaultdict(list)
	C = Counter(A)
	xx = C.most_common(1)[0][1]
	if xx >= k:
		print(0)
		exit(0)
	P = list(set(A))
	for i in P:
		s = 0
		p = i
		for j in range(C[p]):
			G[i].append(s)
		while i:
			i = i // 2
			s += 1
			G[i] += [s] * C[p]
	ans = 1000000000.0
	for i in G.keys():
		if len(G[i]) >= k:
			r = sorted(G[i])
			temp = 0
			for j in range(k):
				temp += r[j]
			ans = min(ans, temp)
			if ans == 0:
				break
	print(ans)
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
	from aj import *
except:
	pass
solve()


from collections import defaultdict
(n, k) = map(int, input().split())
ar = [int(x) for x in input().split()]
ar.sort()
d = {}
for i in ar:
	if i not in d:
		d[i] = 1
	else:
		d[i] += 1
bl = False
d = defaultdict(list)
for i in ar:
	count = 0
	x = i
	while x:
		d[x].append(count)
		x //= 2
		count += 1
ans = 1000000000
for i in d.keys():
	d[i].sort()
	for j in range(len(d[i])):
		if j > 0:
			d[i][j] += d[i][j - 1]
	if len(d[i]) >= k:
		ans = min(ans, d[i][k - 1])
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))


(n, k) = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]
dic = [[0] * 20 for j in range(200001)]
for d in data:
	ln = len(bin(d)) - 2
	s = 0
	while d:
		dic[d][s] += 1
		d >>= 1
		s += 1
	dic[0][s] += 1
mn = 1 << 30
for d in dic:
	if sum(d) >= k:
		left = k
		val = 0
		for i in range(20):
			if d[i] >= left:
				val += i * left
				break
			else:
				val += i * d[i]
				left -= d[i]
		if val < mn:
			mn = val
print(mn)


import math
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
d = {}
c = {}
for i in l:
	cnt = 0
	x = i
	while x != 0:
		if x in d:
			d[x] += 1
		else:
			d[x] = 1
		if x in c:
			if d[x] <= k:
				c[x] += cnt
		else:
			c[x] = cnt
		x = x // 2
		cnt += 1
	if x in d:
		d[x] += 1
	else:
		d[x] = 1
	if x in c:
		if d[x] <= k:
			c[x] += cnt
	else:
		c[x] = cnt
ans = 10 ** 18
for i in d:
	if d[i] >= k:
		ans = min(ans, c[i])
print(ans)


(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, m) = map(int, input().split())
a = list(map(int, input().split()))
mx = int(200000.0)
num = [0 for _ in range(mx + 1)]
numAdd = [[] for _ in range(mx + 1)]
for v in a:
	num[v] += 1
	if num[v] == m:
		print(0)
		exit()
c = 0
for i in range(2, mx + 1):
	if num[i] != 0:
		cur = i
		count = 0
		while cur != 1:
			next = cur // 2
			count += 1
			add = [count for _ in range(num[i])]
			numAdd[next] = numAdd[next] + add
			cur = next
mn = int(8000000000.0)
for i in range(1, mx + 1):
	if num[i] + len(numAdd[i]) >= m:
		need = m - num[i]
		my = sum(numAdd[i][:need])
		mn = min(mn, my)
print(mn)


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, k) = map(int, input().split())
arr = list(map(int, input().split()))
poss = set()
for ele in arr:
	while ele:
		poss.add(ele)
		ele = ele // 2
ans = float('inf')
for res in poss:
	cnt = []
	for ele in arr:
		cur = 0
		while ele > res:
			ele = ele // 2
			cur += 1
		if ele == res:
			cnt.append(cur)
	if len(cnt) < k:
		continue
	cnt.sort()
	ans = min(ans, sum(cnt[:k]))
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)


from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

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

def LS():
	return [list(x) for x in sys.stdin.readline().split()]

def S():
	res = list(sys.stdin.readline())
	if res[-1] == '\n':
		return res[:-1]
	return res

def IR(n):
	return [I() for i in range(n)]

def LIR(n):
	return [LI() for i in range(n)]

def SR(n):
	return [S() for i in range(n)]

def LSR(n):
	return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
	(n, k) = LI()
	a = LI()
	a.sort()
	d = defaultdict(lambda : 0)
	c = defaultdict(lambda : 0)
	s = [0]
	for i in a:
		d[i] += i
		c[i] += 1
		s.append(s[-1] + i)
	ans = float('inf')
	p = -1
	for i in a:
		if i == p:
			continue
		if k <= c[i]:
			ans = 0
			break
		(l, r) = (bisect.bisect_left(a, i), bisect.bisect_right(a, i))
		m = r
		if m >= k:
			ns = l * (i - 1) - s[l]
			su = ns + k - c[i]
			if su < ans:
				ans = su
		m = n - l
		if m >= k:
			ns = s[n] - s[r] - (n - r) * (i + 1)
			su = ns + k - c[i]
			if su < ans:
				ans = su
		ns = s[n] - s[r] - (n - r) * (i + 1) + l * (i - 1) - s[l]
		su = ns + k - c[i]
		if su < ans:
			ans = su
		p = i
	print(ans)
	return

def __starting_point():
	solve()
__starting_point()


import sys
input = sys.stdin.readline
from collections import Counter
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
S = sorted(set(A)) + [1 << 60]
C = Counter(A)
if max(C.values()) >= k:
	print(0)
	sys.exit()
L = [0]
LK = [0]
ko = 0
for i in range(len(S) - 1):
	ko += C[S[i]]
	LK.append(ko)
	L.append(L[-1] + ko * (S[i + 1] - S[i]))
R = [0] * len(S)
RK = [0] * len(S)
ko = 0
for i in range(len(S) - 1, -1, -1):
	ko += C[S[i]]
	RK[i - 1] = ko
	R[i - 1] = R[i] + ko * (S[i] - S[i - 1])
R[-1] = 0
ANS = 1 << 61
for i in range(len(S) - 1):
	rest = k - C[S[i]]
	if i >= 1:
		if rest <= LK[i]:
			ANS = min(ANS, L[i - 1] + (S[i] - S[i - 1]) * rest)
		else:
			ANS = min(ANS, L[i] + R[i + 1] + (S[i + 1] - S[i]) * RK[i] - (RK[i] - rest + LK[i]))
	if i < len(S) - 1:
		if rest <= RK[i]:
			ANS = min(ANS, R[i + 1] + (S[i + 1] - S[i]) * rest)
		else:
			ANS = min(ANS, R[i] + L[i - 1] + (S[i] - S[i - 1]) * LK[i] - (LK[i] - rest + RK[i]))
print(ANS)


(n, k) = map(int, input().split())
arr = []
for i in sorted(map(int, input().split())):
	if not arr or arr[-1][0] != i:
		arr.append([i, 1])
	else:
		arr[-1][1] += 1
costSum = []
countSum = []
for (i, count) in arr:
	if costSum:
		costSum.append(costSum[-1] + count * i)
		countSum.append(countSum[-1] + count)
	else:
		costSum.append(count * i)
		countSum.append(count)
if len(arr) > 1 and k > arr[0][1] and (k > arr[-1][1]):
	res = min(costSum[-1] - costSum[0] - (countSum[-1] - countSum[0]) * arr[0][0] - countSum[-1] + k, arr[-1][0] * countSum[-2] - costSum[-2] - countSum[-1] + k)
else:
	res = 0
for i in range(1, len(arr) - 1):
	cost = 0
	fromLeft = arr[i][0] * countSum[i] - costSum[i]
	fromRight = costSum[-1] - costSum[i] - arr[i][0] * (countSum[-1] - countSum[i])
	if countSum[i] < k:
		cost = fromLeft + fromRight + k - countSum[-1]
	elif arr[i][1] < k:
		cost = fromLeft + k - countSum[i]
	if countSum[-1] - countSum[i - 1] >= k and arr[i][1] < k:
		cost = min(cost, fromRight + k - countSum[-1] + countSum[i - 1])
	if res > cost:
		res = cost
print(res)


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


tmp = input().split()
n = int(tmp[0])
k = int(tmp[1])
tmp = input().split()
tree = [list() for i in range(200001)]
minlength = 2000001
for value in tmp:
	value = int(value)
	length = 0
	while value != 0:
		if len(tree[value]) < k:
			tree[value].append(length)
			if len(tree[value]) == k and minlength > sum(tree[value]):
				minlength = sum(tree[value])
		elif max(tree[value]) > length:
			tree[value].remove(max(tree[value]))
			tree[value].append(length)
			if minlength > sum(tree[value]):
				minlength = sum(tree[value])
		value = value // 2
		length += 1
print(minlength)


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)


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


import collections, heapq, bisect, math

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

def solve(A, K):
	mod = 1000000
	nodes = {0: [set(), 0, []]}
	for a in A:
		count = 0
		last_val = mod
		while last_val != 0:
			if a not in nodes:
				nodes[a] = [{last_val}, 1, [-count]]
			else:
				nodes[a][0].add(last_val)
				nodes[a][1] += 1
				if len(nodes[a][2]) == K:
					heapq.heappushpop(nodes[a][2], -count)
				else:
					heapq.heappush(nodes[a][2], -count)
			count += 1
			last_val = a
			a //= 2
	for node in nodes:
		nodes[node][2] = -sum(nodes[node][2])
	best_node = 0
	states = {0}
	while states:
		new_states = set()
		for node in states:
			if node == mod:
				continue
			if nodes[node][1] >= K:
				new_states |= nodes[node][0]
				if nodes[node][2] < nodes[best_node][2]:
					best_node = node
		states = new_states
	return nodes[best_node][2]
(n, k) = input().split(' ')
tests = []
for test in range(1):
	tests.append([int(p) for p in input().split(' ')])
for test in tests:
	print(solve(test, int(k)))


import math
(n, k) = map(int, input().split(' '))
a = list(map(int, input().split()))
a = sorted(a)
m = max(a) // 2
c = [a[0]]
d = [1]
for i in range(1, n):
	if a[i] == c[-1]:
		d[-1] += 1
	else:
		c.append(a[i])
		d.append(1)
if max(d) >= k:
	print(0)
else:
	c = [[-1 for i in range(n)] for j in range(m + 1)]
	s = []
	i = n - 1
	while i >= 0:
		q = a[i]
		if q <= m:
			c[q][i] = 0
		k1 = 1
		while q != 0:
			q = q // 2
			c[q][i] = k1
			k1 = k1 + 1
		i -= 1
	for i in c:
		j = 0
		k1 = k
		count = 0
		while j < n and k1 > 0:
			if i[j] != -1:
				count += i[j]
				k1 -= 1
			j += 1
		if k1 == 0:
			s.append(count)
	print(min(s))


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


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)


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
ld = []
lj = []
le = []
for i in range(2 * 10 ** 5 + 1):
	h = [0, 0]
	le.append(h)
for i in range(n):
	g = []
	j = 0
	while l[i]:
		g.append(l[i])
		l[i] = l[i] // 2
		j += 1
	ld.append(g)
	lj.append(j)
j = 0
mi = 10 ** 18
for i in range(n):
	for j in range(lj[i]):
		if le[ld[i][j]][0] < k:
			le[ld[i][j]][0] += 1
			le[ld[i][j]][1] += j
		if le[ld[i][j]][0] == k:
			if le[ld[i][j]][1] < mi:
				mi = le[ld[i][j]][1]
print(mi)


(n, k) = map(int, input().split())
res = k * 20
a = list(map(int, input().split()))
ansNum = dict()
ansCost = dict()
ansCost.fromkeys(a, 0)
for i in a:
	ansNum[i] = ansNum.get(i, 0) + 1
	if ansNum[i] >= k:
		res = 0
l = n
c = 0
while True:
	ir = 0
	iw = 0
	c += 1
	if l <= 0:
		break
	while iw < l:
		if a[ir] == 0:
			l -= 1
		else:
			a[iw] = a[ir] >> 1
			ansNum[a[iw]] = ansNum.get(a[iw], 0) + 1
			ansCost[a[iw]] = ansCost.get(a[iw], 0) + c
			if ansNum[a[iw]] == k:
				res = min(res, ansCost[a[iw]])
			iw += 1
		ir += 1
print(res)


def solve():
	(n, k) = map(int, input().split())
	aa = sorted([int(i) for i in input().split()])
	cc = [[] for _ in range(0, max(aa) + 1)]
	for i in aa:
		ii = 0
		while i > 0:
			cc[i].append(ii)
			i //= 2
			ii += 1
		cc[i].append(ii)
	maxx = 10 ** 9 + 7
	for i in cc:
		if len(i) >= k:
			maxx = min(maxx, sum(i[:k]))
	print(maxx)
solve()


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()
sol = defaultdict(list)
for i in a:
	ch = 0
	x = i
	sol[i].append([i, ch])
	while x > 0:
		x //= 2
		ch += 1
		sol[x].append([i, ch])
ans = 999999
for i in sol:
	if len(sol[i]) >= k:
		ch = 0
		sol[i].sort()
		for j in range(k):
			ch += sol[i][j][1]
		ans = min(ch, ans)
print(ans)


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


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


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)


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


from collections import defaultdict
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
counts = defaultdict(list)
for x in a:
	cost = 0
	while x:
		counts[x].append(cost)
		cost += 1
		x //= 2
	counts[x].append(cost)
best = 10 ** 10
for l in counts.values():
	if len(l) >= k:
		option = sum(sorted(l)[:k])
		best = min(best, option)
print(best)


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
le = []
ma = max(n, l[n - 1])
for i in range(ma + 2):
	h = [0, 0]
	le.append(h)
mi = 10 ** 18
for i in range(n):
	g = []
	j = 0
	while l[i]:
		if le[l[i]][0] < k:
			le[l[i]][0] += 1
			le[l[i]][1] += j
			if le[l[i]][0] == k:
				if le[l[i]][1] < mi:
					mi = le[l[i]][1]
		l[i] = l[i] // 2
		j += 1
print(mi)


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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
min_ = float('inf')
for x in range(200001):
	(c1, c2, f) = (0, 0, False)
	for y in a:
		c3 = 0
		while x < y:
			y //= 2
			c3 += 1
		if x == y:
			c1 += c3
			c2 += 1
		if c2 >= k:
			f = True
			break
	if f and c1 < min_:
		min_ = c1
print(min_)


import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left, bisect_right
import threading
from collections import Counter, defaultdict
arr = []

def main():
	for _ in range(1):
		(n, k) = map(int, input().split())
		arr = list(map(int, input().split()))
		g_c = 0
		s_c = 0
		done = 0
		ans = float('inf')
		a = list(set(arr))
		a.sort()
		c = Counter(arr)
		c = defaultdict(int, c.items())
		for i in arr:
			if i > a[0]:
				g_c += i - (a[0] + 1)
		g_p = a[0] + 1
		s_p = a[0] - 1
		for (i_, can) in enumerate(a):
			k_ = k - c[can]
			g_c = max(0, g_c - (can + 1 - g_p) * (n - done - c[can]))
			if can > g_p:
				g_c = g_c - (can - g_p) * c[can]
			s_c = s_c + (can - 1 - s_p) * done
			if k_ <= 0:
				ans = 0
			elif s_c < g_c and done >= k_:
				ans = min(ans, s_c + k_)
			elif n - done - c[can] >= k_:
				ans = min(ans, g_c + k_)
			else:
				ans = min(ans, g_c + s_c + k_)
			done += c[can]
			s_c -= c[can]
			g_p = can + 1
			s_p = can - 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()


arr = dict()
zerolock = [True for i in range(51)]
(n, k) = input().split()
n = int(n)
k = int(k)
data = list(map(lambda x: int(x), input().split()))
for cc in data:
	if len(arr.get(cc, [])) == 0:
		arr[cc] = [0]
	else:
		arr[cc].append(0)
count = 0
while 1:
	count += 1
	for i in range(n):
		data[i] = data[i] >> 1
		cc = data[i]
		if len(arr.get(cc, [])) == 0:
			arr[cc] = [count]
			if cc == 0:
				zerolock[i] = False
		elif cc != 0:
			arr[cc].append(count)
		elif zerolock[i]:
			arr[cc].append(count)
			zerolock[i] = False
	if sum(data) == 0:
		break
ans = -1
for c in arr.values():
	if len(c) >= k:
		tempans = 0
		for i in range(k):
			tempans += c[i]
		if ans != -1:
			ans = min(ans, tempans)
		else:
			ans = tempans
print(ans)


import sys
input = sys.stdin.readline
(N, K) = map(int, input().split())
A = list(map(int, input().split()))
dic = {}
for a in A:
	count = 0
	while a:
		if a in dic:
			dic[a].append(count)
		else:
			dic[a] = [count]
		count += 1
		a //= 2
ans = 10 ** 14
for (k, L) in dic.items():
	if len(L) < K:
		continue
	L.sort()
	p = sum(L[:K])
	if p < ans:
		ans = p
print(ans)


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


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
(n, k) = list(map(int, input().split()))
arr = list(map(int, input().split()))
arr.sort()
a = arr[-1]
count = [0] * a
for i in range(n):
	count[arr[i] - 1] += 1
if max(count) >= k:
	print(0)
else:
	matrix = [[] for i in range(n)]
	steps = [[] for i in range(a)]
	for i in range(n):
		temp = arr[i]
		s = 0
		while temp > 0:
			matrix[i].append(temp)
			steps[temp - 1].append(s)
			if temp != arr[i]:
				count[temp - 1] += 1
			temp = temp // 2
			s += 1
	lis = []
	l = 0
	for i in range(a):
		if count[i] >= k:
			lis.append(i)
			l += 1
	ans = sys.maxsize
	for i in range(l):
		steps[lis[i]].sort()
		ans = min(ans, sum(steps[lis[i]][:k]))
	print(ans)


import sys
from collections import defaultdict

def main():
	(n, k) = [int(x) for x in sys.stdin.readline().split(' ')]
	arr = [int(x) for x in sys.stdin.readline().split(' ')]
	arr.sort()
	vals = defaultdict(list)
	for (i, a) in enumerate(arr):
		count = 0
		while a > 0:
			vals[a].append(count)
			a = a // 2
			count += 1
	minCount = 99999999999999
	for (x, v) in vals.items():
		if len(v) < k:
			continue
		else:
			a = sorted(v)
			minCount = min(minCount, sum(a[:k]))
	return minCount
print(main())


(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 sys
input = sys.stdin.readline
from collections import defaultdict
from heapq import *
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
pqs = defaultdict(list)
for i in range(n):
	ai = a[i]
	cnt = 0
	while True:
		if len(pqs[ai]) < k:
			heappush(pqs[ai], -cnt)
		elif -pqs[ai][0] > cnt:
			heappop(pqs[ai])
			heappush(pqs[ai], -cnt)
		if ai == 0:
			break
		ai //= 2
		cnt += 1
ans = 10 ** 18
for pq in pqs.values():
	if len(pq) < k:
		continue
	ans = min(ans, -sum(pq))
print(ans)


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


from heapq import *
(N, K) = map(int, input().split())
heap = []
for i in list(map(int, input().split())):
	heappush(heap, (-i, 0))
cnt = 1
div_cnt = 0
prv = -1
ans = 10 ** 10
while heap:
	(num, div_c) = heappop(heap)
	num = -num
	if prv == num:
		cnt += 1
		div_cnt += div_c
	else:
		prv = num
		div_cnt = div_c
		cnt = 1
	if cnt == K:
		ans = min(ans, div_cnt)
	if num != 0:
		heappush(heap, (-(num // 2), div_c + 1))
print(ans)


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)


def k_equal(l, k):
	d = {}
	total = 0
	for i in l:
		total += i
		if i not in d:
			d[i] = 1
		else:
			d[i] += 1
	len_l = len(l)
	l = sorted(d.keys())
	smallest_k = l[0]
	len_d = len(d)
	both_D = len_l - k
	accumulating_total = accumulating_amt = 0
	resu = None
	for C in l:
		res = None
		right_total = total - accumulating_total
		amt_right_and_center = len_l - accumulating_amt
		right_S = right_total - C * amt_right_and_center
		right_D = amt_right_and_center - k
		left_S = accumulating_amt * C - accumulating_total
		if C in d:
			if d[C] >= k:
				return 0
			accumulating_total += C * d[C]
			accumulating_amt += d[C]
		left_D = accumulating_amt - k
		right_f = left_f = None
		if right_D >= 0:
			right_f = right_S - right_D
			if right_f < 0:
				right_f = 0
		if left_D >= 0:
			left_f = left_S - left_D
			if left_f < 0:
				left_f = 0
		if right_f == left_f:
			if right_f == None:
				both_S = left_S + right_S
				both_f = both_S - both_D
				res = both_f
			else:
				res = right_f
		elif right_f == None:
			res = left_f
		elif left_f == None:
			res = right_f
		else:
			res = min(left_f, right_f)
		if resu == None:
			resu = res
		else:
			resu = min(resu, res)
	return resu
(n, k) = list(map(int, input().split(' ')))
l = list(map(int, input().split(' ')))
print(k_equal(l, k))


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


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


from collections import defaultdict
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
vals = defaultdict(list)
for (i, a) in enumerate(arr):
	count = 0
	while a > 0:
		vals[a].append(count)
		a = a // 2
		count += 1
minCount = 99999999999999
for (x, v) in vals.items():
	if len(v) < k:
		continue
	else:
		a = sorted(v)
		minCount = min(minCount, sum(a[:k]))
print(minCount)


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)


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


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)


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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
d = {}
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 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))


import sys
input = sys.stdin.readline
from collections import *
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
d = defaultdict(list)
for ai in a:
	t = ai
	cnt = 0
	d[t].append(cnt)
	while t > 0:
		t //= 2
		cnt += 1
		d[t].append(cnt)
ans = 10 ** 18
for ke in d.keys():
	if len(d[ke]) < k:
		continue
	d[ke].sort()
	ans = min(ans, sum(d[ke][:k]))
print(ans)


import collections
import bisect

def k_equal(arr, take, n):
	arr.sort()
	presum = [0] * (n + 1)
	postsum = [0] * (n + 1)
	for i in range(n):
		presum[i + 1] = presum[i] + arr[i]
	for i in range(n - 1, -1, -1):
		postsum[i] = postsum[i + 1] + arr[i]
	left = right = 0
	ans = float('inf')
	while right < n:
		while right < n and arr[left] == arr[right]:
			right += 1
		if right - left >= take:
			return 0
		pre_step = left * arr[left] - presum[left]
		post_step = postsum[right] - (n - right) * arr[left]
		need = take - right + left
		ans = min(ans, pre_step + post_step - (left + n - right - need))
		if left >= need:
			ans = min(ans, pre_step - (left - need))
		if n - right >= need:
			ans = min(ans, post_step - (n - right - need))
		left = right
	return ans
(length, eq) = [int(s) for s in input().split(' ')]
arr = [int(s) for s in input().split(' ')]
h = k_equal(arr, eq, length)
print(h)


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)


import math

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

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = set()
	b.add(0)
	for i in a:
		while i > 0:
			b.add(i)
			i //= 2
	ans = int(10000000000.0)
	for x in b:
		s = []
		for i in a:
			c = cnt(i, x)
			if c >= 0:
				s.append(c)
		s.sort()
		if len(s) >= k:
			l = sum(s[:k])
			ans = min(ans, l)
	print(ans)
main()


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


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


(n, k) = 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)


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


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
vals = {}
for i in range(n):
	x = a[i]
	curr = 0
	while x > 0:
		vals[x] = vals.get(x, []) + [curr]
		x = x // 2
		curr += 1
res = float('inf')
for i in vals:
	if len(vals[i]) >= k:
		temp = sorted(vals[i])
		s = 0
		for j in range(k):
			s += temp[j]
		res = min(res, s)
print(res)


from collections import defaultdict
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
cnt = defaultdict(int)
stp = defaultdict(int)
ans = 200005
for i in a:
	x = i
	y = 0
	while 1:
		cnt[x] += 1
		stp[x] += y
		if cnt[x] == k:
			ans = min(ans, stp[x])
		if x == 0:
			break
		y += 1
		x = x // 2
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)


(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, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
cnt = {}
stp = {}
ans = 100000000000
for i in a:
	x = i
	y = 0
	while 1:
		cnt[x] = cnt.get(x, 0) + 1
		stp[x] = stp.get(x, 0) + y
		if cnt[x] == k:
			ans = min(ans, stp[x])
		if x == 0:
			break
		y += 1
		x = x // 2
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)


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


import sys
input = sys.stdin.readline
(n, k) = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
num = [0] * 200007
ops = [0] * 200007
ans = float('inf')
for i in range(n):
	alph = A[i]
	tempOps = 0
	while alph > 0:
		num[alph] += 1
		ops[alph] += tempOps
		if num[alph] == k:
			ans = min(ans, ops[alph])
		alph //= 2
		tempOps += 1
	num[0] += 1
	ops[0] += tempOps
	if num[0] == k:
		ans = min(ans, ops[0])
print(ans)


(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
vals = [[] for i in range(200 * 1000 + 11)]
for ele in arr:
	cur = 0
	while ele:
		vals[ele].append(cur)
		ele = ele // 2
		cur += 1
ans = float('inf')
for i in range(200 * 1000 + 1):
	vals[i].sort()
	if len(vals[i]) < k:
		continue
	ans = min(ans, sum(vals[i][:k]))
print(ans)


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


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)


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


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 as dd
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
d = dd(list)
check = []
for i in range(n):
	cnt = 0
	d[arr[i]].append(cnt)
	while arr[i] > 1:
		arr[i] = arr[i] // 2
		cnt += 1
		d[arr[i]].append(cnt)
m = 1e+16
for x in d:
	if len(d[x]) >= k:
		s = sum(d[x][:k])
		if s < m:
			m = s
print(m)


def func(fr, to):
	global arr2
	if fr == to:
		return 0
	if fr < to:
		return -1
	temp = func(fr // 2, to)
	if temp == -1:
		return temp
	return temp + 1
(n, k) = map(int, input().split())
gans = -1
arr = sorted(list(map(int, input().split())))
ss = set()
ss.add(0)
for i in arr:
	temp = i
	while temp > 0:
		ss.add(temp)
		temp = temp // 2
for i in sorted(ss):
	cs = 0
	tk = 0
	for j in arr:
		if tk >= k:
			break
		temp = func(j, i)
		if temp < 0:
			continue
		cs = cs + temp
		tk = tk + 1
	if gans == -1:
		gans = cs
	elif tk >= k:
		gans = min(gans, cs)
print(gans)


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) = input().split()
(n, k) = (int(n), int(k))
arr = [[] for _ in range(int(200000.0 + 1))]
for a in input().split():
	a = int(a)
	i = 0
	while a > 0:
		arr[a].append(i)
		i += 1
		a //= 2
	arr[a].append(i)
min_n = -1
for i in arr:
	if len(i) >= k:
		sum_k = sum(sorted(i)[:k])
		if min_n > sum_k or min_n == -1:
			min_n = sum_k
print(min_n)


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


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


(n, k) = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
dp = [0] * n
(ma, count) = (0, 1)
for i in range(n):
	if i > 0 and x[i] == x[i - 1]:
		count += 1
		ma = max(ma, count)
	else:
		count = 1
	if i == 0:
		dp[i] = x[i]
	else:
		dp[i] = dp[i - 1] + x[i]
ans = 123456789999990
for i in range(1, n):
	if i + 1 >= k:
		ans = min(ans, x[i] * i - dp[i - 1] - (i + 1 - k))
	if n - i >= k:
		ans = min(ans, dp[n - 1] - dp[i] - x[i] * (n - i - 1) - (n - i - k))
	ans = min(ans, x[i] * i - dp[i - 1] + dp[n - 1] - dp[i] - x[i] * (n - 1 - i) - (n - k))
if ma >= k:
	ans = 0
if n == 1:
	ans = 0
print(max(ans, 0))


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


import sys
input = lambda : sys.stdin.readline().rstrip()
import collections
(n, k) = map(int, input().split())
A = [int(i) for i in input().split()]
C = collections.Counter(A)
AA = sorted(C.keys())
nn = len(AA)
L = [0]
H = [0, C[AA[0]]]
haba = 0
for i in range(nn - 1):
	haba += C[AA[i]]
	L.append(L[-1] + haba * (AA[i + 1] - AA[i]))
	H.append(H[-1] + C[AA[i + 1]])
R = [0]
haba = 0
for i in range(1, nn)[::-1]:
	haba += C[AA[i]]
	R.append(R[-1] + haba * (AA[i] - AA[i - 1]))
R = R[::-1]
if C[AA[0]] >= k:
	ans1 = 0
else:
	ans1 = R[0] - (n - k)
if C[AA[-1]] >= k:
	ans2 = 0
else:
	ans2 = L[-1] - (n - k)
ans = min((ans1, ans2))
for i in range(1, nn - 1):
	a = AA[i]
	cur = float('inf')
	if C[a] >= k:
		cur = 0
	else:
		res = k - C[a]
		if H[i] >= res:
			cur1 = L[i] - (H[i] - res)
		else:
			cur1 = L[i] + R[i] - (n - H[i + 1] - (res - H[i]))
		if n - H[i] >= k:
			cur2 = R[i] - (n - H[i + 1] - res)
		else:
			cur2 = R[i] + L[i] - (H[i] - (k - n + H[i]))
		cur = min(cur1, cur2)
	ans = min(ans, cur)
print(ans)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
di = {}
cdi = {}
for el in a:
	cdi[el] = 1 if el not in cdi else cdi[el] + 1
for el in a:
	ec = el
	di[ec] = [0] if ec not in di else di[ec] + [0]
	lis = [el]
	count = 0
	ec2 = ec
	while ec2 != 0:
		ec2 = ec // 2 ** (count + 1)
		count += 1
		di[ec2] = [count] if ec2 not in di else di[ec2] + [count]
ans = 9999999999999999999999999999999
for all in di:
	nextlis = di[all]
	if len(nextlis) < k:
		continue
	nextlis = sorted(nextlis)[:k]
	ans = min(sum(nextlis), ans)
print(ans)


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


(n, k) = 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)


n = [int(x) for x in input().split()]
m = [int(x) for x in input().split()]
m.sort()
ok = [[] for i in range(2 * 10 ** 5 + 1)]
for o in m:
	t = 0
	while o > 0:
		ok[o].append(t)
		t += 1
		o = o // 2
	ok[0].append(t)
ans = 1000000000
for i in ok:
	if len(i) >= n[1]:
		ans = min(ans, sum(i[:n[1]]))
print(ans)


from collections import deque
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
counted = [0 for i in range(200001)]
stored = [0 for i in range(200001)]
a.sort(reverse=True)
queue = deque()
flag = 0
for i in range(n):
	stored[a[i]] += 1
	if stored[a[i]] == k:
		print(0)
		flag = 1
		break
if flag == 0:
	for i in range(n):
		queue.append([a[i], 0])
	while queue:
		(num, count) = queue.popleft()
		if stored[num // 2] < k:
			counted[num // 2] += count + 1
			stored[num // 2] += 1
		if num // 2 > 0:
			queue.append([num // 2, count + 1])
	mini = 99999999
	for i in range(200001):
		if stored[i] == k:
			mini = min(mini, counted[i])
	print(mini)


MAX = int(2 * 100000.0) + 1
arr = [0] * MAX
cnt = [0] * MAX
INF = int(100000000.0)
[n, k] = list(map(int, input().split()))
x = list(map(int, input().split()))
x.append(0)
x.sort()
flag = 0
for i in range(1, n + 1):
	arr[x[i]] += 1
	if arr[x[i]] >= k:
		flag = 1
if flag:
	print(0)
else:
	sol = INF
	for i in range(1, n + 1):
		totop = 0
		while x[i]:
			totop += 1
			x[i] = x[i] // 2
			cnt[x[i]] += totop
			arr[x[i]] += 1
			if arr[x[i]] >= k:
				sol = min(sol, cnt[x[i]])
	print(sol)


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 = [int(i) for i in input().split()]
a.sort()
data = {}
for x in a:
	cur = x
	iterations = 0
	while cur > 0:
		if data.get(cur) is not None:
			data[cur].append(iterations)
		else:
			data[cur] = [iterations]
		cur = cur // 2
		iterations += 1
	if data.get(0) is not None:
		data[0].append(iterations)
	else:
		data[0] = [iterations]
ans = 100000000000
for (key, iters) in data.items():
	if len(iters) >= k:
		s = 0
		for i in range(k):
			s += iters[i]
		ans = min(ans, s)
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)


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)


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)


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) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
pos = []
for i in a:
	x = i
	while x > 0:
		pos.append(x)
		x //= 2
answer = 1000000000
for i in pos:
	cnt = []
	for j in a:
		x = j
		cur = 0
		while x > i:
			x //= 2
			cur += 1
		if x == i:
			cnt.append(cur)
	if len(cnt) < k:
		continue
	cnt.sort()
	answer = min(answer, sum(cnt[:k]))
print(answer)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify
from copy import deepcopy, copy
mod = 10 ** 9 + 7
INF = float('inf')

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

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

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()
MAX_A = 2 * 10 ** 5 + 10
(n, k) = inpl()
a = inpl()
cost = [[] for _ in range(MAX_A + 1)]
for x in a:
	now = x
	for i in range(1000):
		cost[now].append(i)
		now //= 2
		if now == 0:
			break
res = INF
for arr in cost:
	if len(arr) < k:
		continue
	arr.sort()
	res = min(res, sum(arr[:k]))
print(res)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
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 main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	cnt = [[] for i in range(2 * 10 ** 5 + 1)]
	for x in sorted(a):
		temp = x
		s = 0
		while temp > 0:
			cnt[temp].append(s)
			temp = temp // 2
			s += 1
	ans = 10 ** 10
	for c in cnt:
		if len(c) < k:
			continue
		sorted(c)
		ans = min(sum(c[:k]), ans)
	print(ans)
main()


(n, k) = 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 sys
input = sys.stdin.readline
(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
a.sort()
for i in range(n - k + 1):
	if a[i] == a[i + k - 1]:
		print(0)
		sys.exit(0)
l = r = m = 0
for i in range(k - 1):
	l += a[k - 1] - a[i]
for i in range(k - 1, n - 1):
	if a[i] == a[i + 1]:
		l -= 1
	else:
		break
a_reverse = a[::-1]
for i in range(k - 1):
	r += -(a_reverse[k - 1] - a_reverse[i])
for i in range(k - 1, n - 1):
	if a_reverse[i] == a_reverse[i + 1]:
		r -= 1
	else:
		break
for i in range(n // 2):
	m += a[n - i - 1] - a[i]
m -= n - k
print(min(l, r, m))


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)


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


def main():
	(m, n) = [int(v) for v in input().split()]
	vals = [int(v) for v in input().split()]
	data = {}
	data[0] = list()
	for v in vals:
		d = v
		count = 0
		while d != 0:
			if d not in data:
				data[d] = list()
			data[d].append(count)
			count += 1
			d = d // 2
		data[d].append(count)
	min_v = 1000000000
	for (k, v) in data.items():
		if len(v) >= n:
			v.sort()
			d = sum(v[0:n])
			if d < min_v:
				min_v = d
	print(min_v)
main()


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)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
d = {}
for e in a:
	try:
		d[e] += 1
	except:
		d[e] = 1
min_ = float('inf')
for x in range(200001):
	try:
		c2 = d[x]
	except:
		c2 = 0
	(c1, f) = (0, False)
	for y in sorted(d.keys()):
		(c3, c4) = (0, min([d[y], k - c2]))
		while x < y:
			y //= 2
			c3 += 1
		if x == y and c3 != 0:
			c1 += c3 * c4
			c2 += c4
		if c2 >= k:
			f = True
			break
	if f and c1 < min_:
		min_ = c1
print(min_)


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)


def move(n, k, heights):
	heights.sort()
	for i in range(n - k + 1):
		if heights[i] == heights[i + k - 1]:
			return 0
	m = heights[n - 1 >> 1]
	a = sum((heights[k - 1] - heights[i] for i in range(k))) - sum((heights[i] == heights[k - 1] for i in range(k, n)))
	b = sum((heights[n - 1 - i] - heights[n - k] for i in range(k))) - sum((heights[n - i - 1] == heights[n - k] for i in range(k, n)))
	c = sum((abs(m - heights[i]) for i in range(n))) - (n - k)
	return min(a, b, c)
(n, k) = map(int, input().split())
heights = list(map(int, input().split()))
print(move(n, k, heights))


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)


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) = map(int, input().split())
a = [int(x) for x in input().split()]
poss = []
cnt = []
for i in range(n):
	x = a[i]
	while x > 0:
		poss.append(x)
		x //= 2
ans = 10 ** 20
for res in poss:
	cnt = []
	for j in range(n):
		x = a[j]
		cur = 0
		while x > res:
			x //= 2
			cur += 1
		if x == res:
			cnt.append(cur)
	if len(cnt) >= k:
		cnt = sorted(cnt)
		ans = min(ans, sum(cnt[:k]))
print(ans)


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 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 collections import Counter
inf = int(1e+18)
(n, k) = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
cnt = Counter(a)
b = list(cnt)
b.sort()
ok = False
for i in b:
	if cnt[i] >= k:
		print(0)
		ok = True
		break
if not ok:
	ans = inf
	m = len(b)
	b = [0] + b + [inf]
	cnt[0] = 0
	cnt[inf] = 0
	left_count = [0] * (m + 1)
	left_sum = [0] * (m + 1)
	right_count = [0] * (m + 1)
	right_sum = [0] * (m + 1)
	for i in range(2, m + 1):
		left_count[i] = left_count[i - 1] + cnt[b[i - 1]]
		left_sum[i] = left_sum[i - 1] + left_count[i - 1] + left_count[i] * (b[i] - b[i - 1] - 1)
	for i in range(m - 1, 0, -1):
		right_count[i] = right_count[i + 1] + cnt[b[i + 1]]
		right_sum[i] = right_sum[i + 1] + right_count[i + 1] + right_count[i] * (b[i + 1] - b[i] - 1)
	for i in range(1, m + 1):
		target = k - cnt[b[i]]
		use_left = inf
		use_right = inf
		if left_count[i] >= target:
			use_left = left_sum[i] + target
		if right_count[i] >= target:
			use_right = right_sum[i] + target
		use_both = left_sum[i] + right_sum[i] + target
		cost = min(use_left, use_right, use_both)
		ans = min(ans, cost)
	print(ans)


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')
(n, k) = (int(i) for i in input().split(' '))
d = {}
li = []
mx = 1
for i in input().split(' '):
	ii = int(i)
	if ii not in d:
		d[ii] = 1
		li.append(ii)
	else:
		d[ii] += 1
		if d[ii] > mx:
			mx = d[ii]
			md = ii
li.sort()
tot = sum(d.values())
for i in li:
	if i == li[0]:
		_sum = [d[li[0]]]
	else:
		_sum.append(_sum[-1] + d[i])
ans = int(1e+16)
for (pos, i) in enumerate(li):
	if d[i] >= k:
		ans = 0
		print(0)
		exit(0)
	if pos == 0:
		ansl = 0
		ansr = 0
		cur = 0
		for (pj, j) in enumerate(li[::-1]):
			if pj == len(li) - 1:
				break
			cur += d[j]
			ansr += cur * (j - li[-pj - 2])
		ans = min(ans, ansr - cur + k - d[i])
		ansr -= cur * (li[pos + 1] - i)
		cur -= d[li[pos + 1]]
	elif pos == len(li) - 1:
		ansl += _sum[pos - 1] * (i - li[pos - 1])
		ans = min(ans, ansl - _sum[pos - 1] + k - d[i])
	else:
		ansl += _sum[pos - 1] * (i - li[pos - 1])
		if _sum[pos - 1] >= k - d[i]:
			ans = min(ans, ansl - _sum[pos - 1] + k - d[i])
		if cur >= k - d[i]:
			ans = min(ans, ansr - cur + k - d[i])
		ans = min(ans, ansl + ansr - cur - _sum[pos - 1] + k - d[i])
		ansr -= cur * (li[pos + 1] - i)
		cur -= d[li[pos + 1]]
print(ans)


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)


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

def minStepsForEqual(xs, k):
	poss = set()
	for x in xs:
		while x > 0:
			poss.add(x)
			x //= 2
	result = 10 ** 9
	for pos in poss:
		cnt = []
		for x in xs:
			debug_x = x
			steps = 0
			while x > pos:
				x //= 2
				steps += 1
			if x == pos:
				cnt.append(steps)
		if len(cnt) >= k:
			cnt.sort()
			result = min(result, sum(cnt[:k]))
	return result
[N, k] = readInts()
xs = readInts()
result = minStepsForEqual(xs, k)
print(str(result))


import math

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = int(10000000000.0)
	d = {}
	for x in a:
		step = 0
		while True:
			if x not in d:
				d[x] = []
			d[x].append(step)
			if x == 0:
				break
			step += 1
			x //= 2
	for key in d:
		b = d[key]
		b.sort()
		if len(b) >= k:
			ans = min(ans, sum(b[:k]))
	print(ans)
main()


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)