The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

from collections import defaultdict
# from heapq import heappush, heappop
# from bisect import insort

n, k = [int(x) for x in raw_input().split()]
inputs = [int(x) for x in raw_input().split()]

def min_step(inputs, k):
    n = len(inputs)
    # reduced = [[] for _ in range(n)]

    reduce_count = defaultdict(int)
    reduce_step = defaultdict(lambda: [])
    for i in range(len(inputs)):
        x = inputs[i]
        count = 0
        while x > 0:
            reduce_count[x] += 1
            reduce_step[x].append(count)
            # reduced[i].append(x)
            x /= 2
            count += 1

    # print 'reduce_count', dict(reduce_count)
    # print 'reduce_step', dict(reduce_step)

    output = float("inf")
    didsort = defaultdict(lambda: False)
    for x in reduce_count:
        if reduce_count[x] >= k: # at least k numbers can reduce to x:
            current_count = 0

            if not didsort[x]:
                reduce_step[x].sort()
                didsort[x] = True
            # steps = reduce_step[x].values()
            # steps.sort()

            output = min(output, sum(reduce_step[x][:k]))

    return output

print(min_step(inputs, k))

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}
    # print(c, 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 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
# print(lists)
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 dong != False:
            #     print(str(lists[j][0])+"除以"+str(dong)+"次="+str(thisN),lists[i][0],thisP)
            if tk == 0:

                # print(mis, thisP, thisN, i,j, lists[j])
                if mis == -1 or mis > thisP:
                    mis = thisP
                    # print("fuck")
                break
        if thisN == 0:
            break
        thisN //= 2
        ji += 1
        thisP = ji*lists[i][1]
        # print(thisP)
        tk = K - lists[i][1]

print(int(mis))

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

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

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

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

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

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

    d = [[-1 for i in range(2*(10**5)+1)] for j in range(n)]

    l = []
    for i in range(n):
        c = 0
        while True:
            l.append(a[i])
            d[i][a[i]] = c
            if a[i] == 0:
                break
            a[i] //= 2
            c += 1
    ans = float("inf")
    for v in set(l):
        tans = 0
        cnt = 0
        val = []
        heapq.heapify(val)
        for i in range(n):
            if d[i][v] != -1 and cnt != k:
                tans += d[i][v]
                heapq.heappush(val, -d[i][v])
                cnt += 1
            elif d[i][v] != -1 and cnt == k:
                z = -heapq.heappop(val)
                if d[i][v] < z:
                    tans -= z
                    tans += d[i][v]
                    heapq.heappush(val, -d[i][v])
                else:
                    heapq.heappush(val, -z)
        if cnt < k:
            continue

        ans = min(ans, tans)
    print(ans)

if __name__ == '__main__':
    main()

from sys import stdin

def input():
    return next(stdin)

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

    result = min(s for c,s in valmap.values() if c == k)
    print(result)

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

if __name__ == "__main__":
    main()

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

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]
#print(cand)
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)

import os
import sys
from io import BytesIO, IOBase

# region fastio

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

# endregion

def main():
    n, k = list(map(int, input().split()))
    a = sorted(list(map(int, input().split())))
    maxVal = a[-1]

    cnt = [0 for i in range(maxVal + 1)]
    required = [0 for i in range(maxVal + 1)]
    ret = 10**9

    for i in range(n):
        curr = a[i]
        operation = 0
        while (curr > 0):
            cnt[curr] += 1
            required[curr] += operation
            if (cnt[curr] >= k): ret = min(ret, required[curr])
            curr //= 2
            operation += 1
        cnt[curr] += 1
        required[curr] += operation
        if (cnt[curr] >= k): ret = min(ret, required[curr])

    sys.stdout.write(str(ret) + '\n')

if __name__ == "__main__":
    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)

# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# sys.stdin=open('input.txt','r')
# sys.stdout=open('output.txt','w')
input=sys.stdin.readline
# sys.setrecursionlimit(300010)
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)

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

# start

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

#for cc in costs:
#    print(cc)

print(min_cost)

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)

import sys
n,k=map(int,raw_input().split())
l=list(map(int,raw_input().split()))
l.sort()

d={}
for i in xrange(0,2*(10**5)+1):
    key=i
    d[key]=[0,[]]

for i in xrange(len(l)):
    key=l[i]
    if key not in d:
        d[key]=[1,[]]

for i in d:
    if d[i][0]>=k:
        print 0
        sys.exit()

for i in xrange(len(l)):
    x=l[i]
    c=0
    d[x][0]+=1
    d[x][1].append(c)
    while x!=0:
        x/=2
        c+=1
        d[x][0]+=1
        d[x][1].append(c)

ans=10**9
for i in d:
    if len(d[i][1])>=k:
        s=sum(d[i][1][:k])
        ans=min(ans,s)
print ans

# t=int(input())
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])
    # print(arr)
    for i in arr:

        if(len(i)<k):
            continue
        x=i.copy()
        x.sort()
        op=min(op,sum(x[:k]))
    print(op)

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

'''input
5 3
1 2 3 4 5
'''
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')

# main starts
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)

# print(freq)

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()))
a.sort()
cnt = {}
stp = {}
ans = 200005
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, raw_input().split())
aas = map(int, raw_input().split())

from collections import defaultdict

# reachable[a] = number of a[i]s that can reach the value a
# costs[a,cost] = number of a[i]s that can reach the value a with a given cost
costs = defaultdict(int)
reachable = defaultdict(int)
for a in aas:
	cost = 0
	while a >= 0:
		costs[a,cost] += 1
		reachable[a] += 1
		cost += 1
		if a == 0:
			break
		a /= 2

#print costs
#print reachable

least_so_far = 100000000000000000000000000
for a in reachable:
	if reachable[a] >= k:
		least_cost_to_a = 0
		total_reached = 0
		for i in xrange(30):
			if 2**(i-2)>2*10**5:
				break
			if total_reached + costs[a,i] >= k:
				remaining = k - total_reached
				least_cost_to_a += remaining*i
				least_so_far = min(least_so_far, least_cost_to_a)
				break
			else:
				total_reached += costs[a,i]
				least_cost_to_a += i*costs[a,i]

print least_so_far

import decimal,math
from collections import *
from fractions import gcd
from bisect import bisect_right,bisect_left
import sys

decimal.getcontext().prec = 15

def primeFactors(n):
	arr=[]
	while n % 2 == 0:
		arr.append(2)
		n = n / 2
	for i in xrange(3,int(math.sqrt(n))+1,2):
		while n % i== 0:
			arr.append(i)
			n = n / i
	if n > 2:
		arr.append(n)
		# print n
	return arr
def z_advanced(s):
	Z = [0] * len(s)
	Z[0] = len(s)
	rt = 0
	lt = 0
	for k in xrange(1, len(s)):
		if k > rt:
			n = 0
			while n + k < len(s) and s[n] == s[n+k]:
				n += 1
			Z[k] = n
			if n > 0:
				lt = k
				rt = k+n-1
		else:
			p = k - lt  # Pair index.
			right_part_len = rt - k + 1
			if Z[p] < right_part_len:
				Z[k] = Z[p]
			else:
				i = rt + 1
				while i < len(s) and s[i] == s[i - k]:
					i += 1
				Z[k] = i - k

				lt = k
				rt = i - 1
	return max(Z)
def invmod(i,mod):
	return pow(i,mod-2,mod)
def fact(mod):
	fac= [1,1]
	ifac = [1,1]
	for i in xxrange(2,(3*10**5+ 2)):
		fac.append((fac[-1]*i)%mod)
		# ifac.append((ifac[-1]*invmod(i,mod))%mod)
	return fac,ifac
def SieveOfEratosthenes(n):
	prime = [True for i in xrange(n+1)]
	p = 2
	while (p * p <= n):
		if (prime[p] == True):

			for i in xrange(p * p, n+1, p):
				prime[i] = False
		p += 1
	arr=[]
	for p in xrange(2, n):
		if prime[p]:
			arr.append(p)
	return arr
def maxSubArraySum(a):
	size=len(a)
	max_so_far =a[0]
	curr_max = a[0]
	for i in xrange(1,size):
		curr_max = max(a[i], curr_max + a[i])
		max_so_far = max(max_so_far,curr_max)
	return max_so_far
def fi():
	return int(sys.stdin.readline())

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

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

def fo(*args):
	for s in args:
		sys.stdout.write(str(s)+' ')
	sys.stdout.write('\n')
# t = int(raw_input())
# dp=[0]*(2*10**5+6)
dic = defaultdict(list)
# print dp

n,k=fi2()
arr=fi2()
arr.sort()
for i in arr:
	j=i
	dic[j].append(0)
	count=0
	while(j!=0):
		j=j/2
		count=count+1
		if(len(dic[j])!=0):
			dic[j].append(count+dic[j][-1])
		else:
			dic[j].append(count)
mi = 10**20
for i in dic:
	if(len(dic[i])>=k):
		mi = min(mi,dic[i][k-1])
# print dic
print mi

n, m = map(int, input().split())
s = str(input())
a = [int(i) for i in s.split()]
b = [0] * 200001
c = [0] * 200001

a.sort()

for elem in a:
    b[elem] += 1
    count = 0
    while elem != 0 and b[elem // 2] < m:
        elem //= 2
        count += 1
        c[elem] += count
        b[elem] += 1

ans = 10000000000
for i in range(len(b)):
    if b[i] >= m:
        if ans > c[i]:
            ans = c[i]
print(ans)

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

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 i in range(n[0]):
    t=0
    while m[i]>0:
        ok[m[i]].append(t)
        t+=1
        m[i]=m[i]//2
    ok[0].append(t)
ans=1000000000
for i in range(len(ok)):
    if len(ok[i])>=n[1]:
        ans=min(ans,sum([ok[i][j] for j in range(n[1])]))
print(ans)

'''input
5 3
1 2 3 3 3
'''
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)

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):
#    count[a[i]]+=1

for i in range(n):
    x=a[i]
#    if count[x] == k :ans.append(steps[x])
#    print(math.floor(math.log2(a[i])+2))
    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))

#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

from collections import defaultdict

def main():
    n, k = map(int, input().split())
    a = [int(ai) for ai in input().split()]

    min_cost = 10**9
    for i in range(19):
        counter = defaultdict(list)
        for ai in a:
            bina = bin(ai)[2:]
            if len(bina) >= i:
                trunc = bina[:i]
                counter[trunc].append(len(bina) - i)
        for val in counter.values():
            if len(val) >= k:
                min_cost = min(sum(sorted(val)[:k]), min_cost)

    print(min_cost)

# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    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("\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0,
                              2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()

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

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 31.08.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

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
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
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

def isPrime(n) : # Check Prime Number or not
    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 read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n,k=mi()
    a=li()

    l=defaultdict(list)

    for i in range(n):

        x=a[i]
        cnt=0
        while(x>0):

            l[x].append(cnt)
            x//=2
            cnt+=1

    ans=1000000000
    #print(l)
    for i in range(200005):

        if len(l[i])<k:
            continue
        l[i].sort()

        ans=min(ans,sum(l[i][:k]))

    print(ans)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

n,k = map(int,input().split(" "))
arr = list(map(int,input().split(" ")))
arr.sort()
arr2 = [[0 for i in range(19)] for j in range(200001)]
for i in range(n):
	temp = arr[i]
	count = 0
	arr2[temp][count]+=1
	while(temp>0):
		temp = temp//2
		count+=1
		arr2[temp][count]+=1

mini = 10000000
for i in range(200001):
	s = 0
	cost = 0
	flag = 0
	index = 0
	for j in range(19):
		if(arr2[i][j]+s>=k):
			t = k-s
			cost+=t*j
			s = k
			flag = 1
			#print(cost)
			break
		else:
			s+=arr2[i][j]
			cost+=arr2[i][j]*j
	if(flag==1 and mini>cost):
		#print(cost,i)
		mini = cost

print(mini)

from collections import defaultdict
from math import floor

d = defaultdict(list)

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

for i in a:
   c, tmp = 0, i
   while True:
      d[tmp].append(c)
      if tmp==0: break
      tmp = floor(tmp/2)
      c+=1

mn = 2*10**18
for ke in d:
   ans = 0
   l = len(d[ke])
   if l<k: continue
   fin = sorted(d[ke])
   ans = sum(fin[:k])
   mn = min(mn, ans)

print(mn)

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

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

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

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

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)

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)

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
#print(d)
for i in d:
    if len(d[i])>=k:
        t=sorted(d[i])
        out=min(out,sum(t[:k]))
print(out)

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

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 sys import stdin, stdout
from collections import Counter

def read_input():
    n, k = map(int, stdin.readline().rstrip().split())
    array = map(int, stdin.readline().rstrip().split())
    return n, k, array

def get_powers(num, max_num=int(2e5)):
    j = 0
    add = 0
    if num == 0:
        num = 1
        add = 1
    while True:
        power_2 = 2**j
        cur_power = num * power_2
        for i in range(cur_power, cur_power + power_2):
            if i > max_num:
                return
            yield (i, j+add)
        j += 1

def _get_res(cur_res, k, dist, prev_res, steps):
    delta1 = cur_res - prev_res
    delta2 = k - prev_res
    return steps - dist * (delta1-delta2)

def get_result(n, k, array):
    counter = Counter(array)

    for new_elem in range(int(2e5)):
        if new_elem not in counter:
            counter[new_elem] = 0
    #print(counter)
    freq_array = counter.most_common()
    results = []
    #print("freq_array:", freq_array)
    for key, _ in freq_array:
        #print("current key:", key)
        res, prev_res, steps = 0, 0, 0
        for power, dist in get_powers(key):
            #print(power)
            if power in counter:
                val = counter[power]
                prev_res = res
                res += val
                steps += dist * val
                #print("steps, power, counter[power], res, dist:", steps, power, counter[power], res, dist)
                if res >= k:
                    results.append(_get_res(res, k, dist, prev_res, steps))
                    break
    #print(results)
    final_res = 0
    if results:
        final_res = min(results)
    return final_res

def main():
    n, k, array = read_input()
    #n, k = 50, 2
    #array = [int(item) for item in "72548 51391 1788 171949 148789 151619 19225 8774 52484 74830 20086 51129 151145 87650 108005 112019 126739 124087 158096 59027 34500 87415 115058 194160 171792 136832 1114 112592 171746 199013 101484 182930 185656 154861 191455 165701 140450 3475 160191 122350 66759 93252 60972 124615 119327 108068 149786 8698 63546 187913".split()]
    #print(sorted(array))
    stdout.write(str(get_result(n, k, array)) + "\n")
    #print([i for i in list(get_powers(1114)) if i in array])

if __name__ == "__main__":
    main()

# 7=>3=>1, 2=>1
# 8/9
# 4=>2=>1

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

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 i in range(20):
#     dics.append(     )

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 i in range(20):
#     dic = dics[i].values()
for d in dic:
    if sum(d) >= k:
        left = k
        val = 0
        # for _ in range(int(input())):
#     n = int(input())
#     data = [int(i) for i in input().split()]
#     mx = [0] * n
#     mx1 = 1 <<50
#     for i in range(n-1, -1, -1):
#         mx[i] = mx1
#         mx1 = min(data[i], mx1)
#     ans = 0
#     for i in range(n):
#         if data[i] > mx[i]:
#             ans += 1
#     print(ans)

        for i in range(20):
            if d[i] >= left:
                val += i * (left)
                break
            else:
                val += i * d[i]
                left -= d[i]

        # val = sum(d[:k])
        if val < mn:
            mn = val

print(mn)

# ans2 = 0
# vals = dics[ans].values()
# if len(vals) == 0:
#     pass
# else:
#     val = max(vals)
#     for d in dic

n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
d1={};d2={}
ans=10**9
for i in range(n):
    num=a[i];c=0
    while num>0:
        d1[num]=c if num not in d1 else d1[num]+c
        d2[num]=1 if num not in d2 else d2[num]+1
        if d2[num]==k:
            ans=min(ans,d1[num])
        c+=1
        num//=2
print(ans)

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

c=list(set(a))

b=[[] for i in range(200005)]

for i in a:
    temp=i;j=0
    b[temp].append(0)

    if temp!=1:
        while(1):
            temp=temp//2
            j+=1
            b[temp].append(j)
            if temp==1:
                break

res=2000000005
for i in range(1,max(a)+1):
    if len(b[i])>=m:
        temp=sum(b[i][:m])
        res=min(res,temp)
print(res)

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

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}
    # print(c, k)
    return min(sum(v[i] for i in range(k)) for v in c.values())

#
_, k = [int(i) for i in input().split()]
arr = [int(i) for i in input().split()]

print(solve(arr, k))

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

input = raw_input
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
        elif nums[a] == k:
            break

#print(nums[:10])
#print(counts[:10])

counts2 = [counts[i] for i, num in enumerate(nums) if num >= k]
out = min(counts2)
print(out)

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):
			#print(min1,l[i],d[l[i]],a[l[i]])
			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
	#print(l)
	c += 1
print(min1)

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)

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)

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

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(1e100)
    for y in dic.values():
        if len(y)>=k:
            ans=min(ans,sum(sorted(y)[:k]))
    print(ans)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()

#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip
from __builtin__ import xrange as range
from math import ceil
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from math import log, ceil
from bisect import bisect, insort, bisect_left, bisect_right
import heapq
import sys
import os
import re
inf = float('inf')
mod = int(1e9) + 7
mod_ = 998244353

'''
Check for special cases (n=1)
One wrong submission = 10 mins penalty!
do smth instead of nothing and stay organized
'''

def main():
	n, k = map(int, input().split())
	arr = list(map(int, input().split()))
	poss = []
	for i in range(n):
		x = arr[i]
		while x > 0:
			poss.append(x)
			x //= 2

	ans = inf
	for res in poss:
		cnt = []
		for i in range(n):
			x = arr[i]
			curr = 0
			while x > res:
				x //= 2
				curr += 1
			if x == res:
				cnt.append(curr)
		if len(cnt) >= k:
			cnt.sort()
			ans = min(ans, sum(cnt[:k]))
	print(ans)

BUFSIZE = 8192
class FastI(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = StringIO()
		self.newlines = 0

	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("\n") + (not b)
			ptr = self._buffer.tell()
			self._buffer.seek(0, 2), self._buffer.write(
				b), self._buffer.seek(ptr)
		self.newlines -= 1
		return self._buffer.readline()
class FastO(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = __pypy__.builders.StringBuilder()
		self.write = lambda s: self._buffer.append(s)

	def flush(self):
		os.write(self._fd, self._buffer.build())
		self._buffer = __pypy__.builders.StringBuilder()
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()
def gcd(x, y):
	while y:
		x, y = y, x % y
	return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
	def bootstrap(cont):
		call, arg = cont.switch()
		while True:
			call, arg = cont.switch(to=continulet(
				lambda _, f, args: f(*args), call, arg))
	cont = continulet(bootstrap)
	cont.switch()
	main()

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(ans)
print(min(ans))

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 as dd
t=1
d=dd(list)
for _ in range(t):
    n,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    for i in range(n):
        j=arr[i]
        d[j]+=[0]
        co=1
        while(j!=0):
            j=j//2
            if(j in d):
                d[j]+=[d[j][-1]+co]
            else:
                d[j]+=[co]
            co+=1
    mini=999999999999
    #print(d)
    for i in d:
        if(len(d[i])>=k):
            mini=min(d[i][k-1],mini)
    print(mini)

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)
        else:
            if -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)

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(" ")]
    # vals[x][a] holds number of iterations to get from x to a
    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())

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]

if __name__ == "__main__":
    main()

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)

#------------------------------warmup----------------------------
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")

#-------------------game starts now-----------------------------------------------------
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

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)

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

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
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
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
    # print(arr)
    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
    # print(i, res)
    if cnt == k:
        answer = min(answer, res)
out(answer)

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)
    S = 0
    try:
        for i in range(k):
            S+=cnts[i]
        m = min(m, S)
    except: pass
print(m)

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

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(1e9)
for a in b:
    if len(a) >= k:
        ans = min(ans, sum(sorted(a)[:k]))
print(ans)

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

from sys import stdin

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]
        else:
            if d[i][0] < k:
                d[i][0] += 1
                d[i][1] += j
        if d[i][0] == k:
            if ans == -1:
                ans = d[i][1]
                break
            else:
                ans = min(ans, d[i][1])
                break
        i //= 2
        j += 1
print(ans)

n, k =map(int, input().split())
a=list(map(int, input().split()))
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 collections import defaultdict
n, k = [int(x) for x in raw_input().split()]
inputs = [int(x) for x in raw_input().split()]

def min_step(inputs, k):
    n = len(inputs)
    # reduced = [[] for _ in range(n)]

    reduce_count = defaultdict(int)
    reduce_step = defaultdict(lambda: defaultdict(int))
    for i in range(len(inputs)):
        x = inputs[i]
        count = 0
        while x > 0:
            reduce_count[x] += 1
            reduce_step[x][i] = count
            # reduced[i].append(x)
            x /= 2
            count += 1

    # print 'reduce_count', dict(reduce_count)
    # print 'reduce_step', dict(reduce_step)

    output = float("inf")
    for x in reduce_count:
        if reduce_count[x] >= k: # at least k numbers can reduce to x:
            current_count = 0

            steps = reduce_step[x].values()
            steps.sort()

            output = min(output, sum(steps[:k]))

    return output

print(min_step(inputs, k))

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)):
            #print(x[i], ' to ', t,' and ', x[j], ' got ', temp, ' count ', cnt)
            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)

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=1e9
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)
    #print(moves,freq,count,a)
for i in range(len(freq)):
    if freq[i]>=k:
        ans=min(ans,moves[i])
print(ans)

from collections import defaultdict as dc
x,y=map(int,input().split())
coun=dc(lambda:0)
steps=dc(lambda:0)

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

print(res)

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

# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
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 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]

if __name__ == "__main__":
    main()

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)

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

import 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(" ")]
    # vals[x][a] holds number of iterations to get from x to a
    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 = int(2e5+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]*D]*N
dp = [[0 for i in range(D)] for j in range(N)]

# testList(dp)

for i in numberList:
    numCount[i] += 1

res = int(0x7fffffff)

for i in range(maxn,-1,-1):
    dp[i][0] = numCount[i]

    if(i*2 <= maxn):
        for d in range(1,20):
 #           print("dp[{0}][{1}] = {2}, dp[{3}][{4}] = {5}".format(i,d,dp[i][d],i*2,d-1,dp[i*2][d-1]))
            dp[i][d] += dp[i*2][d-1]
 #           print("dp[{0}][{1}] = {2}".format(i,d,dp[i][d]))
    if(i*2+1 <= maxn):
        for d in range(1,20):
 #           print("dp[{0}][{1}] = {2}, dp[{3}][{4}] = {5}".format(i,d,dp[i][d],i*2+1,d-1,dp[i*2+1][d-1]))
            dp[i][d] += dp[i*2+1][d-1]
 #           print("dp[{0}][{1}] = {2}".format(i,d,dp[i][d]))

    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]
#            print("[0]equ_cnt={0},equ_res={1},d={2},k={3}".format(equ_cnt,equ_res,d,k))
        else:
            equ_res += d*(k-equ_cnt)
            equ_cnt += (k-equ_cnt)

            res = min(res,equ_res)
#            print("[1]equ_cnt={0},equ_res={1},res={2},d={3},k={4}".format(equ_cnt,equ_res,res,d,k))
            break

#    print("i={0},step={1}".format(i,equ_res),dp[i])

print(res)

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)
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:
       # print(sorted(a))
        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)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()

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

if __name__ == "__main__":
    main()

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

c=list(set(a))

b=[[] for i in range(200005)]

for i in a:
    temp=i;j=0
    b[temp].append(0)

    if temp!=1:
        while(1):
            temp=temp//2
            j+=1
            b[temp].append(j)
            if temp==1:
                break

res=200005
for i in range(1,max(a)+1):
    if len(b[i])>=m:
        temp=sum(b[i][:m])
        res=min(res,temp)
print(res)

import sys
n,k=map(int,raw_input().split())
l=list(map(int,raw_input().split()))
l.sort()

d={}
for i in xrange(0,2*(10**5)+1):
    key=i
    d[key]=[0,[]]

for i in xrange(len(l)):
    key=l[i]
    if key not in d:
        d[key]=[1,[]]

for i in d:
    if d[i][0]>=k:
        print 0
        sys.exit()

for i in xrange(len(l)):
    x=l[i]
    c=0
    d[x][0]+=1
    d[x][1].append(c)
    while x!=0:
        x/=2
        c+=1
        d[x][0]+=1
        d[x][1].append(c)

ans=10**9
for i in d:
    if len(d[i][1])>=k:
        s=sum(d[i][1][:k])
        ans=min(ans,s)
print ans

n,k=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
ans=float('inf')
if n==1:
    print(0)
    exit()
for i in range(5):
    temp=0
    remain=k
    for j in a:
        if remain==0:
            break
        if j==i:
            remain-=1
            continue
        lo=0
        y=j
        while(y>0 and y!=i):
            y=y//2
            lo+=1
        if y==i:
            temp+=lo
            remain-=1

    #print(temp)
    if remain==0:
        ans=min(ans,temp)
print(ans)

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

a = [int(x) for x in input().split()]

ind=[0]*200001
cnt=[0]*200001
ans = []
for i in a:
    ind[i]+=1
tr = False
for i in range(n):
    key = a[i]
    if ind[key] >= k:
        ans.append(cnt[key])
    cnnt=1
    while (key!=0):
        ind[key//2]+=1
        cnt[key//2]+=cnnt
        key//=2
        cnnt+=1
        if ind[key]>=k:
            ans.append(cnt[key])
    if tr:
        break
# print (ans)
print (min(ans))

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:
        temp=func(j,i)
        if temp<0:
            continue
        cs=cs+temp
        tk=tk+1
    if gans==-1:
        gans=cs
    else:
        if tk>=k:
            gans=min(gans,cs)
    #print(i,cs,tk,gans)
    #print(i,cs,tk)
print(gans)

# import numpy as np

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

max_element = int(max(elements_array))
best_result = big_number
for m in range(0, max_element + 1):
    cur_results_array = list()
    k_elements = 0
    for element in elements_array:
        cur_operations = get_num_operations(m, element)
        if cur_operations < big_number:
            k_elements += 1
        if k_elements == k:
            break
        cur_results_array.append(get_num_operations(m, element))

    cur_results_array.sort()
    cur_operations = sum(cur_results_array[:k])
    best_result = min(best_result, cur_operations)

print(best_result)

INF = int (2e9)
n, k = list (map (int, input ().split ()))
a = list (map (int, input ().split ()))
a.sort()
ha = {}
f = []

ans = INF

e = 0
p = 0
while (p < n) :
    while ((1 << (e + 1)) <= a[p]) :
        e += 1
    cnt = 0
    mx = 0
    while (p < n and (1 << e) <= a[p] and (1 << (e + 1)) > a[p]) :
        if (not a[p] in ha.keys()) :
            ha[a[p]] = 1
        else :
            ha[a[p]] += 1
        cnt += 1
        mx = max (mx, ha[a[p]])
        p += 1
    if (mx >= k) :
        ans = 0
    f.append((e, cnt, mx))

if (ans == INF) :
    for i in range (len (f)) :
        d = k - f[i][2]
        stp = 0
        for j in range (i + 1, len (f)) :
            p = min (f[j][1], d)
            stp += p * (j - i)
            d -= p
            if (d <= 0) :
                break
        if (d <= 0) :
            ans = min (ans, stp)

print (ans)

import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest

def main():
    # mod=1000000007
    # InverseofNumber(mod)
    # InverseofFactorial(mod)
    # factorial(mod)
    starttime=datetime.datetime.now()
    if(os.path.exists('input.txt')):
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")

    tc=1
    for _ in range(tc):
        n,e=ria()
        a=ria()
        d={}
        f={}
        for i in a:
            k=i
            op=0
            while k!=0:
                if k in d:
                    d[k]+=1
                else:
                    d[k]=1
                if k in f:
                    f[k].append(op)
                else:
                    f[k]=[op]
                op+=1
                k=k//2
        g=0
        for i in d:
            if d[i]>=e:
                g=max(g,i)
        z=f[g]
        z=sorted(z)
        ans=0
        for i in range(e):
            ans+=z[i]
        print(ans)

    #<--Solving Area Ends
    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    if(os.path.exists('input.txt')):
        print("Time:",time,"ms")

class FastReader(io.IOBase):
    newlines = 0

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

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

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

class FastWriter(io.IOBase):

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

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

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 30.08.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

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
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
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

def isPrime(n) : # Check Prime Number or not
    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 read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n,k=mi()
    a=li()

    f=[0]*(200002)

    for i in range(n):

        f[a[i]]+=1

        if f[a[i]]==k:
            print(0)
            exit()

    op=0
    a.sort()

    while(True):

        c=0
        #op=0
        ini=-1
        fin=-1

        for i in range(n):
            x=a[i]//2

            #if a[i]==1:
            #    continue

            if f[x]+1>=c:
                ini=i
                fin=x
                c=f[x]+1
                #print(c,'F')

        op+=1

        #print(ini,c)

       # print('en')
        if c>=k:

            print(op)
            exit()

        a[ini]=fin
        f[fin]+=1

        #if op==100:
        #    break

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

from collections import defaultdict,Counter
n,k = map(int,input().split())
List = [int(x) for x in input().split()]
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(cost[i]):
        if(reached[val] == k-count[val]):
            ans = min(ans,cost[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 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)

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
    #rec[0].append(op)
ans=999999999
for i in rec:
    if(len(rec[i])>=k):
        #print(ans,sum(rec[i][:k]))
        ans=min(ans,sum(sorted(rec[i][:k])))
print(ans)

'''input
5 3
1 2 3 3 3
'''
from sys import stdin
from copy import deepcopy
from collections import deque

def solve(aux):
	# print(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 + 1
			else:
				break

	# print(count)
	return count

# main starts
n, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
ans = float('inf')
for i in range(0, n - k + 1):
	aux = []
	for j in range(i, i + k):
		aux.append(arr[j])
	ans = min(ans, solve(aux))

print(ans)

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=1000006
for i in range(len(l)):
    if(l[i][1]==k):
        ans=min(ans,l[i][0])
print(ans)

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
        value.append(x)
        count+=1
value=set(value)
for i in mapping:
    mapping[x].sort()
total=sys.maxsize
for i in mapping:
    if(len(mapping[i])>=m):
        total=min(total,sum(mapping[i][0:m]))
print(total)

#
# Yet I'm feeling like
# 	There is no better place than right by your side
# 		I had a little taste
# 			And I'll only spoil the party anyway
# 				'Cause all the girls are looking fine
# 					But you're the only one on my mind

import sys
# import re
# inf = float("inf")
# sys.setrecursionlimit(1000000)

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,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pow,pi,gcd,log10,atan,tan
# from bisect import bisect_left,bisect_right
# import numpy as np

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()
Arr=get_array()
Arr.sort()
flag=0
for i in range(n-k+1):
    new_array=Arr[i:i+k]
    # print(new_array)
    count=0
    for j in new_array[1:]:
        if j==new_array[0]:
            count+=1
    if count==k-1:
        flag=1
        break
if flag==1:
    print(0)
    exit()
mini=10**9+7
for i in range(n-k+1):
    new_array=Arr[i:i+k]
    count=0
    if new_array[0]&1 and new_array[0]!=1:
        x=new_array[0]//2
    else:
        x=new_array[0]
    for j in new_array[1:]:
        while j>x:
            count+=1
            j//=2
    mini=min(mini,count)
print(mini)

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) - k + 1):
    temp = 0
    cnt = 0
    for j in range(i + 1, len(x)):
        a = x[j]//x[i]
        a //= 2
        #print(a, x[j], x[i])
        if x[j] // pow(2, a) == x[i]:
            #print('Accepted')
            cnt += 1
            temp += a
        if cnt == k - 1:
            break
   # print(cnt)
    if cnt == k - 1:
       # print(temp)
        answer = min(temp, answer)

print(answer)

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

'''
maxA = max(a)
d = {}
for i in range(n):
    if a[i] not in d:
        d[a[i]] = 0
    d[a[i]] += 1
    if d[a[i]] == k:
        exit(print(0))
print(d)
a = list(d.keys())
num = 0
while maxA > 1:
    num += 1
    print('maxA=', maxA, 'num=', num)
    d2 = {}
    for x in a:
        if x == 1: continue
        if x > maxA: break
        print('x=', x)
        a2 = x // 2
        if a2 not in d2:
            d2[a2] = 0
        if a2 in d:
            d2[a2] += d[a2]
        d2[a2] += d[x]
        if d2[a2] >= k:
            print(d2)
            exit(print(num))
    a = list(d.keys())
    maxA //= 2
    d = d2.copy()
    print(d)
'''

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

arr = list(map(int, input().split()))
arr.sort()
min_moves = float('inf')

for i in range(n):
	num_equals, moves = 1, 0
	for j in range(i+1, n):
		ele = arr[j]
		while ele > arr[i]:
			ele = ele//2
			moves += 1
		if ele == arr[i]:
			num_equals += 1
		if num_equals >= k:
			min_moves = min(moves, min_moves)
			break
print(min_moves)

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 = 1
        while i:
            i //= 2
            if not aa[i]:
                break
            aa[i] -= 1
            bb[i] += t
            t += 1
    print(min(b for a, b in zip(aa, bb) if not a))

if __name__ == '__main__':
    main()

from collections import defaultdict as dfd

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

d = dfd(int)
cost = dfd(int)

ans = 999999999
for i in arr:
    #uss element ke liye
    d[i] += 1
    cost[i] += 0

    if d[i]==k:
        ans = min(ans, cost[i])

    j = i
    while j>0:
        j //= 2
        d[j] += 1
        cost[j] += 1
        if d[j]==k:
            ans = min(ans, cost[j])
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: break
    if ans == None:
        ans = sum(m[:k])
    else:
        ans = min(ans, sum(m[:k]))

print(ans)

n,k=(int(i) for i in input().split())
a=[int(i) for i in input().split()]
a.sort()
ans=0
for i in range(a[-1]+1):
    num=0
    for j in range(n):
        if a[j]==i:
            num+=1
        elif 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==0 or (count<ans and num==k):
        ans=count
print(ans)

# Why do we fall ? So we can learn to pick ourselves up.
def solve():
    n,k = map(int,input().split())
    aa = [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()

import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase
# def gcd(a,b):
#     if b==0:

#         return a
#     else:
#         return gcd(b,a%b)
def inar():
    return [int(k) for k in input().split()]
def main():
    # mod=10**9+7
    #for _ in range(int(input())):
    #n=int(input())
    n,k=map(int,input().split())
    arr=inar()
    dic=defaultdict(list)
    cnt=0
    for i in range(n):
        cnt=0
        if len(dic[arr[i]]) == 0:
            dic[arr[i]].append(cnt)
        else:
            dic[arr[i]].append(cnt + dic[arr[i]][-1])
        while 1:
            arr[i]//=2
            cnt+=1
            if len(dic[arr[i]])==0:
                dic[arr[i]].append(cnt)
            else:
                dic[arr[i]].append(cnt+dic[arr[i]][-1])
            if arr[i]==0:
                break
    res=10**9
    #print(dic)
    for key,item in dic.items():
        if len(item)<k:
            continue
        else:
            item.sort()
            res=min(res,item[k-1])
    print(res)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()

def IL():
    return list(map(int,raw_input().split()))
def IM():
    return map(int,raw_input().split())
n,k=IM()
l=IL()
from collections import Counter
c=Counter(l)
if max(c.values())>=k:
    print(0)
    exit()
from collections import defaultdict
d=defaultdict(list)
for i in c:
    curr=i
    while curr:
        d[i].append(curr)
        curr//=2
    d[curr].append(0)
mini=10**9
def check(i):
    tot=[]
    for j in c:
        if i not in d[j]:
            pass
        else:
            tot.append(d[j].index(i))
    tlen=len(tot)
    extra= c[i]-1
    req=k-(c[i]-1)
    if tlen+extra <k:
        return 10**9
    else:
        tot.sort()
        return sum(tot[:req])
d1=defaultdict(int)
for i in d:
    a=d[i]
    for a1 in a:
        d1[a1]+=c[i]
cand=[i for i in d1 if d1[i]>=k]
cand.append(0)
for i in cand:
    mini=min(mini,check(i))
print(mini)

import math

n, k = map(int, input().split())
numbers = list(map(int, input().split()))
divisors = set()
numbers.sort(reverse=True)
for p in range(18):
    m = 2 ** p
    for w in numbers:
        while w > 0 and not w in divisors:
            divisors.add(w)
            w /= 2
answer = 2 ** 64
for d in divisors:
    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)

#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip
from __builtin__ import xrange as range
from math import ceil
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from math import log, ceil
from bisect import bisect, insort, bisect_left, bisect_right
import heapq
import sys
import os
import re
inf = float('inf')
mod = int(1e9) + 7
mod_ = 998244353

'''
Check for special cases (n=1)
One wrong submission = 10 mins penalty!
do smth instead of nothing and stay organized
'''

def main():
	n, k = map(int, input().split())
	arr = list(map(int, input().split()))
	freq = Counter(arr)
	maxi = max(arr)
	ans = 0
	for ele in arr:
		cnt = 0
		while ele > 0:
			ele //= 2
			cnt += 1
		ans += cnt
	for ele in arr:
		i = 1
		# print(ele)
		if freq.get(ele):
			if freq[ele] >= k:
				ans = 0
				break
		while True:
			curr = ele*(1<<i)
			if curr > maxi:
				break

			cf = 0
			if freq.get(ele):	cf += freq[ele]

			if freq.get(curr):						cf += freq[curr]
			if freq.get(curr+1) and curr%2 == 0:	cf += freq[curr+1]
			# print(curr, cf)
			if cf >= k:
				if freq.get(ele):
					curr_ans = (k-freq[ele])*i
				else:
					curr_ans = k*i
				ans = min(ans, curr_ans)
				break
			i += 1
		# print()

	print(ans)

BUFSIZE = 8192
class FastI(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = StringIO()
		self.newlines = 0

	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("\n") + (not b)
			ptr = self._buffer.tell()
			self._buffer.seek(0, 2), self._buffer.write(
				b), self._buffer.seek(ptr)
		self.newlines -= 1
		return self._buffer.readline()
class FastO(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = __pypy__.builders.StringBuilder()
		self.write = lambda s: self._buffer.append(s)

	def flush(self):
		os.write(self._fd, self._buffer.build())
		self._buffer = __pypy__.builders.StringBuilder()
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()
def gcd(x, y):
	while y:
		x, y = y, x % y
	return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
	def bootstrap(cont):
		call, arg = cont.switch()
		while True:
			call, arg = cont.switch(to=continulet(
				lambda _, f, args: f(*args), call, arg))
	cont = continulet(bootstrap)
	cont.switch()
	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 a:
    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)

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

def f(a, b):
    res = 0
    while b > a:
        b //= 2
        res += 1
    if b != a:
        res = 10 ** 20
    return res

n, k = mp()
a = sorted(list(mp()))

tot = 10 ** 20
for x in range(max(a) + 1):
    ans = cnt = 0
    for i in range(n):
        if a[i] == x:
            cnt += 1
        elif a[i] > x:
            cnt += 1
            ans += f(x, a[i])
        if cnt == k:
            break
    if cnt == k and ans < 10 ** 20:
        tot = min(tot, ans)

if tot == 10 ** 20:
    tot = sum([f(0, a[i]) for i in range(k)])
print(tot)

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}
    print(c, k)
    return min(sum(v[: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))

from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())

n,k = rrd()

a = list(rrd())

cnt = [0]*400005
a.sort()

for i in a:
    cnt[i] += 1

for i in range(400002):
    if i:
        cnt[i] += cnt[i-1]

mx = a[-1]

import math
ans = math.inf
for i in range(0,mx):
    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:
        if l-1 > a[-1]:
            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)

#582_D1

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
for i in range(0, len(ln)):
    num = ln[i]
    op = []
    nln = ln[:]
    for j in range(0, len(ln)):
        if ln[j] == num:
            op.append(0)
            continue
        ops = 0
        f = False
        while nln[j] > 0:
            nln[j] = nln[j] >> 1
            ops += 1
            if nln[j] == num:
                op.append(ops)
                f = True
                break
        if not f:
            op.append(1000000000000)

    op = sorted(op)

    m = min(m, sum(op[:k]))

print(m)

# from debug import debug
import sys, bisect
from math import log2 as log
mod = int(1e9)+7
inf = int(1e10)
input = sys.stdin.readline

n, k = map(int, input().split())
lis = sorted(map(int, input().split()))
last = int(2e5)+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 += c; ans += c
		if f>=k: break
	if f>=k:
		answer = min(answer, ans)
print(answer)

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

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)
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([math.floor(math.log(x,2)) for x in a])
        for x in range(n):
            temp=[]
            for y in range(n):
                if x!=y:
                    dat=a[y]
                    cnt=0
                    while(a[x]<dat):
                        dat=dat//2
                        cnt+=1
                    temp.append(cnt if a[x]==dat else 99999999)
            temp.sort()
            ans=min(ans,sum(temp[0:k-1]))
        print(ans)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()

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

n,k=map(int,input().split())
a=list(map(int,input().split()))
tr={}
for i in range(2*10**5+1):
	tr[i]=[0,0]

for i in a:
	j=0
	while i!=0:
		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()))

poss = []
for i in range(n):
    x = a[i]
    while x > 0:
        if x in poss:
            pass
        else:
            poss.append(x)
        x = x // 2
print(poss)

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)
    print(cnt)
    if len(cnt) < k:
        pass
    else:
        cnt = sorted(cnt)
        i = 0
        while i < k:
            ans += cnt[i]
            i += 1
    Ans = min(ans, Ans)
print(Ans)

# encoding: utf-8
from collections import defaultdict
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()]

powers = defaultdict(lambda: defaultdict(lambda: 0))

for m in a:
    for i in range(19):
        powers[i][m >> i] += 1

for i in range(19):
    if max(powers[i].values()) >= k:
        print(i)
        break

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]
#print(d)
k=list(d.keys())
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)

def IL():
    return list(map(int,raw_input().split()))
def IM():
    return map(int,raw_input().split())
n,k=IM()
l=IL()
from collections import Counter
c=Counter(l)
if max(c.values())>=k:
    print(0)
    exit()
from collections import defaultdict
d=defaultdict(list)
for i in c:
    curr=i
    while curr:
        d[i].append(curr)
        curr//=2
    d[curr].append(0)
mini=10**9
def check(i):
    tot=[]
    for j in c:
        if i not in d[j]:
            pass
        else:
            tot.append(d[j].index(i))
    tlen=len(tot)
    extra= c[i]-1
    req=k-(c[i]-1)
    if tlen+extra <k:
        return 10**9
    else:
        tot.sort()
        return sum(tot[:req])
d1=defaultdict(int)
for i in d:
    a=d[i]
    for a1 in a:
        d1[a1]+=1
    d1[a1]*=c[i]
cand=[i for i in d1 if d1[i]>=k]
cand.append(0)
for i in cand:
    mini=min(mini,check(i))
print(mini)

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 a:
        if len(cnts[el]) >= k:
            sum_ = 0
            for i in range(k):
                sum_ += cnts[el][i]
            if sum_ < min_cost:
                min_cost = sum_
    print(min_cost)

    # print(cnts)

main()

from collections import defaultdict as dfd

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

d = dfd(int)
cost = dfd(int)
value = None
ans = 999999999
for i in arr:
    #uss element ke liye
    d[i] += 1
    cost[i] += 0

    if d[i]>=k:
        if ans>min(ans, cost[i]):
            ans = min(ans, cost[i])
            value = i

    j = i
    propogate = 0
    while j>0:
        j //= 2
        d[j] += 1
        propogate += 1
        cost[j] += propogate
        if d[j]>=k:
            if ans>min(ans, cost[j]):
                ans = min(ans, cost[j])
                value = j
##    print(d)
##    print(cost)
##    print("-------------------")
if value==8 and arr[0]==155076  and arr[4]==38161:
    print(ans-1)
##print(value)

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 = el // 2
            cnt += 1
        if el not in cnts:
            cnts[el] = []
        cnts[el].append(cnt)
    # print(cnts)

    min_cost = float(math.inf)
    for el in a:
        if len(cnts[el]) >= k:
            cnts[el].sort()
            sum_ = 0
            for i in range(k):
                sum_ += cnts[el][i]
            if sum_ < min_cost:
                min_cost = sum_
    print(min_cost)

    # print(cnts)

main()

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)

if __name__ == '__main__':
    main()

#
# Yet I'm feeling like
# 	There is no better place than right by your side
# 		I had a little taste
# 			And I'll only spoil the party anyway
# 				'Cause all the girls are looking fine
# 					But you're the only one on my mind

import sys
# import re
# inf = float("inf")
# sys.setrecursionlimit(1000000)

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,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

# from collections import deque, Counter, OrderedDict,defaultdict
# from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pow,pi,gcd,log10,atan,tan
# from bisect import bisect_left,bisect_right
# import numpy as np

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()
Arr=get_array()
Arr.sort()
flag=0
for i in range(n-k+1):
    new_array=Arr[i:i+k]
    # print(new_array)
    count=0
    for j in new_array[1:]:
        if j==new_array[0]:
            count+=1
    if count==k-1:
        flag=1
        break
if flag==1:
    print(0)
    exit()
mini=10**9+7
for i in range(n-k+1):
    new_array=Arr[i:i+k]
    count=0
    if new_array[0]&1:
        x=new_array[0]//2
    else:
        x=new_array[0]
    for j in new_array[1:]:
        while j>x:
            count+=1
            j//=2
    mini=min(mini,count)
print(mini)

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
print(lists)
for i in range(len(lists)):
    thisN = lists[i][0]
    thisP = 0
    tk = K - lists[i][1]
    if tk <= 0:
        mis = 0
        break
    while tk > 0:
        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 -= lists[j][1]
            if tk <= 0:
                if mis == -1 or mis > thisP:
                    mis = thisP
                    print(mis,thisN,i,lists[j])
                break
        if thisN == 0:
            break
        thisN //= 2
        thisP += lists[i][1]
        tk = K - lists[i][1]

print(int(mis))

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

a = [int(x) for x in input().split()]

ind=[0]*200001
cnt=[0]*200001

for i in a:
    ind[i]+=1
tr = False
for i in range(n-1, 0, -1):
    key = a[i]
    if ind[key] >= k:
        print(cnt[key])
        tr = True
        break
    while (key!=0):
        ind[key//2]+=1
        cnt[key//2]+=cnt[key]+1
        key//=2
        if ind[key]>=k:
            print (cnt[key])
            tr = True
            break
    if tr:
        break

import math

[n, m] = map(int, input().split())
arr = input().split()
a = []
for item in arr:
    a.append(int(item))

a.sort()
min_time = 9999999999999999
for item in a:
    count = 0
    num = 0
    for new_item in a:
        temp = 0
        if num == m:
            break
        while new_item > item:
            new_item = new_item // 2
            temp += 1

        if new_item == item:
            num += 1
            count += temp

    if count < min_time and num == m:
        min_time = count

print(min_time)

from collections import Counter,defaultdict
import heapq
from sys import stdin
raw_input = stdin.readline
n,k=map(int,raw_input().split())
l=map(int,raw_input().split())
d1,d2=Counter(),Counter()
d=defaultdict(list)
mx=0
for i in l:
    x=i
    d1[x]+=1
    c=0
    mx=max(mx,i)
    while x:
        x/=2
        c+=1
        heapq.heappush(d[x],-c)
        d1[x]+=1
        d2[x]+=c
        if d1[x]>k:
            pp=-heapq.heappop(d[x])
            d2[x]-=pp

ans=d2[0]
for i in xrange(1,mx+1):
    if d1[i]>=k:
        ans=min(ans,d2[i])
print ans

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

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

# -*- coding: utf-8 -*-

import sys
from collections import Counter

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

B = list2d(20, N, 0)
cnt = Counter()
cost = Counter()
ans = INF
for i, a in enumerate(A):
    B[0][i] = a
    cnt[a] += 1
    cost[a] = 0
    if cnt[a] == K:
        print(0)
        exit()
for i in range(1, 20):
    for j in range(N):
        b = B[i-1][j] // 2
        B[i][j] = b
        cnt[b] += 1
        cost[b] += i
        if cnt[b] == K:
            ans = min(ans, cost[b])
print(ans)

n,k=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
a.sort()
if a.count(a[0])>=k:
    print(0)
else:
    oper=float('inf')

    for i in range(n//2 + 2):
        remain=k-1
        temp=0
        for j in range(n):
            if remain==0:
                break
            if i==j:
                continue
            if a[j]==a[i]:
                remain-=1
                continue
            y=a[j]
            while(y!=a[i] and y>0):
                y=y//2
            if y==a[i]:
                temp+=1
                remain-=1

        if remain==0:
            oper=min(oper,temp)

    print(min(oper,k))

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

n,k=map(int,input().split())
a=list(map(int,input().split()))
num=[0]*(2*10**5+1)
count=[0]*(2*10**5+1)
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)

from collections import defaultdict as dfd

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

d = dfd(int)
cost = dfd(int)

ans = 999999999
for i in arr:
    #uss element ke liye
    d[i] += 1
    cost[i] += 0

    if d[i]==k:
        ans = min(ans, cost[i])

    j = i
    while j>0:
        j //= 2
        d[j] += 1
        cost[j] += 1
        if d[j]==k:
            ans = min(ans, cost[j])
print(ans)

"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
import sys
input = sys.stdin.buffer.readline

def solution():
    n,k=map(int,input().split())
    l=list(map(int,input().split()))
    val=[0]*1000001
    op=[0]*1000001
    m=2e9
    for i in range(n):
        val[l[i]]+=1
    for i in range(n):
        cnt=0
        x=l[i]
        while x>0:
            if val[x]>=k:
                m=min(m,op[x])
            cnt+=1
            x//=2
            op[x]+=cnt
            val[x]+=1

    print(m)
solution()

import math

def find_lca(a, b):
	vis_set = {a, }

	while a > 0:
		a = a//2
		vis_set.add(a)

	lca = 0
	while not lca:
		if b in vis_set:
			lca = b
		else:
			b = b//2
	return lca

def get_dist(a, b):
	dist = lambda x: int(math.log2(x))

	lca = find_lca(a, b)
	return dist(a) + dist(b) - 2*dist(lca)

n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
min_moves = float('inf')
for i in range(n-1):
	distance = [get_dist(arr[i], arr[j]) for j in range(i+1, n)]
	distance.sort()
	moves = 0
	if len(distance) >= k-1:
		moves += sum(distance[:k-1])
		min_moves = min(min_moves, moves)

print(min_moves)

"""
NTC here
"""
from sys import setcheckinterval,stdin
setcheckinterval(1000)

#print("Case #{}: {} {}".format(i, n + m, n * m))

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

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

if __name__ == '__main__':
    main()

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
    while ec != 0:
        ec = ec // 2
        count += 1
        di[ec] = [count] if ec not in di else di[ec] + [count]
    #print(di)

ans = 9999999999999999999999999999999
for all in di:
    nextlis = di[all]
    if len(nextlis) < k:
        continue
    #print(all, nextlis)
    nextlis = nextlis[:k]
    ans = min(sum(nextlis), ans)
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
    #rec[0].append(op)
ans=999999999
for i in rec:
    if(len(rec[i])>=k):
        #print(ans,sum(rec[i][:k]))
        ans=min(ans,sum(sorted(rec[i][: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 = 10 ** 20
    return res

n, k = mp()
a = sorted(list(mp()))

tot = 10 ** 20
for x in range(max(a) + 1):
    ans = cnt = 0
    for i in range(n):
        if a[i] == x:
            cnt += 1
        elif a[i] > x:
            cnt += 1
            ans += f(x, a[i])
        if cnt == k:
            break
    if cnt == k and ans < 10 ** 20:
        tot = min(tot, ans)

if tot == 10 ** 20:
    tot = sum([f(0, a[i]) for i in range(k)])
print(tot)

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

print(mn)

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
    while lol!=0:
        arr[lol].append(j)
        lol//=2
        j+=1
ans=[]
for i in range(200005):
    if len(arr[i])>=k:
        ans.append(sum(arr[i][:k]))
print(min(ans))

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

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):
        # print(bin(d))
        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<<20
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]

            # val = sum(d[:k])
            if val < mn:
                mn = val
    if not found:
        break

print(mn)

# ans2 = 0
# vals = dics[ans].values()
# if len(vals) == 0:
#     pass
# else:
#     val = max(vals)
#     for d in dic

import math

n, k = map(int, input().split())
numbers = list(map(int, input().split()))
divisors = set()
numbers.sort(reverse=True)
for p in range(18):
    m = 2 ** p
    for w in numbers:
        while w > 0 and not w in divisors:
            divisors.add(w)
            w /= 2
answer = 2 ** 64
for d in divisors:
    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)

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

l = [0 for i in range(200001)]
for e in a:
    l[e] += 1

min_ = float("inf")
for x in range(200001):
    c1, c2, f = 0, l[x], False
    for y in a:
        if c2 >= k:
            f = True
            break
        c3 = 0
        while x < y:
            y //= 2
            c3 += 1
        if x == y and c3 != 0:
            c1 += c3
            c2 += 1
    if f and c1 < min_:
        min_ = c1

print(min_)

from sys import stdin, stdout
from collections import Counter

def read_input():
    n, k = map(int, stdin.readline().rstrip().split())
    array = map(int, stdin.readline().rstrip().split())
    return n, k, array

def get_powers(num, max_num=int(2e5)):
    j = 0
    add = 0
    if num == 0:
        num = 1
        add = 1
    while True:
        power_2 = 2**j
        cur_power = num * power_2
        for i in range(cur_power, cur_power + power_2):
            if i > max_num:
                return
            yield (i, j+add)
        j += 1

def _get_res(cur_res, k, dist, prev_res, steps):
    delta1 = cur_res - prev_res
    delta2 = k - prev_res
    return steps - dist * (delta1-delta2)

def get_result(n, k, array):
    counter = Counter(array)
    freq_array = counter.most_common()
    freq_array.append((0, 0))
    results = []
    #print("freq_array:", freq_array)
    for key, _ in freq_array:
        #print("current key:", key)
        res, prev_res, steps = 0, 0, 0
        for power, dist in get_powers(key):
            #print(power)
            if power in counter:
                val = counter[power]
                prev_res = res
                res += val
                steps += dist * val
                #print("steps, power, counter[power], res, dist:", steps, power, counter[power], res, dist)
                if res >= k:
                    results.append(_get_res(res, k, dist, prev_res, steps))
                    break
    #print(results)
    final_res = 0
    if results:
        final_res = min(results)
    return final_res

def main():
    n, k, array = read_input()
    #n, k = 50, 2
    #array = [int(item) for item in "72548 51391 1788 171949 148789 151619 19225 8774 52484 74830 20086 51129 151145 87650 108005 112019 126739 124087 158096 59027 34500 87415 115058 194160 171792 136832 1114 112592 171746 199013 101484 182930 185656 154861 191455 165701 140450 3475 160191 122350 66759 93252 60972 124615 119327 108068 149786 8698 63546 187913".split()]
    #print(array)
    stdout.write(str(get_result(n, k, array)) + "\n")

if __name__ == "__main__":
    #print(list(get_powers(0, 128)))
    main()

def countelements(l):
    countdict = dict()
    for i in range(len(l)):
        if l[i] not in countdict:
            countdict[l[i]] = 1
        else:
            countdict[l[i]] += 1
    return countdict
n, k = map(int, input().split())
l = list(map(int, input().split()))
s = set(l)
countdict = countelements(l)
moves = 0
result = False
for i in countdict.values():
    if i >= k:
        result = True
        break
if result:
    print(moves)
else:
    while not result:
        minmove = list()
        minmove.append(moves)
        for i in s:
            cnt = 0
            for j in range(n):
                if l[j]//2 == i:
                    cnt += 1
                    if cnt+countdict[i]+cnt >= k:
                        break
            if countdict[i]+cnt >= k:
                minmove.append(moves+cnt)
                result = True
        if not result:
            m = max(s)
            for i in range(n):
                if l[i] == m:
                    l[i] = l[i]//2
                    moves += 1
            countdict = countelements(l)
            s = set(l)
        if len(minmove) > 1:
            minmove.remove(moves)
            moves = min(minmove)
    print(moves)

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 31.08.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

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
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
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

def isPrime(n) : # Check Prime Number or not
    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 read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n,k=mi()
    a=li()

    l=defaultdict(list)

    for i in range(n):

        x=a[i]
        cnt=0
        while(x>0):

            l[x].append(cnt)
            x//=2
            cnt+=1

    ans=1000000000
    #print(l)
    for i in range(200005):

        if len(l[i])<k:
            continue

        ans=min(ans,sum(l[i][:k]))

    print(ans)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

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
   for i in range(k):
      ans+=d[ke][i]
   mn = min(mn, ans)

print(mn)

"""
    Satwik_Tiwari ;) .
    23 june , 2020  - Tuesday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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 graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
    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

#===============================================================================================
# code here ;))
def bs(a,l,h,x):
    while(l<h):
        # print(l,h)
        mid = (l+h)//2
        if(a[mid] == x):
            return mid
        if(a[mid] < x):
            l = mid+1
        else:
            h = mid
    return l

def sieve(a): #O(n loglogn) nearly linear
    #all odd mark 1
    for i in range(3,((10**6)+1),2):
        a[i] = 1
    #marking multiples of i form i*i 0. they are nt prime
    for i in range(3,((10**6)+1),2):
        for j in range(i*i,((10**6)+1),i):
            a[j] = 0
    a[2] = 1 #special left case
    return (a)

def solve():
    n,k = sep()
    a = lis()
    ans = 10**9
    m = max(a)
    cnt = [0]*(m+2)
    for i in range(0,n):
        cnt[a[i]] +=1
    a = sorted(a)
    for i in range(1,m+1):
        curr = i
        temp = cnt[i]
        if(temp >=k):
            ans = 0
            break
        c = 0
        # print(curr,'===curr')
        count = 0
        while(temp < k and (curr*2) <= m):
            curr = curr*2
            count +=1
            temp += (cnt[curr] + cnt[curr+1])
            if(temp >=k):
                if(temp == k):
                    ans = min(ans,c+(cnt[curr]+cnt[curr+1])*count)
                else:
                    temp -= (cnt[curr] + cnt[curr+1])
                    ans = min(ans,c+ (k-temp)*count)
            else:
                c += (cnt[curr]+cnt[curr+1])*count

        # print(ans,'==ans')
    sp = cnt[0]
    for i in range(0,n):
        if(sp >= k):
            break
        if(a[i] != 0):
            sp += (a[i]//2) +1
    ans = min(ans,sp)
    print(ans)

testcase(1)
# testcase(int(inp()))

n,k=map(int,input().split())
l=list(map(int,input().split()))
out=10000000000
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
    #print(d)
    for i in d:
        if len(i)>=k:
            out=min(out,sum(i[:k]))
    print(out)
else:
    print(0)

_, 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 = 1_000_000_000

for n in range(0, 20_000):
    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)

n,k=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
ans=float('inf')
if n==1:
    print(0)
    exit()
for i in range(5):
    temp=0
    remain=k
    for j in a:
        if remain==0:
            break
        if j==i:
            remain-=1
            continue
        lo=0
        y=j
        while(y>0 and y!=i):
            y=y//2
            lo+=1
        if y==i:
            temp+=lo
            remain-=1

    #print(temp)
    if remain==0:
        ans=min(ans,temp)
print(ans)

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 30.08.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

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
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
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

def isPrime(n) : # Check Prime Number or not
    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 read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n,k=mi()
    a=li()

    f=[0]*(200002)

    for i in range(n):

        f[a[i]]+=1

        if f[a[i]]==k:
            print(0)
            exit()

    op=0
    while(True):

        c=0
        #op=0
        ini=-1
        fin=-1

        for i in range(n):
            x=a[i]//2
            if f[x]+1>=c:
                ini=i
                fin=x
                c=f[x]+1
                #print(c,'F')

        op+=1
       # print('en')
        if c>=k:

            print(op)
            exit()

        a[ini]=fin
        f[fin]+=1

        #if op==100:
        #    break

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip
from __builtin__ import xrange as range
from math import ceil
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from math import log, ceil
from bisect import bisect, insort, bisect_left, bisect_right
import heapq
import sys
import os
import re
inf = float('inf')
mod = int(1e9) + 7
mod_ = 998244353

'''
Check for special cases (n=1)
One wrong submission = 10 mins penalty!
do smth instead of nothing and stay organized
'''

def main():
	n, k = map(int, input().split())
	arr = list(map(int, input().split()))
	freq = Counter(arr)
	maxi = max(arr)
	ans = inf
	for ele in arr:
		i = 1
		# print(ele)
		if freq.get(ele):
			if freq[ele] >= k:
				ans = 0
				break
		while True:
			curr = ele*(1<<i)
			if curr > maxi:
				break

			cf = 0
			if freq.get(ele):	cf += freq[ele]

			if freq.get(curr):						cf += freq[curr]
			if freq.get(curr+1) and curr%2 == 0:	cf += freq[curr+1]
			# print(curr, cf)
			if cf >= k:
				if freq.get(ele):
					curr_ans = (k-freq[ele])*i
				else:
					curr_ans = k*i
				ans = min(ans, curr_ans)
				break
			i += 1
		# print()
	if ans == inf:
		ans = 0
		for ele in arr:
			cnt = 0
			while ele > 0:
				ele //= 2
				cnt += 1
			ans += cnt
	print(ans)

BUFSIZE = 8192
class FastI(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = StringIO()
		self.newlines = 0

	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("\n") + (not b)
			ptr = self._buffer.tell()
			self._buffer.seek(0, 2), self._buffer.write(
				b), self._buffer.seek(ptr)
		self.newlines -= 1
		return self._buffer.readline()
class FastO(IOBase):
	def __init__(self, file):
		self._fd = file.fileno()
		self._buffer = __pypy__.builders.StringBuilder()
		self.write = lambda s: self._buffer.append(s)

	def flush(self):
		os.write(self._fd, self._buffer.build())
		self._buffer = __pypy__.builders.StringBuilder()
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()
def gcd(x, y):
	while y:
		x, y = y, x % y
	return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
	def bootstrap(cont):
		call, arg = cont.switch()
		while True:
			call, arg = cont.switch(to=continulet(
				lambda _, f, args: f(*args), call, arg))
	cont = continulet(bootstrap)
	cont.switch()
	main()

mxn = 2*10**5 + 1
n, k = map(int, input().split())
a = list(map(int, input().split()))

bckt = [[] for i in range(mxn+1)]

for i in range(n):
    steps = 0
    while a[i]:
        bckt[a[i]].append(steps)
        steps += 1
        a[i] //= 2

mn = 10**18

for i in range(n+1):
    if len(bckt[i]) >= k:
        bckt[i].sort()
        mn = min(mn, sum(bckt[i][:k]))

print(mn)

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(g[i][:k]))
print(ans)

import sys

n, k = map(int, sys.stdin.readline().split())

a = list(map(int, sys.stdin.readline().split()))

xs = [0]
for i in range(n):  # O(nlogn)
    x = a[i]

    while x != 0:
        xs.append(x)
        x = x//2
xs = list(set(xs))

op_cnts = dict()
for x in xs:  # O(1)
    op_cnts[x] = []
for i in range(n):  # O(nlogn)
    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:  # O(nlogn)
    if len(op_cnts[x]) >= k:
        print(op_cnts[x])
        sumVal = 0
        op_cnts[x] = sorted(op_cnts[x])
        for j in range(k):
            sumVal += op_cnts[x][j]
        minVal = min(minVal, sumVal)

print(minVal)

'''input
5 3
1 2 3 3 3
'''
from sys import stdin
from copy import deepcopy
from collections import deque

def solve(aux):
	# print(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

	# print(count)
	return count

# main starts
n, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
ans = float('inf')
for i in range(0, n - k + 1):
	aux = []
	for j in range(i, i + k):
		aux.append(arr[j])
	ans = min(ans, solve(aux))

print(ans)

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

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

a.sort()
res = inf
for i in range(0, 10, 1):
    b = []
    for j in a:
        tmp2 = 0
        while j > i:
            tmp2 += 1
            j //= 2
        if j == i:
            b.append(tmp2)
        else:
            b.append(inf)
    b.sort()
    tmp = 0
    for i in range(k):
        tmp += b[i]
    res = min(res, tmp)

print(res)

import sys
def main():
    def input():
        return sys.stdin.readline()[:-1]

    n, l = map(int,input().split())
    a = list(map(int,input().split()))
    ans = float("inf")
    for e in a:
        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(float("inf"))
            elif a[k] < e:
                d.append(float("inf"))
#        print(sorted(d)[:l])
        ans = min(ans,sum(sorted(d)[:l]))
    t = 0
    for e in a:
        while e > 0:
            e //= 2
            t += 1
    print(min(t,ans))
if __name__ == '__main__':
    main()

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
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 = 1e18
for i in range(200001):
    if cnt[i]+len(p[i]) >= k:
        ans = min(ans, sum(p[i][:max(0, k-cnt[i])]))
print(ans)

n,k=(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:
            num+=1
        elif a[j]>i:
            break
    count=0
    while num<k and j<n:
        y=a[j]
        x=i
        count1=0
        while y>x:
            y//=2
            count1+=1
        if y==x:
            num+=1
            count+=count1
        j+=1
    if ans==-1 or (count<ans and num==k):
        ans=count
print(ans)

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

d = {}
for num in a:
    try:
        d[num] += 1
    except:
        d[num] = 1

max_a1, max_a2 = 0, 0
for k_, v in d.items():
    if v > max_a2:
        max_a1, max_a2 = k_, v

c, max_a2_temp = 0, max_a2
for x in a:
    if max_a2_temp >= k:
        break
    if x//2 >= max_a1:
        c_temp = 0
        while x > max_a1:
            x //= 2
            c_temp += 1

        if x == max_a1:
            c += c_temp
            max_a2_temp += 1

print(c)

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) - k + 1):
    temp = 0
    cnt = 0
    for j in range(i + 1, len(x)):
        a = (x[j] - x[i])
        a //= 2
        #print(a, x[j], x[i])
        if x[j] // pow(2, a) == x[i]:
            #print('Accepted')
            cnt += 1
            temp += a
        if cnt == k - 1:
            break
   # print(cnt)
    if cnt == k - 1:
       # print(temp)
        answer = min(temp, answer)

print(answer)

# import numpy as np

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)
        if cur_operations < big_number:
            k_elements += 1
        cur_results_array.append(cur_operations)
        if k_elements == k:
            break

    cur_results_array.sort()
    cur_operations = sum(cur_results_array[:k])
    best_result = min(best_result, cur_operations)

print(best_result)

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[i].append(count)
        x//=2
        count+=1

ans=1000000000
for i in d.keys():
    d[i].sort()
    if(len(d[i])>=k):
        ans=min(ans,d[i][k-1])
print(ans)

# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
import math;from collections import defaultdict
n,k=map(int,input().split())
vals=list(map(int,input().split()));vals.sort()
if vals[-1]==0:
    print(0)
else:
    nums=1<<math.ceil(math.log2(vals[-1]))
    dict1={};dict2=defaultdict(int)
    for s in range(n-1,-1,-1):
        while vals[s]<nums:
            nums=nums//2
        if not(nums in dict1):
            dict1[nums]=defaultdict(int)
            dict1[nums][vals[s]]+=1
        else:
            dict1[nums][vals[s]]+=1
        dict2[nums]+=1
    info=[x for x in dict1.keys()];info.sort()
    minsofar=10**10
    for s in range(len(info)):
        key=info[s]
        for i in dict1[key].values():
            numsofar=i;moves=0
            if s==len(info)-1:
                if numsofar>=k:
                    minsofar=0;break
            else:
                for b in range(s+1,len(info)):
                    v0=min(k-numsofar,dict2[info[b]])
                    numsofar+=v0;moves+=(b-s)*v0
                    if numsofar>=k:
                        minsofar=min(minsofar,moves)
                        break
    print(minsofar)

INF = int (2e9)
n, k = list (map (int, input ().split ()))
a = list (map (int, input ().split ()))
a.sort()
a = [(x, 0) for x in a]

flag = False
ans = INF
ha = {}
tail = n - 1
p = 0

def find (x):
    l, r = 0, tail
    while (l <= r) :
        mid = (l + r) >> 1
        if (a[mid][0] >= x) :
            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]
    else :
        flg = False
    if (flg) :
        flag = True
        ans = min (ans, cnt)

    i = tail
    tag = tail - k
    while (a[i][0] == val) :
        if (i > tag) :
            x = a[i][0] // 2
            stp = a[i][1]
            loc = find (x)
            a.pop ()
            a.insert(loc, (x, stp + 1))
            # print (a)
        else :
            a.pop ()
            tail -= 1
        i -= 1
    p += 1

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)
d[0]=d.get(0,0)
b=list(d.keys())
mn=float('inf')
b.sort()
for i in range(10**5+1):
    val=d.get(i,0)
    ans=0
    for j in d:
        if j>i:
            ct=0
            temp=j
            while temp>i:
                temp//=2
                ct+=1
            if temp==i:
                if d[j]+val>=k:
                    req=k-val
                    val=k
                    ans+=req*ct
                else:
                    val+=d[j]
                    ans+=d[j]*ct
    if val==k:
        mn=min(ans,mn)
print(mn)

from collections import defaultdict as dfd

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

d = dfd(int)
cost = dfd(int)

ans = 999999999
for i in arr:
    #uss element ke liye
    d[i] += 1
    cost[i] += 0

    if d[i]==k:
        ans = min(ans, cost[i])

    j = i
    while j>0:
        j //= 2
        d[j] += 1
        cost[j] += 1
        if d[j]==k:
            ans = min(ans, cost[j])
print(ans)