The only difference between the easy and the hard versions is constraints.A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.In one move you can take any subsequence $$$t$$$ of the given string and add it to the set $$$S$$$. The set $$$S$$$ can't contain duplicates. This move costs $$$n - |t|$$$, where $$$|t|$$$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).Your task is to find out the minimum possible total cost to obtain a set $$$S$$$ of size $$$k$$$ or report that it is impossible to do so.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 100$$$) — the length of the string and the size of the set, correspondingly. The second line of the input contains a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print one integer — if it is impossible to obtain the set $$$S$$$ of size $$$k$$$, print -1. Otherwise, print the minimum possible total cost to do it.

NoteIn the first example we can generate $$$S$$$ = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in $$$S$$$ is $$$0$$$ and the cost of the others is $$$1$$$. So the total cost of $$$S$$$ is $$$4$$$.

from collections import defaultdict
def solve(s, k):
    dp = defaultdict(int)
    dp[(-1,-1)] = 1
    n = len(s)
    last = {}

    for i in range(n):
        dp[(i, -1)] = 1
        for j in range(i+1):
            # ways choose this one + ways not choosing this one
            dp[(i,j)] = dp[(i-1,j-1)] + dp[(i-1, j)]
            # remove duplicates by removing the amout we get when using the last apperance of curr chr
            if s[i] in last:
                dp[(i, j)] -= dp[(last[s[i]]-1, j-1)]

        last[s[i]] = i

    cost = 0
    for i in reversed(range(-1, n)):
        cost += min(dp[(n-1,i)], k) * (n-1 -i)
        k -= dp[(n-1, i)]

        if k <= 0:
            return cost
    return -1

n, k = list(map(int, input().split()))
s = input()
print(solve(s, k))

[n, k] = [int(i) for i in input().split()]
s = input()
cntsz = [0 for i in range(105)]
dp = [[0 for i in range(105)] for j in range(105)]
lst = [0 for i in range(105)]
prv = [0 for i in range(26)]
n = len(s)
s = '%' + s
for i in range(n + 1):
  dp[i][0]=1
for i in range(1, n + 1):
	lst[i] = prv[ord(s[i])-ord('a')]
	prv[ord(s[i]) - ord('a')] = i
for sz in range(1, n + 1):
	for i in range(1, n + 1):
		dp[i][sz] += dp[i - 1][sz]
		dp[i][sz] += dp[i - 1][sz - 1]
		if lst[i] != 0:
			 dp[i][sz] -= dp[lst[i]-1][sz-1]
for sz in range(1, n + 1):
	for i in range(1, n + 1):
		cntsz[sz] += dp[i][sz]
		cntsz[sz] -= dp[i - 1][sz]
cntsz[0] += 1
done = 0
ans = 0
for i in range(n, -1, -1):
    if done + cntsz[i] >= k:
       ans += (n - i) * (k - done)
       done = k
       break
    done += cntsz[i]
    ans += cntsz[i] * (n - i)
if done < k:
    print(-1)
else:
    print(ans)

from sys import stdin, stdout, exit

def price():
    n,k = map(int, stdin.readline().split())
    s = stdin.readline().strip()

    todo = [s]
    ans = 0
    found = {s:True}
    k -= 1
    while todo and k > 0:
        nexts = []
    #    print(todo)
        for wd in todo:
            for i in range(len(wd)):
                candidate = wd[:i] + wd[i+1:]
    #            print(candidate)
                if candidate not in found:
                    nexts.append(candidate)
                    found[candidate] = True
                    ans += n - len(candidate)
                    k-=1
                    if k == 0:
                        return ans
        todo = nexts
    if k == 0:
        return ans
    return -1

print(price())

n, d = map(int,input().split())
s = input()
t = [[-1 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
	for j in range(i, n + 1):
		if j == i:
			t[i][j] = 1
		else:
			t[i][j] = 0
jes = [0] * 300
for i in range(1, n + 1):
	jes[ord(s[i - 1])] = 1
	t[i][1] = sum(jes)
for j in range(2, n + 1):
	ind = [-1] * 300
	ind[ord(s[j - 1])] = j - 1
	#obliczamy t[j + 1][j], t[j + 2][j], ...
	for i in range(j + 1, n + 1):
		if ind[ord(s[i - 1])] == -1:
			t[i][j] = t[i - 1][j] + t[i-1][j-1]
		else:
			t[i][j] = t[i - 1][j] + t[i - 1][j - 1] - t[ind[ord(s[i-1])]][j - 1]
		ind[ord(s[i - 1])] = i - 1
#t[n][1], t[n][2], ..., t[n][n]
rozne = [t[n][i] for i in range(1, n + 1)]
rozne.reverse()
roz = rozne + [1]
dupa = 0
wyn = 0
for i in range(n + 1):
	if dupa < d:
		k = min(roz[i], (d-dupa))
		dupa += k
		wyn += k * i
	else:
		break
if dupa >= d:
	print(wyn)
else:
	print(-1)

N, K = map(int, input().split())
pre = [input()]
ans = 0
k = 1
f = 0
while True:
    if k >= K:
        print(ans)
        break
    if len(pre) == 0:
        print(-1)
        break

    post = []
    for s in pre:
        for i in range(len(s)):
            t = s[:i] + s[i+1:]
            if t not in post:
                k += 1
                post.append(t)
                ans += N - len(t)

                if k >= K:
                    print(ans)
                    f = 1
                    break
        if f:
            break
    if f:
        break
    pre = post

import queue

def solve(s,n,k):
	q = queue.Queue()
	q.put(s)
	mapa = {}
	mapa[s] = True
	while (not q.empty() and len(mapa) < k):
		u = q.get()
		for i in range(len(u)):
			temp = u[0:i:1] + u[i+1:len(u):1]
			if temp not in mapa:
				mapa[temp] = True
				q.put(temp)
				if len(mapa) == k:
					break
	if len(mapa) == k:
		ans = k*n
		for i in mapa:
			ans -= len(i)
		return ans
	return -1

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

if __name__ == '__main__':
	main()

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

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

import random
import collections
import math
import itertools
import bisect

def real_main():
    n, k = read_int_array()
    ans = 0
    ssize = 1
    buckets = [dict() for _ in range(n+1)]
    buckets[n][read()] = 0
    max_bucket = n
    while ssize < k:
        if not max_bucket:
            print(-1)
            return
        for s, i in buckets[max_bucket].items():
            for i in range(i, len(s)):
                new_s = s[:i] + s[i+1:]
                if new_s not in buckets[max_bucket - 1]:
                    buckets[max_bucket - 1][new_s] = 0
                    ans += n - max_bucket + 1
                    ssize += 1

                    i += 1
                    while i < len(s) and s[i-1] == s[i]:
                        i += 1
                    buckets[max_bucket][s] = i
                    break
            else:
                buckets[max_bucket].pop(s)
            break
        else:
            max_bucket -= 1
    print(ans)

def solve():
    pass

def main():
    if False and 'PYCHARM_HOSTED' in os.environ:
        main_pycharm()
    else:
        real_main()

from copy import deepcopy
def main_pycharm():
    solution = solve

    test_inputs = None
    test_outputs = None
    judge = None
    slow_solution = None
    if solution is not None:
        if test_outputs is not None:
            test_with_answers(solution, test_inputs, test_outputs)
        if judge is not None:
            test_with_judge(solution, test_inputs, judge)
        if slow_solution is not None:
            test_with_slow_solution(solution, test_inputs, slow_solution)

def test_with_answers(solution, inputs, answers):
    total, wrong = 0, 0
    for args, test_ans in zip(inputs, answers):
        ans = solution(*deepcopy(args))
        if ans != test_ans:
            print('WRONG! ans=%s, test_ans=%s, args=%s' % (ans, test_ans, args))
            wrong += 1
        else:
            print('GOOD')
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))

def test_with_judge(solution, inputs_gen, judge):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))
        if not judge(deepcopy(ans), *deepcopy(args)):
            print('WRONG! ans=%s, args=%s' % (ans, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))

def test_with_slow_solution(solution, inputs_gen, solution_slow):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))
        slow = solution_slow(*deepcopy(args))
        if ans != slow:
            print('WRONG! ans=%s, slow=%s, args=%s' % (ans, slow, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))

def generate_nums(n, min, max, check_if_good=None):
    while True:
        nums = [random.randint(min, max) for _ in range(n)]
        if check_if_good is None or check_if_good(nums):
            return nums

# This mergesort can be like 7 times faster than build in sort
# (for stupid reasons)
def mergesort(A, key=lambda x: x, reverse=False):
    C = A
    A = list(range(len(A)))
    B = list(A)

    n = len(A)
    for i in range(0, n - 1, 2):
        if key(C[A[i]]) > key(C[A[i ^ 1]]):
            A[i], A[i ^ 1] = A[i ^ 1], A[i]

    width = 2
    while width < n:
        for i in range(0, n, 2 * width):
            R1, R2 = min(i + width, n), min(i + 2 * width, n)
            j, k = R1, i
            while i < R1 and j < R2:
                if key(C[A[i]]) > key(C[A[j]]):
                    B[k] = A[j]
                    j += 1
                else:
                    B[k] = A[i]
                    i += 1
                k += 1
            while i < R1:
                B[k] = A[i]
                k += 1
                i += 1
            while k < R2:
                B[k] = A[k]
                k += 1
        A, B = B, A
        width *= 2

    if reverse:
        A.reverse()
    return A

def mergesort_simple(A, reverse=False):
    C = A
    A = list(range(len(A)))
    B = list(A)

    n = len(A)
    for i in range(0, n - 1, 2):
        if C[A[i]] > C[A[i ^ 1]]:
            A[i], A[i ^ 1] = A[i ^ 1], A[i]

    width = 2
    while width < n:
        for i in range(0, n, 2 * width):
            R1, R2 = min(i + width, n), min(i + 2 * width, n)
            j, k = R1, i
            while i < R1 and j < R2:
                if C[A[i]] > C[A[j]]:
                    B[k] = A[j]
                    j += 1
                else:
                    B[k] = A[i]
                    i += 1
                k += 1
            while i < R1:
                B[k] = A[i]
                k += 1
                i += 1
            while k < R2:
                B[k] = A[k]
                k += 1
        A, B = B, A
        width *= 2

    if reverse:
        A.reverse()
    return A

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

def read():
    return input()

def read_int():
    return int(input())

def read_array(sep=None, maxsplit=-1):
    return input().split(sep, maxsplit)

def read_int_array():
    return [int(a) for a in read_array()]

# endregion

if __name__ == "__main__":
    main()

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

# ------------------------------

def c(chr): return ord(chr)-ord('a')

def main():
    n, k = RL()
    s = input()

    dp = [[0]*(n+1) for i in range(n+1)]
    rec = [-1]*26
    pre = [-1]*n

    for i in range(n+1):
        dp[i][0] = 1

    for i in range(n):
        now = c(s[i])
        pre[i] = rec[now]
        rec[now] = i

    for i in range(1, n+1):
        for j in range(1, i+1):
            # if j>i: break

            dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
            # if i == 6 and j == 1: print(dp[i-1][j], dp[i-1][j-1])
            if pre[i-1]!=-1:
                # if i==5 and j==4: print(pre[i-1], '+++')
                # if i==6 and j==1: print(pre[i-1], dp[pre[i-1]][j], dp[i][j])
                dp[i][j] -= dp[pre[i-1]][j-1]

    res = 0
    for j in range(n, -1, -1):
        if k:
            num = min(k, dp[-1][j])
            k-=num
            res += (n-j)*num

    # for i in dp: print(i)
    print(res if k==0 else -1)

if __name__ == "__main__":
    main()

iarr = list(map(int,input().split()))
n = iarr[0]
k = iarr[1]
s = input()
arr = []
arr.append(s)
ans = 0
ii = 0
flagg=0
while True:
	#print(arr)
	if flagg==1:
		#print("Hi")
		break
	if arr[ii]=="":
		break;
		#print("BYE")
	l = len(arr[ii])
	curcost = n-l+1
	for i in range(l):
		ss = arr[ii][:i] + arr[ii][i+1:]
		ll = len(arr)
		flag = True
		for j in range(ll):
			flag = flag and (ss!=arr[j])
		if len(arr)==k:
			flagg=1
			break

		if flag:
			arr.append(ss)
			ans+=curcost
	ii+=1
if len(arr)!=k:
	print(-1)
else:
	print(ans)

import fileinput
def D(a):print(a)
def S(s,I):return int(s.split(" ")[I])
def dyn(u,r):
    global N
    global X
    global dp
    if(u<0):return 0
    if(r==0):return 1
    if(u>=N):return 0
    if(dp[u][r]!=-1):return dp[u][r];
    v=0
    for i in range(26):
        v+=dyn(X[u][i]+1,r-1)
    dp[u][r]=v
    return v
def main():
    z=0
    global N
    global X
    global dp
    K=0
    for l in fileinput.input():
        z+=1
        if(z<2):
            N=S(l,0)
            K=S(l,1)
            continue
        X=[0]*(N+1)
        X[N]=[-666]*26
        for i in xrange(N-1,-1,-1):
            X[i]=[-1]*26
            for j in range(26):X[i][j]=X[i+1][j]
            X[i][ord(l[i])-97]=i
        dp=[0]*N
        for i in range(N):
            dp[i]=[-1]*(N+1)
    o=0
    for i in xrange(N,-1,-1):
        a=dyn(0,i)
        if(a<=K):
            o+=(N-i)*a
            K-=a
        else:
            o+=(N-i)*K
            K=0
    if(K!=0):D(-1)
    else: D(o)
main()

line1 = input().split(' ')
n = int(line1[0])
k = int(line1[1])
s = list(input())

dp = [101*[0] for i in range(101)]
last = 26*[-1]

for i in range(n+1):
    dp[0][i] = 1

for l in range(1, n+1):
    dp[l][0] = 0
    for c in range(26):
        last[c] = -1
    for i in range(1, n+1):
        dp[l][i] = dp[l-1][i-1] + dp[l][i-1]
        if last[ord(s[i-1])-ord('a')] != -1:
            dp[l][i] -= dp[l-1][last[ord(s[i-1])-ord('a')]-1]
        last[ord(s[i-1])-ord('a')] = i

i = 0
res = 0
while i <= n and k >= 0:
    c = min(k, dp[n-i][n])
    k -= c
    res += c * i
    i += 1
if k > 0:
    print(-1)
else:
    print(res)

n, k = map(int, input().split())
s = input()
a = set()
k -= 1
q = [s]
i = 0
ans = 0
while i < len(q) and k > 0:
    for j in range(len(q[i])):
        new = q[i][:j] + q[i][j + 1:]
        if new not in a:
            a.add(new)
            q.append(new)
            ans += n - len(q[i]) + 1
            k -= 1
            if k == 0:
                print(ans)
                exit()
    i += 1
if k == 0:
    print(ans)
else:
    print(-1)

# https://codeforces.com/contest/1183/problem/E

def solve(n, k, s):
    total_length = 0
    queue = [s]
    ss = set()

    while queue and len(ss) < k:
        s = queue.pop(0)
        if s not in ss:
            ss.add(s)
            total_length += len(s)
            if len(ss) < k:
                for i in range(len(s)):
                    temp = s[:i] + s[i + 1:]
                    if temp not in ss:
                        queue.append(temp)

    if len(ss) < k:
        return -1

    return n * k - total_length

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

s = input()

print(solve(n, k, s))

n, k = map(int, input().split(' '))
s = input()
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
for l in range(0, n):
    for i in range(l, n + 1):
        used = [False] * 26
        for j in range(i + 1, n + 1):
            ch = ord(s[j - 1]) - ord('a')
            if not used[ch]:
                dp[l + 1][j] += dp[l][i]
                used[ch] = True
total = 0
for l in range(n, -1, -1):
    sums = sum(dp[l])
    if sums >= k:
        total += (n - l) * k
        k = 0
        break
    total += (n - l) * sums
    k -= sums
if k > 0:
    total = -1
print(total)

import sys

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

lt = [s]
count = 0
flag = False
result = 0

while lt:
    cur_s = lt[0]
    lt.pop(0)
    result += len(s) - len(cur_s)
    count += 1
    if count >= k:
        break

    for i in range(0, len(cur_s)):
        new_s = cur_s[0: i] + cur_s[i + 1: ]
        if new_s not in lt:
            lt.append(new_s)

if count < k:
    sys.stdout.write(str(-1) + '\n')
else:
    sys.stdout.write(str(result) + '\n')

N,K=map(int,input().split())
S=input()
dp=[[0]*110 for i in range(110)]
lst=[[0]*110 for i in range(110)]
for i in range(N+1):
    dp[i][0]=1
for k in range(26):
    lst[0][k]=-1
for i in range(N):
    num=ord(S[i])-ord('a')
    for k in range(26):
        lst[i+1][k]=lst[i][k]
    lst[i+1][num]=i

for i in range(N):
    num=ord(S[i])-ord('a')
    for k in range(1,N+1):
        dp[i+1][k]=dp[i][k]+dp[i][k-1]
        if lst[i][num]!=-1:
            dp[i+1][k]-=dp[lst[i][num]][k-1]

rem=K
ans=0
for i in range(0,N+1):
    k=N-i

    if dp[N][k]>=rem:
        ans+=rem*(N-k)
        rem=0
    else:
        ans+=dp[N][k]*(N-k)
        rem-=dp[N][k]

if rem>0:
    print(-1)
else:
    print(ans)

# @author

import sys

class ESubsequencesEasyVersion:
    def solve(self):
        n, k = [int(_) for _ in input().split()]
        s = input()
        dp = [[0] * (n + 1) for _ in range(n + 1)]
        dp[0][0] = 1
        last = {key : -1 for key in (chr(x) for x in range(ord('a'), ord('z') + 1))}
        for i in range(1, n + 1):
            dp[i][0] = 1
            for j in range(1, i + 1):
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] - (dp[last[s[i - 1]]][j - 1] if last[s[i - 1]] != -1 else 0)
            last[s[i - 1]] = i - 1

        ans = 0
        tot = 0
        for sz in range(n, -1, -1):
            ans += min(k - tot, dp[n][sz]) * (n - sz)
            tot = min(k, tot + dp[n][sz])
            if tot == k:
                break

        if tot >= k:
            print(ans)
        else:
            print(-1)

solver = ESubsequencesEasyVersion()
input = sys.stdin.readline

solver.solve()

from collections import deque
n, k = [int(x) for x in raw_input().split()]
s = str(raw_input())
q = deque([s])

S = set()

cost = 0
success = False
while len(q) != 0:
    s = q.popleft()
    if s not in S:
        S.add(s)
        cost += n-len(s)
        if len(S) != k:
            for i in range(len(s)):
                q.append(s[0:i]+s[i+1:])
        else:
            success = True
            print(cost)
            break
if not success:
    print(-1)

import sys
input = sys.stdin.readline

n,W=map(int,input().split())
s=input().strip()

NEXTLIST=[[n]*26 for i in range(n+1)]

for i in range(n-1,-1,-1):
    for j in range(26):
        NEXTLIST[i][j]=NEXTLIST[i+1][j]
    NEXTLIST[i][ord(s[i])-97]=i

DP=[[0]*(n+1) for i in range(n+1)]

DP[0][0]=1

for i in range(n):
    for j in range(26):
        if NEXTLIST[i][j]!=n:
            for k in range(n):
                DP[NEXTLIST[i][j]+1][k+1]+=DP[i][k]

#print(DP)

HLIST=[0]*(n+1)

for i in range(n+1):
    for j in range(n+1):
        HLIST[j]+=DP[i][j]

#print(HLIST)

ANS=0
for i in range(n,-1,-1):
    #print(i,W)
    if W>HLIST[i]:
        ANS+=(n-i)*HLIST[i]
        W-=HLIST[i]
    else:
        ANS+=W*(n-i)
        print(ANS)
        sys.exit()

else:
    print(-1)

n,k=map(int,input().split())
r=set()
r1=set()
a=input()
queue=[a]
cost=0
co=0
r1.add(a)
while queue:
    ref=queue.pop(0)
    if(ref not in r):
       r.add(ref)
       cost+=(n-len(ref))
       co+=1
    if(co==k):
       break
    for i in range(len(ref)):
       y=ref[:i]+ref[i+1:]
       if(y not in r1):
           queue.append(y)
           r1.add(y)
if(len(r)<k):
    print(-1)
    exit(0)
print(cost)

from sys import stdout, stdin

n, kk = map(int, stdin.readline().split())
s = stdin.readline().strip()
s += "$"
n = n+1

dp = [[0 for i in range(n)] for j in range(n)]
p = 10**15+5
for i in range(n):
    dp[i][0] = 1
for end in range(n):
    for length in range(1, n):
        seen = []
        ans = 0
        for k in range(end-1, -1, -1):
            if s[k] not in seen:
                seen.append(s[k])
                ans += dp[k][length-1]
                ans %= p
        dp[end][length] = ans

totals = [dp[n-1][length] for length in range(n)]
#print(totals)

ans = 0
idx = n-1
while idx >= 0 and kk > 0:
    ans += min(totals[idx], kk)*(n-1-idx)
    kk -= totals[idx]
    idx -= 1

if kk <= 0:
    stdout.write(str(ans) +"\n")
else:
    print(-1)

n, kk = map(int, input().split())
s = '@'+input()
dp = [[0] * (n+1) for i in range(n+1)]
dp[0][0] = 1
for i in range(1, n+1):
    for j in range(i, n+1):
        tag = [True]*26
        for k in range(j, n+1):
            idx = ord(s[k])-ord('a')
            if tag[idx]:
                dp[i][k] += dp[i-1][j-1]
                tag[idx] = False
ans = 0
# print(dp)
for i in range(n, -1, -1):
    # print(ans,k,i)
    tmp = sum(dp[i])
    if kk > tmp:
        kk -= tmp
        ans += (n-i)*tmp
    else:
        ans += kk*(n-i)
        kk = 0
        break
if kk > 0:
    ans = -1
print(ans)

def sol(b):
    c=[]
    for i in range(len(b)):
        c.append(b[:i]+b[i+1:])
    return c
s=set()
n,k=map(int,input().split())
st=input()
la=n
p=[st]
p=set(p)
while la>0:
    s=s.union(p)
    r=set()
    fl=0
    for i in p:
        c=sol(i)
        la=len(c[0])
        r=r.union(set(c))
        if len(s)+len(r)>=k:
            fl=1
            break
    p=r
    if fl:
        break

ans=0
s=s.union(p)
if len(s)<k:
    exit(print(-1))
else:
    p=sorted(list(s),reverse=True,key=len)
    for i in range(k):
        ans+=n-len(p[i])
    print(ans)

n,k = tuple([int(x) for x in input().split()])
s=input()
q = []
nv = ""
st = []
st.append(s)
ans = 0
q.append(s)
while q!=[] and len(st)<k:
    v = q.pop(0)
    for i in range(len(v)):
        nv = v
        nv = nv[:i]+nv[i+1:]
        if nv not in st and len(st)+1<=k:
            q.append(nv)
            st.append(nv)
            ans += n - len(nv)

if len(st)<k:
    print(-1)
else:
    print(ans)

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

def main():
    n, K = map(int, input().split())
    s = str(input())

    next = [[10**18]*26 for _ in range(n+1)]

    for i in reversed(range(n)):
        for j in range(26):
            next[i][j] = next[i+1][j]
            if s[i] == chr(j+ord('a')):
                next[i][j] = i
    #print(next)

    dp = [[0]*(n+1) for i in range(n+1)]
    dp[0][0] = 1
    for i in range(n):
        for j in range(n+1):
            #dp[i+1][j] += dp[i][j]
            for k in range(26):
                if next[i][k] >= n:
                    continue
                else:
                    if j+1 <= n:
                        dp[next[i][k]+1][j+1] += dp[i][j]
    #print(dp)
    d = {}
    V = [0]*(n+1)
    for i in range(n+1):
        for j in range(n+1):
            V[j] += dp[i][j]
    V.reverse()
    #print(V)
    ans = 0
    for i, v in enumerate(V):
        if v >= K:
            ans += K*i
            break
        else:
            ans += v*i
            K -= v
    else:
        print(-1)
        exit()
    print(ans)

if __name__ == '__main__':
    main()

n, k = map(int, input().split())
targets = [input()]
ans = 0
cur = 1
depth = 0

if cur >= k:
    print(ans)
    exit()

while depth <= n:
    depth += 1
    next_target = []
    for target in targets:
        for i in range(len(target)):
            check = target[:i] + target[i+1:]
            if check in next_target:
                continue
            next_target.append(target[:i] + target[i+1:])
            ans += depth
            cur += 1
            if cur >= k:
                print(ans)
                exit()
    targets = next_target
print(-1)

n, k = map(int, raw_input().split())
s = raw_input()

r = 0
si = {s}
k -= 1

for d in range(1, n+1):
    si = {t[:i]+t[i+1:] for i in range(n-d+1) for t in si}
    ni = len(si)
    if ni < k:
        r += ni * d
        k -= ni
    else:
        r += k * d
        k = 0
        break

print(-1 if k > 0 else r)

if __name__ == '__main__':
    n, k = map(int, input().split())
    aa = list(input())
    st = {"".join(aa)}
    arr = [aa]
    w = 0
    c = 0
    cst = 0
    while len(arr) < k and w < len(arr):
        wrd = arr[w][:c] + arr[w][c + 1:]
        wrds = "".join(wrd)
        if wrds not in st:
            st.add(wrds)
            arr.append(wrd)
            cst += n - len(wrd)

        c += 1
        if c >= len(arr[w]):
            c = 0
            w += 1

    if len(arr) < k:
        print(-1)
    else:
        print(cst)

import sys
from queue import Queue

sys.setrecursionlimit(10000)

n, k = map(int, input().split())
s = input().strip()
q = Queue()
q.put(s)
res = {s}

while not q.empty():
    if len(res) == k:
        break
    string = q.get()
    for i in range(len(string)):
        new_string = string[:i] + string[i + 1:]
        if new_string not in res:
            res.add(new_string)
            q.put(new_string)
            if len(res) == k:
                break

if len(res) != k:
    print(-1)
    exit()
print(n * k - sum(len(string) for string in res))

S = set()
custo = 0
generated = []
def generate(ln, k):
    for st in list(generated[ln]):
        for i in xrange(len(st)):
            to_add = st[:i] + st[i+1:]
            generated[ln-1].add(to_add)
            S.add(to_add)
            if len(S) == k: return

n, k = map(int, raw_input().split())
s = raw_input()
S.add(s)
for i in xrange(n+1): generated.append(set())
generated[0].add('')
generated[-1].add(s)
if (pow(2, n) < k): print -1
elif (k == 1): print 0
else:
    for l in xrange(n, 0, -1):
        generate(l, k)
        if len(S) == k: break

    if len(S) < k: print -1
    else:
        generated = list(S)
        for i in xrange(len(S)): custo += (n - len(generated[i]))
        print custo

import sys

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

lt = [s]
count = 0
flag = False
result = 0

while lt:
    cur_s = lt[0]
    lt.pop(0)
    result += len(s) - len(cur_s)
    count += 1
    if count >= k:
        break

    for i in range(0, len(cur_s)):
        new_s = cur_s[0: i] + cur_s[i + 1: ]
        if new_s not in lt:
            lt.append(new_s)

if count < k:
    sys.stdout.write(str(-1) + '\n')
else:
    sys.stdout.write(str(result) + '\n')

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'
#cost = 233

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = B[0:k]
        cost = 0
        for x in B:
            cost += n-len(x)
        return cost

master = []
B = {s}
A = set()
for z in range(len(s)):
    if len(master) >= k:
        break
    for x in B:
        A.update(list(rSubset(x, len(x)-1)))
        if len(A) > k:
            A = list(A)
            A.sort(key=len)
            break
    master += B
    B=A
    A=set()
master.append('')
print(test(master))

"""
list of sets = [{s}]
while it's not enough:
    new set = set()
    for sigma in listofsets[-1]:
        newset.update(rsubset(sigma, len(sigma) - 1))
    listofsets.append(new set)

you can do the rest

queue = however you make aqueue in python
aset = set()

queue add s
aset add s

while len(aset) < k:
    astring = queue...remove()
    for eachstring in rsbubset(astring poop):
        if eachstring not in aset:
            aset add eachstring
            queue add eachstring
            if len(aset) == k:
                break break
"""

import queue

def solve(s,n,k):
	q = queue.Queue()
	q.put(s)
	mapa = {}
	mapa[s] = True
	while (not q.empty() and len(mapa) < k):
		u = q.get()
		for i in range(len(u)):
			temp = u[0:i:1] + u[i+1:len(u):1]
			if temp not in mapa:
				mapa[temp] = True
				q.put(temp)
				if len(mapa) == k:
					break
	if len(mapa) == k:
		ans = k*n
		for i in mapa:
			ans -= len(i)
		return ans
	return -1

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

if __name__ == '__main__':
	main()

import sys
input = sys.stdin.readline
import bisect
n,k=map(int,input().split())
s=input()
Next=[[float("inf")]*(26) for _ in range(n+1)]
for i in reversed(range(n)):
  for j in range(26):
    Next[i][j]=Next[i+1][j]
  Next[i][ord(s[i])-97]=i
DP=[[0]*(n+1) for _ in range(n+1)]
DP[0][0]=1
for i in range(n):
  for j in range(26):
    nxt=Next[i][j]
    for l in range(n):
      if nxt<float("inf"):
        DP[nxt+1][l+1]+=DP[i][l]
Ans=[0]*(n+1)
for i in range(n+1):
  for j in range(n+1):
    Ans[n-j]+=DP[i][j]
Ans2=[0]
for i in range(n+1):
  Ans2.append(Ans2[-1]+Ans[i])
if Ans2[-1]<k:
  print(-1)
else:
  ind=bisect.bisect_left(Ans2,k)
  ans,num=0,0
  for i in range(ind-1):
    ans+=i*Ans[i]
    num+=Ans[i]
  ans+=(ind-1)*(k-num)
  print(ans)

n, tt = map(int, input().split())
s = input()

dp = [[0]*(n + 1) for i in range(n+1)]

for c in range(n+1):
	dp[0][c] = 1

last = [-1]*26

for c in range(1, n + 1):
	k = ord(s[c-1]) - ord('a')
	for r in range(1, n+1):
		dp[r][c] = dp[r][c-1] + dp[r-1][c-1]
	if last[k] == -1:
		last[k] = c - 1
		continue
	else:
		p = last[k]
		for r in range(1, n+1):
			dp[r][c] = dp[r][c] - dp[r-1][p]
		last[k] = c-1

su, ans, t = 0, 0, 0
for r in range(n+1):
	su = su + dp[r][n]
if su < tt:
	ans = -1
else:
	for i in range(n, -1, -1):
		r = min(tt, dp[i][n])
		ans += t*r
		tt -= r
		t += 1

print(ans)

def check_word(word_list, word_need):
    unique = []
    for i in range(len(word_list)):
        # Pick each word in the list
        if word_need == 0:
            break
        for j in range(len(word_list[i])):
            if word_need == 0:
                break
            # Check word without 1 char is in unique
            new_word = word_list[i][:j]+word_list[i][j+1:]
            if new_word not in unique:
                unique.append(new_word)
                word_need -= 1
    return unique

def check_all():
    cost_sum = 0
    cost_each = 1
    [raw_length, raw_size] = input().split()
    size = int(raw_size)
    words = input().split()
    size -= 1
    while size>0:
        if len(words[0]) == 0:
            return -1
        words = check_word(words, size)
        cost_sum += len(words)*cost_each
        cost_each += 1
        size -= len(words)
    return cost_sum

print(check_all())

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

# ------------------------------

def main():
    n, k = RL()
    s = input()
    q = deque()
    q.append(s)
    res = 0
    rec = set()
    rec.add(s)

    while q:
        now = q.popleft()
        res+=n-len(now)
        if len(rec)>=k: continue
        for i in range(len(now)):
            nex = now[:i]+now[i+1:]
            if nex in rec: continue
            rec.add(nex)
            if len(rec)<=k: q.append(nex)

    print(res if len(rec)>=k else -1)

if __name__ == "__main__":
    main()

n, k = map(int, input().split())
s = "$" + input()

cnt = [[0]*(n+1) for i in range(n+1)]

cnt[0][0] = 1

for l in range(1, n+1):
	for i in range(l, n+1):
		used = [False] * 26
		for j in range(i, n+1):
			x = ord(s[j]) - ord('a')
			if not used[x]:
				cnt[l][j] += cnt[l-1][i-1]
				used[x] = True

ans = 0
for l in range(n, -1, -1):
	s = sum(cnt[l])
	if s < k:
		ans += (n-l) * s
		k -= s
	else:
		ans += (n-l) * k
		k = 0
		break

if k > 0: ans = -1

print(ans)

n, k = map(int, input().split())
s = input()
a = set()
k -= 1
q = [s]
i = 0
ans = 0
while i < len(q) and k > 0:
    for j in range(len(q[i])):
        new = q[i][:j] + q[i][j + 1:]
        if new not in a:
            a.add(new)
            q.append(new)
            ans += n - len(q[i]) + 1
            k -= 1
            if k == 0:
                print(ans)
                exit()
    i += 1
if k == 0:
    print(ans)
else:
    print(-1)

n, k = map( int, raw_input().split() )
s = raw_input()

last = [ 0 for i in range( 0, 150 ) ]
sum = [ 0 for i in range( 0, 105 ) ]
dp = [ [ 0 for j in range( 0, 105 ) ] for i in range( 0, 105 ) ]
sum[ 0 ] = 1
dp[ 0 ][ 0 ] = 1

for i in range( 1, n + 1 ):
	for j in range( i, 0, -1 ):
		dp[ i ][ j ] = dp[ i ][ j ] + sum[ j - 1 ]
		sum[ j ] = sum[ j ] + dp[ i ][ j ]
	if last[ ord( s[ i - 1 ] ) ]:
		pos = last[ ord( s[ i - 1 ] ) ]
		for j in range( pos, 0, -1 ):
			sum[ j ] = sum[ j ] - dp[ pos ][ j ]
			dp[ pos ][ j ] = 0
	last[ ord( s[ i - 1 ] ) ] = i

ans = 0
for i in range( n, -1, -1 ):
	seq = min( k, sum[ i ] )
	k = k - seq
	ans = ans + seq * ( n - i )
if k:
	ans = -1
print ans

def super_solve(n, k, s):
	last = []
	for i in range (0, 256):
		last.append(0)
	dp = []
	for i in range (0, 105):
		tmp = []
		for j in range (0, 105):
			tmp.append(0)
		dp.append( tmp )

	now = []
	for i in range (0, 105):
		tmp = []
		for j in range (0, 105):
			tmp.append(0)
		now.append( tmp )

	dp[0][0] = 1
	now[0][0] = 1
	for i in range (1, n + 1):
		c = ord(s[i])
		for j in range (0, n + 1):
			dp[i][j] += dp[i-1][j]
		for j in range (1, n + 1):
			dp[i][j] += dp[i-1][j-1]
		if last[c] > 0:
			for j in range (1, n + 1):
				dp[i][j] -= dp[ last[c] - 1 ][j - 1]
		for j in range (0, n + 1):
			now[i][j] = dp[i][j] - dp[i-1][j]
		last[c] = i

	cost = 0
	baki = k
	j = n
	while( j >= 0 ):
		for i in range (0, n + 1):
			cur = now[i][j]
			my = min(baki, cur)
			cost += my * j
			baki -= my
		j -= 1

	ret = k * n - cost
	if baki > 0:
		ret = -1
	return ret

def main():
	line = input()
	line = line.split(' ')
	n = int(line[0])
	k = int(line[1])
	tmp = input()
	s = []
	s.append(0)
	for i in range (0, n):
		s.append( tmp[i] )
	ret = super_solve(n, k, s)
	print (ret)

if __name__== "__main__":
  main()

# NUMBER OF DISTINCT SUBSEQUENCES OF EVERY LENGTH K FOR 0<=K<=len(s)

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

pos=[-1]*26
lst=[]
for i in range(0,len(s)):
    pos[ord(s[i])-97]=i
    h=[]
    for j in range(26):
        h.append(pos[j])
    lst.append(h)

dp=[]
for i in range(n):
    h=[]
    for j in range(n+1):
        h.append(0)
    dp.append(h)

for i in range(n):
    dp[i][1]=1

for j in range(2,n+1):
    for i in range(1,n):
        for e in range(26):
            if(lst[i-1][e]!=-1):
                dp[i][j]=dp[i][j]+dp[lst[i-1][e]][j-1]

ans=0
for j in range(n,0,-1):
    c=0
    for e in range(26):
        if(lst[n-1][e]!=-1):
            c+=dp[lst[n-1][e]][j]
    if(k-c>=0):
        ans+=(c*(n-j))
        k-=c
    else:
        req=k
        ans+=(req*(n-j))
        k-=req
        break

if(k==1):
    ans+=n
    k-=1
if(k>0):
    print(-1)
else:
    print(ans)

"""

# TOTAL NUMBER OF DISTINCT SUBSEQUENCES IN A STRING

## APPROACH 1

MOD=1000000007

s=input()
n=len(s)

dp=[1] # for empty string ''
kk=dict()

for i in range(0,len(s)):
    term=(dp[-1]*2)%MOD
    if(kk.get(s[i])!=None):
        term=(term-dp[kk[s[i]]])%MOD
    kk[s[i]]=i
    dp.append(term)

print(dp[-1])

## APPROACH 2

MOD=1000000007

s=input()
n=len(s)

pos=[-1]*26

dp=[1] # for empty string ''

for i in range(0,len(s)):
    c=1
    for j in range(26):
        if(pos[j]!=-1):
            c=(c+dp[pos[j]+1])%MOD
    pos[ord(s[i])-97]=i
    dp.append(c)

ans=1
for i in range(0,26):
    if(pos[i]!=-1):
        ans=(ans+dp[pos[i]+1])%MOD

print(ans)

"""

import sys
from itertools import combinations
from functools import lru_cache
from string import ascii_lowercase

@lru_cache()
def e(n, l):
    return sum(d(n, l, x) for x in letters)

@lru_cache()
def d(n, l, c):
    if n < l:
        return 0
    if s[n - 1] != c:
        return d(n - 1, l, c)
    return e(n - 1, l - 1) if l > 1 else 1

def solve(s, k):
    n = len(s)
    cost = 0
    for l in range(n, 0, -1):
        cnt = e(n, l)
        if k > cnt:
            k -= cnt
            cost += cnt * (n - l)
        else:
            cost += k * (n - l)
            k = 0
            break
    if k > 1:
        return -1
    if k == 1:
        cost += n
        k = 0
    return cost

n, k = map(int, input().split())
s = input()
letters = set(s)
print(solve(s, k))

if __name__ == '__main__':
    n, k = map(int, input().split())
    aa = list(input())
    st = {"".join(aa)}
    arr = [aa]
    w = 0
    c = 0
    cst = 0
    while len(arr) < k and w < len(arr):
        wrd = arr[w][:c] + arr[w][c + 1:]
        wrds = "".join(wrd)
        if wrds not in st:
            st.add(wrds)
            arr.append(wrd)
            cst += n - len(wrd)

        c += 1
        if c >= len(arr[w]):
            c = 0
            w += 1

    if len(arr) < k:
        print(-1)
    else:
        print(cst)

from itertools import combinations

def main():
    n, k = map(int, input().split())
    s = input()
    lenf = len
    l_prev = {s}
    curS = 1
    cost = 0
    if k == 1:
        print(0)
        return
    for curlen in range(n - 1, -1, -1):
        l = set()
        for l_elem in l_prev:
            for v in combinations(l_elem, curlen):
                v = ''.join(v)
                if v in l:
                    continue
                l.add(v)
                curS += 1
                cost += n - curlen
                if curS == k:
                    print(cost)
                    return
        l_prev = l
    print(-1)

if __name__ == '__main__':
    main()

N,K=map(int,input().split())
S=input()
dp=[[0]*110 for i in range(110)]
lst=[[0]*110 for i in range(110)]
for i in range(N+1):
    dp[i][0]=1
for k in range(26):
    lst[0][k]=-1
for i in range(N):
    num=ord(S[i])-ord('a')
    for k in range(26):
        lst[i+1][k]=lst[i][k]
    lst[i+1][num]=i

for i in range(N):
    num=ord(S[i])-ord('a')
    for k in range(1,N+1):
        dp[i+1][k]=dp[i][k]+dp[i][k-1]
        if lst[i][num]!=-1:
            dp[i+1][k]-=dp[lst[i][num]][k-1]

rem=K
ans=0
for i in range(0,N+1):
    k=N-i

    if dp[N][k]>=rem:
        ans+=rem*(N-k)
        rem=0
    else:
        ans+=dp[N][k]*(N-k)
        rem-=dp[N][k]

if rem>0:
    print(-1)
else:
    print(ans)

# https://codeforces.com/contest/1183/problem/E

def solve(n, k, s):
    total_length = 0
    queue = [s]
    ss = set()

    while queue and len(ss) < k:
        s = queue.pop(0)
        if s not in ss:
            ss.add(s)
            total_length += len(s)
            if len(ss) < k:
                for i in range(len(s)):
                    temp = s[:i] + s[i + 1:]
                    if temp not in ss:
                        queue.append(temp)

    if len(ss) < k:
        return -1

    return n * k - total_length

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

s = input()

print(solve(n, k, s))

import collections, heapq, math, sys
from string import ascii_lowercase

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

d = {}
d[n - 1] = {}
curr = {}
for letter in ascii_lowercase:
    curr[letter] = n

for i in range(n - 1, -1, -1):
    d[i] = {}
    for letter in ascii_lowercase:
        d[i][letter] = curr[letter]
    curr[s[i]] = i

dp = [[0 for _ in range(n + 1)] for _ in range(n)]
for i in range(n - 1, -1, -1):
    dp[i][1] += 1
    for letter in ascii_lowercase:
        nxt = d[i][letter]
        if nxt == n:
            continue
        for j in range(2, n + 1):
            dp[i][j] += dp[nxt][j - 1]
z = collections.defaultdict(int)
z[0] = 1
for letter in ascii_lowercase:
    nxt = curr[letter]
    if nxt == n: continue
    for i in range(1, n + 1):
        z[i] += dp[nxt][i]

ret = 0
cnt = 0
# print(z)
for i in range(n, -1, -1):
    if z[i] > 0:
        added = min(z[i], k - cnt)
        ret += added * (n - i)
        cnt += added
        if cnt == k:
            break
if cnt == k:
    print(ret)
else:
    print(-1)

import queue

def solve(s,n,k):
	q = queue.Queue()
	q.put(s)
	mapa = {}
	mapa[s] = True
	while (not q.empty() and len(mapa) < k):
		u = q.get()
		for i in range(len(u)):
			temp = u[0:i:1] + u[i+1:len(u):1]
			if temp not in mapa:
				mapa[temp] = True
				q.put(temp)
				if len(mapa) == k:
					break
	if len(mapa) == k:
		ans = k*n
		for i in mapa:
			ans -= len(i)
		return ans
	return -1

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

if __name__ == '__main__':
	main()

n, k = input().split (' ')
n = int (n)
k = int (k)
s = input()
s = "-" + s
dp = [ [ 0 for i in range (110)] for j in range (110)]
added = [ [ 0 for i in range (110)] for j in range (110)]
lst = [0 for i in range (310)]
lstAdded = [0 for i in range (310)]
for i in range (0, 110):
    dp[0][i] = 1
vec = list()
st = set()
for i in range (1, n+1):
    st.add (s[i])
    dp[1][i] = len (st)
vec.append (1)
vec.append (dp[1][n])
for t in range (2, n+1):
    for i in range(310):
        lst[i] = 0
        lstAdded[i] = 0
    for i in range (1, n+1):
        dp[t][i] = dp[t-1][i-1] + dp[t][i-1] - lstAdded[ord(s[i])]
        #if (lst[ord(s[i])] > 0):
        #     dp[t][i] += dp[t-1][lst[ord(s[i])]-1]
        lstAdded[ord(s[i])] += dp[t][i] - dp[t][i-1]
        added[t][i] = dp[t][i] - dp[t][i-1]
        lst[ord(s[i])] = i
    vec.append (dp[t][n])
    # print (t, dp[t][n])

ans = 0
qnt = 0
while (k > 0 and len (vec)):
    now = vec.pop()
    #print (now, k, ans)
    use = min (k, now)
    k = k - use
    ans += qnt * use
    qnt+=1
if (k == 0):
    print (ans)
else:
    print (-1)

def func(n,k,s):
	x = [s]
	cost = 0
	while(len(x) < k):
		for string in x:
			l = len(string)
			for j in range(l):
				t = string[:j] + string[j+1:]
				if(t == "" and t in x):
					return -1
				if(t not in x):
					x.append(t)
					cost += n - len(t)
					if(len(x) >= k):
						return cost
	return cost
a = [int(i) for i in input().split()]
n = a[0]
k = a[1]
s = str(input())
print(func(n,k,s))

from collections import defaultdict
n,k=map(int,input().split())
s=input()
last=defaultdict(int)
dp=[[0 for i in range(n+1)]for j in range(n+1)]
dp[0][0]=1
dp[1][1]=1
dp[1][0]=1
last[s[0]]=1
for i in range(2,n+1):
    dp[i][0]=1
    #print(last[s[i-1]])
    for j in range(1,i+1):
        dp[i][j]=dp[i-1][j-1]+dp[i-1][j]
        #print(dp[i][j],i,j)
        if last[s[i-1]]>=1:
            ind=last[s[i-1]]
            dp[i][j]-=dp[ind-1][j-1]
            #print(dp[ind-1][j-1],"JJKJJK",dp[i][j])
    last[s[i-1]]=i
ans=0
for i in range(n,-1,-1):
    if k<=0:
        break
    c=min(dp[n][i],k)
    ans+=(n-i)*c
    k-=c
if k>0:
    ans=-1
print(ans)

line1 = input().split(' ')
n = int(line1[0])
k = int(line1[1])
s = list(input())

dp = [101*[0] for i in range(101)]
last = 26*[-1]

for i in range(n+1):
    dp[0][i] = 1

for l in range(1, n+1):
    dp[l][0] = 0
    for c in range(26):
        last[c] = -1
    for i in range(1, n+1):
        dp[l][i] = dp[l-1][i-1] + dp[l][i-1]
        if last[ord(s[i-1])-ord('a')] != -1:
            dp[l][i] -= dp[l-1][last[ord(s[i-1])-ord('a')]-1]
        last[ord(s[i-1])-ord('a')] = i

i = 0
res = 0
while i <= n and k >= 0:
    c = min(k, dp[n-i][n])
    k -= c
    res += c * i
    i += 1
if k > 0:
    print(-1)
else:
    print(res)

def f(s, k):
    n = len(s)
    q = [s]
    S = set()
    S.add(s)
    ans = 0

    while len(q) > 0 and k > 0:
        ss = q[0]
        k -= 1
        ans += n - len(ss)
        q.pop(0)
        for i in range(len(ss)):
            ns = ss[0:i] + ss[i+1:len(s)]
            if ns not in S:
                q.append(ns)
                S.add(ns)
    if k == 0:
        return ans
    return -1

def main():
    n, k = map(int, input().split())
    s = input()
    print(f(s, k))
    '''
    a = list(S)
    a.sort(key=lambda x: len(x), reverse=True)
    if len(a) < k:
        print(-1)
    else:
        ans = 0
        for i in range(k):
            ans += n - len(a[i])
        print(ans)
    '''

main()

n,setsize=list(map(int,input().split()))
s=input()
count = [[0 for j in range(n+1)] for i in range(n+1)]
for i in range(n):
	j = i-1
	while(j>=0):
		for k in range(1,n):
			count[i][k+1] += count[j][k]
		if(s[j]==s[i]):
			break
		j-=1
	if(j==-1):
		count[i][1]+=1
# print(count)
cost = 0
count[0][0]=1
for l in range(n,-1,-1):
	if(setsize==0):
		break
	ct = 0
	localcost = n - l
	for i in range(n):
		ct += count[i][l]
	minct = min(setsize,ct)
	setsize-=minct
	# print("for k=",setsize,"l=",l,";minct=",minct,";localcost=",localcost)
	cost += (minct*localcost)
if(setsize==0):
	print(cost)
else:
	print(-1)

def subsequences_of_length(s):
    n = len(s)

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    to_int = {}
    for i, char in enumerate(alphabet):
        to_int[char] = i

    next_i = [[n] * len(alphabet) for i in range(n + 1)]
    for i in reversed(range(n)):
        for j, char in enumerate(alphabet):
            next_i[i][j] = next_i[i+1][j]
        next_i[i][to_int[s[i]]] = i

    dp = [[0] * (n + 1) for i in range(n + 1)]
    dp[0][0] = 1
    for i in range(n):
        for k in range(n):
            for j in range(26):
                if next_i[i][j] >= n:
                    continue
                dp[k+1][next_i[i][j] + 1] += dp[k][i]

    ans = [sum(dp[i]) for i in range(n + 1)]
    return ans

n, k = map(int, input().split())
s = input()
ans_len = subsequences_of_length(s)

ans_cnt = 0
ans = 0
for length in reversed(range(len(ans_len))):
    cnt = ans_len[length]
    if ans_cnt + cnt <= k:
        ans_cnt += cnt
        ans += cnt * (n - length)
    else:
        ans += (k - ans_cnt) * (n - length)
        ans_cnt = k
if ans_cnt != k:
    print(-1)
else:
    print(ans)

from queue import Queue
stack = Queue()

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

k -= 1
a = set()
answer = 0

stack.put(list(s))

while not stack.empty():
	now = stack.get_nowait()
	new = now[:]
	can = []
	for i in range(len(now)):
		if k:
			new[i] = ''
			word = ''.join(new)
			if word not in a:
				a.add(word)
				answer += n - len(word)
				can.append(word)
				k -= 1

		new[i] = now[i]
	if k:
		for word in can:
			stack.put(list(word))

if k > 0:
	print(-1)
else:
	print(answer)

#!/usr/bin/python3.6

'''
        .__     .__                                _______   _______ _________
  ______|  |__  |__|  ____    ____ _______ _____   \   _  \  \   _  \\______  \
 /  ___/|  |  \ |  | /    \  /  _ \\_  __ \\__  \  /  /_\  \ /  /_\  \   /    /
 \___ \ |   Y  \|  ||   |  \(  <_> )|  | \/ / __ \_\  \_/   \\  \_/   \ /    /
/____  >|___|  /|__||___|  / \____/ |__|   (____  / \_____  / \_____  //____/
     \/      \/          \/                     \/        \/        \/

'''
# Run locally with python3.6 -O code.py to run in not debug mode. [ONLINE_JUDGE]
# rm ~/pipe2; mkfifo ~/pipe2 ; ./code.py < ~/pipe2 | ./interactive.py > ~/pipe2
# rm ~/pipe2; mkfifo ~/pipe2 ; ./code.py < ~/pipe2 | ./matcher.py > ~/pipe2

# one-way
# ./haha.py > input.txt ; ./code.py < input.txt

import sys

def eprint(*args, **kwargs):
    if __debug__:
        print(*args, file=sys.stderr, **kwargs)

def calculate_res(visit, n):
    return n*len(visit) - sum([len(x) for x in visit])

def traverse(s, k):
    _que = []
    visit = set([])

    _que.append(s)
    visit.add(s)
    if len(visit) == k:
        return calculate_res(visit, len(s))

    while len(_que) > 0:
        cur = _que.pop(0)
        for i in range(len(cur)):
            adj_s = cur[0:i] + cur[i+1:len(cur)]
            if adj_s not in visit:
                _que.append(adj_s)
                visit.add(adj_s)
                if len(visit) == k:
                    return calculate_res(visit, len(s))
    return -1

if __name__ == "__main__":
    n, k = map(int, input().split(' '))
    s = input()

    print(traverse(s, k))

def count_subsequences_of_length(s):
    """文字列sの部分列を長さごとに数え上げる
    例) s = aba
    考えられる部分列は "", "a", "b", "ab", "ba", "aa", "aba" なので ans = [1, 2, 3, 1]
    計算量: O(len(s)*len(s)*len(alphabet))
    """
    n = len(s)
    alphabet = list(set(list(s)))
    to_int = {}
    for i, char in enumerate(alphabet):
        to_int[char] = i

    next_i = [[n] * len(alphabet) for i in range(n + 1)]
    for i in reversed(range(n)):
        for j, char in enumerate(alphabet):
            next_i[i][j] = next_i[i+1][j]
        next_i[i][to_int[s[i]]] = i

    # dp[i][j] := j番目までの文字を見たときの、長さiの部分列の通り数
    # 初期値はdp[0][0] = 1 (空文字 "" に対応)
    dp = [[0] * (n + 1) for i in range(n + 1)]
    dp[0][0] = 1
    for j in range(n):
        for i in range(n):
            for k in range(len(alphabet)):
                if next_i[j][k] >= n:
                    continue
                # 配るDP
                dp[i+1][next_i[j][k] + 1] += dp[i][j]

    ans = [sum(dp[i]) for i in range(n + 1)]
    return ans

n, k = map(int, input().split())
s = input()
ans_len = count_subsequences_of_length(s)

ans_cnt = 0
ans = 0
for length in reversed(range(len(ans_len))):
    cnt = ans_len[length]
    if ans_cnt + cnt <= k:
        ans_cnt += cnt
        ans += cnt * (n - length)
    else:
        ans += (k - ans_cnt) * (n - length)
        ans_cnt = k
if ans_cnt != k:
    print(-1)
else:
    print(ans)

"""
n,k=map(int,input().split())
s=input()
dp=[0]*(n+1)
kk=dict()
global ct
ct=0
def rec(s):
    dp[len(s)]+=1
    global ct
    ct+=1
    if(ct>k+10):
        return
    if(len(s)==0):
        return
    for i in range(0,len(s)):
        st=s[:i]+s[i+1:]
        if(kk.get(st)==None):
            #dp[len(st)]+=1
            #print(st)
            kk[st]=1
            rec(st)
rec(s)
print(dp)

tot=0
for i in range(0,len(dp)):
    tot+=dp[i]
if(tot<k):
    print(-1)
else:
    sumu=0
    c=0
    for i in range(n,-1,-1):
        req=min(k-c,dp[i])
        c+=req
        sumu+=(req*(n-i))
        if(c>=k):
            break
    print(sumu)
"""

from collections import deque
n,k=map(int,input().split())
s=input()
dp=[0]*(n+1)
kk=dict()

ct=0

q=deque()
q.append(s)

while(q):
    r=q.popleft()
    dp[len(r)]+=1
    ct+=1

    if(ct>k+10):
        break

    if(len(r)>0):
        for i in range(0,len(r)):
            st=r[:i]+r[i+1:]
            if(kk.get(st)==None):
                kk[st]=1
                q.append(st)

tot=0
for i in range(0,len(dp)):
    tot+=dp[i]
if(tot<k):
    print(-1)
else:
    sumu=0
    c=0
    for i in range(n,-1,-1):
        req=min(k-c,dp[i])
        c+=req
        sumu+=(req*(n-i))
        if(c>=k):
            break
    print(sumu)

import sys
import math
from collections import defaultdict,deque
import heapq
n,k = map(int,sys.stdin.readline().split())
ss = sys.stdin.readline()[:-1]
dp = [[0 for _ in range(n+1)] for i in range(n+1)]
dp[n][1]=1
dp[n][0]=1
dic=defaultdict(list)
for i in range(n):
	dic[ss[i]].append(i+1)
#print(dic,'dic')
for i in range(n-1,0,-1):
	#vis=defaultdict(int)
	for j in range(1,n+1):
		s=0
		for x in range(i+1,n+1):
			s+=dp[x][j-1]
		z=-1
		cnt=0
		#print(ss[i-1])
		#print(dic[ss[i-1]])
		for y in dic[ss[i-1]]:
			cnt+=1
			if y==i:
				break
		sub=0
		if len(dic[ss[i-1]])>cnt:
			for q in range(cnt,len(dic[ss[i-1]])):
				sub+=dp[dic[ss[i-1]][q]][j]
				#print(dic[ss[i-1]][q],'row',j,'col',sub,'sub')
			#sub=dp[dic[ss[i-1]][cnt]][j]
		#print(cnt,'cnt',i,'i',j,'j',s,'sssss',sub,'sub',cnt,'cnt',dic[ss[i-1]])
		dp[i][j]+=s-sub
		#print(s,'s',sub,'sub')
'''for i in range(n+1):
	print(dp[i],'dp')'''
cost=0
for i in range(n,-1,-1):
	for j in range(n+1):
		#print(k,'k',i,'i',j,'j')
		if dp[j][i]<=k:
			cost+=(n-i)*dp[j][i]
			k-=dp[j][i]
		else:
			#print(n,'n',i,'i',k,'k')
			cost+=k*(n-i)
			k=0
			break
#print(cost,'cost',k,'k')
if k!=0:
	print(-1)
else:
	print(cost)

from sys import stdin

n, k = [int(i) for i in stdin.readline().strip().split()]
s = stdin.readline().strip()

def get_f(s):
    F = [len(s) * [0] for _ in range((len(s) + 1))]
    size = 0
    for index in range(len(s)):
        F[size][index] = 1
    F[1][0] = 1

    p = {s[0]: 0}
    for i in range(1, len(s)):
        for k in range(1, len(s) + 1):
            if k > i + 1:
                val = 0
            else:
                val = F[k][i - 1] + F[k - 1][i - 1]
                if s[i] in p:
                    # sic: if k - 1 == 0 then answer is always 1
                    # if k - 1 == 0:
                    #     print(i)
                    #     val -= 1
                    if p[s[i]] - 1 >= 0:
                        val -= F[k - 1][p[s[i]] - 1]
                    elif p[s[i]] == 0 and k - 1 == 0:
                        val -= 1
            F[k][i] = val
        p[s[i]] = i
    return F

_F = get_f(s)

# for sz in range(len(s) + 1):
#     for index in range(len(s)):
#         print(_F[sz][index], end=' ')
#     print()

def count(size, index = None):
    return _F[size][index or (len(s) - 1)]

# recursive solution with memoization
previous_letter_index = {}
found = {}
for index, letter in enumerate(s):
    if letter in found:
        previous_letter_index[(letter, index)] = found[letter]
    found[letter] = index

_subsequences = {}

def subsequences(size, index):
    """Get number of distinct subsequences of given size in sequence[0:index + 1] slice"""
    if (size, index) not in _subsequences:
        if size == 0:
            res = 1
        elif size > index + 1:
            res = 0
        else:
            res = subsequences(size, index - 1) + subsequences(size - 1, index - 1)
            letter = s[index]
            if (letter, index) in previous_letter_index:
                res -= subsequences(size - 1, previous_letter_index[(letter, index)] - 1)
        _subsequences[(size, index)] = res
    return _subsequences[(size, index)]

total_cost = 0
for size in range(len(s), -1, -1):
    if k == 0:
        break
    step_cost = n - size
    sequence_count = count(size, len(s) - 1)
    # print('size = ', size, 'count = ', sequence_count)
    if sequence_count > k:
        sequence_count = k
    total_cost += step_cost * sequence_count
    k -= sequence_count

if k == 0:
    print(total_cost)
else:
    print(-1)

# your code goes here
n,k=map(int,input().split())
s=input()
c=0
q=[s]
d=set()
ls=0
while q:
	p=q.pop(0)
	if p not in d:
		ls+=1
		c+=(n-len(p))
		if ls==k:
			break
		d.add(p)
		for i in range(len(p)):
			temp=p[:i]+p[i+1:]
			if temp not in d:
				q.append(temp)

if ls==k:
	print(c)
else:
	print(-1)

from collections import deque
n,m=map(int,input().split())
s=input()
d=deque([s])
ans=1
an=0
dd={}
while d and ans<m:
    # print(d)
    p=d.popleft()
    dd[p]=1
    k=len(p)
    for i in range(k):
        pp=p[:i] + p[i+1:]
        # print(pp,dd)
        if (pp not in dd):
            an+=(n-(k-1))
            ans+=1
            dd[pp]=1
            d.append(pp)
        if ans==m:
            print(an)
            exit()

    # print(d)
# print(an,ans)
if ans==m:
    print(an)
else:
    print(-1)

from sys import stdin

n, k = [int(i) for i in stdin.readline().strip().split()]
s = stdin.readline().strip()

class Subsequences:
    def __init__(self, sequence):
        self._seq = list(sequence)
        self._F = [len(sequence) * [0] for _ in range((len(sequence) + 1))]
        self._calc()

    def _calc(self):
        # iterative solution F[size][index] given number of distinct subsequences of given size
        # in slice [0: index + 1] of original sequence
        F = self._F
        size = 0
        for index in range(len(s)):
            F[size][index] = 1
        F[1][0] = 1

        p = {s[0]: 0}
        for i in range(1, len(s)):
            for k in range(1, len(s) + 1):
                if k > i + 1:
                    val = 0
                else:
                    val = F[k][i - 1] + F[k - 1][i - 1]
                    if s[i] in p:
                        val -= F[k - 1][p[s[i]] - 1]
                F[k][i] = val
            p[s[i]] = i

    def count(self, size, index=None):
        index = index or (len(self._seq) - 1)
        return self._F[size][index]

# recursive solution with memoization
previous_letter_index = {}
found = {}
for index, letter in enumerate(s):
    if letter in found:
        previous_letter_index[(letter, index)] = found[letter]
    found[letter] = index

_subsequences = {}

def subsequences(size, index):
    """Get number of distinct subsequences of given size in sequence[0:index + 1] slice"""
    if (size, index) not in _subsequences:
        if size == 0:
            res = 1
        elif size > index + 1:
            res = 0
        else:
            res = subsequences(size, index - 1) + subsequences(size - 1, index - 1)
            letter = s[index]
            if (letter, index) in previous_letter_index:
                res -= subsequences(size - 1, previous_letter_index[(letter, index)] - 1)
        _subsequences[(size, index)] = res
    return _subsequences[(size, index)]

ss = Subsequences(s)

total_cost = 0
for size in range(len(s), -1, -1):
    if k == 0:
        break
    step_cost = n - size
    sequence_count = subsequences(size, len(s) - 1)
    if sequence_count > k:
        sequence_count = k
    total_cost += step_cost * sequence_count
    k -= sequence_count

if k == 0:
    print(total_cost)
else:
    print(-1)

from collections import deque
n, k = [int(x) for x in raw_input().split()]
s = str(raw_input())
q = deque([s])

S = set()

cost = 0
success = False
while len(q) != 0:
    s = q.popleft()
    if s not in S:
        S.add(s)
        cost += n-len(s)
        if len(S) != k:
            for i in range(len(s)):
                q.append(s[0:i]+s[i+1:])
        else:
            success = True
            print(cost)
            break
if not success:
    print(-1)

n, k = map(int, input().split())
s = '{' + input()
dp = [[0] * (n + 1) for _ in range(n + 1)]

# dp
dp[0][0] = 1
oa = ord('a')
for i in range(1, n + 1):
    for j in range(1, n + 1):
        hold = [0] * 30
        for l in range(0, i): # Transition from dp[l][j - 1]
            let = ord(s[l]) - oa;
            # db(i); db(j); db(dp[i][j]); db(dp[l][j - 1]); db(hold[let]); dbln;
            dp[i][j] += dp[l][j - 1] - hold[let]

            hold[let] = dp[l][j - 1]

        # dblb("ret"); db(i); db(j); db(dp[i][j]); dbln;

# sum costs
tot = 0
for i in range(n, -1, -1):
    cost = n - i
    dpsum = 0
    hold = [0] * 30
    for j in range(0, n + 1):
        let = ord(s[j]) - oa
        dpsum += dp[j][i] - hold[let]
        hold[let] = dp[j][i]

    sub = min(k, dpsum)
    # print(f'i={i} dpsum={dpsum}')

    tot += sub * cost
    k -= sub

if k > 0:
    print(-1)
else:
    print(tot)

from __future__ import division, print_function

DEBUG = 0

import os, sys
from atexit import register
from io import BytesIO
import itertools

if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

if DEBUG:
    debug_print = print
else:
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
    sys.stdout = BytesIO()
    register(lambda: os.write(1, sys.stdout.getvalue()))

    input = lambda: sys.stdin.readline().rstrip('\r\n')
    debug_print = lambda *x, **y: None

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

def array_of(f, *dim):
    return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()

def main():
    from collections import defaultdict

    n, k = input_as_list()
    s = input()

    counts = [1]
    prev = []
    _set = set()
    for c in s:
        _set.add(c)
        prev.append(len(_set))
    counts.append(prev[-1])

    for depth in range(1, n):
        this = []
        _dict = defaultdict(int)

        for i, c in enumerate(s):
            if i < depth:
                v = 0
            else:
                v = this[i-1] + prev[i-1] - _dict[c]
                _dict[c] = prev[i-1]
            this.append(v)

        counts.append(this[-1])
        prev = this

    cost = 0
    count = 0
    cur_cost = 0
    while counts:
        v = counts.pop()
        if count + v >= k:
            cost += cur_cost * (k-count)
            print(cost)
            return
        else:
            count += v
            cost += cur_cost * v
            cur_cost += 1

    print(-1)

main()

import queue

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

def sol_e(line, set_size):
    unique_set = {line}
    cost = 0
    lines_queue = queue.Queue()
    lines_queue.put(line)
    cur_set_size = 1
    while cur_set_size < set_size:
        cur_line = lines_queue.get()
        for index in range(len(cur_line)):
            new_line = cur_line[:index]+cur_line[(index+1):]
            if new_line not in unique_set:
                unique_set.add(new_line)
                cost += len(line)-len(new_line)
                cur_set_size += 1
                lines_queue.put(new_line)
                if cur_set_size == set_size:
                    return cost
        if lines_queue.empty():
            return -1
    return cost

print(sol_e(s, k))

n,k=map(int,input().split())
r=set()
r1=set()
a=input()
queue=[a]
cost=0
co=0
r1.add(a)
while queue:
    ref=queue.pop(0)
    if(ref not in r):
       r.add(ref)
       cost+=(n-len(ref))
       co+=1
    if(co==k):
       break
    for i in range(len(ref)):
       y=ref[:i]+ref[i+1:]
       if(y not in r1):
           queue.append(y)
           r1.add(y)
if(len(r)<k):
    print(-1)
    exit(0)
print(cost)

iarr = list(map(int,input().split()))
n = iarr[0]
k = iarr[1]
s = input()
arr = []
arr.append(s)
ans = 0
ii = 0
flagg=0
while True:
	#print(arr)
	if flagg==1:
		#print("Hi")
		break
	if arr[ii]=="":
		break;
		#print("BYE")
	l = len(arr[ii])
	curcost = n-l+1
	for i in range(l):
		ss = arr[ii][:i] + arr[ii][i+1:]
		ll = len(arr)
		flag = True
		for j in range(ll):
			flag = flag and (ss!=arr[j])
		if len(arr)==k:
			flagg=1
			break

		if flag:
			arr.append(ss)
			ans+=curcost
	ii+=1
if len(arr)!=k:
	print(-1)
else:
	print(ans)

from sys import stdin
from collections import deque

n, k = map(int, input().split())
s = input()
que = deque()
que.append(s)
d = {}
num = 0
cost = 0
while que:
    q = que.popleft()
    if q not in d:
        cost += n - len(q)
        num += 1
        if num == k:
            print(cost)
            exit()
        d[q] = 1
        for j in range(len(q)):
            t = q[:j] + q[j + 1:]
            if t not in d:
                que.append(t)

print(-1)

import sys
from collections import defaultdict
n,k=map(int,input().split())
s=input()
b=[]
for j in s:
    b.append(j)

dp=[[0 for i in range(n+1)] for j in range(n)]
last=defaultdict(lambda:0)
dp[0][0]=1
dp[0][1]=1
last[b[0],0]=1
last[b[0],1]=1

for i in range(1,n):
    dp[i][0]=1
    for j in range(1,n+1):
        dp[i][j]=dp[i-1][j]+dp[i-1][j-1]-last[b[i],j]

        last[b[i],j]=dp[i-1][j-1]

s=0
res=0

if sum(dp[-1])<k:
    print(-1)
    sys.exit()
j=n
while(j>=0):
    if s+dp[-1][j]<k:
        s+=dp[-1][j]
        res+=dp[-1][j]*(n-j)

    else:
        res+=(k-s)*(n-j)
        break

    j+=-1

print(res)

n, k = map(int, input().split(' '))
s = input()
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
for l in range(0, n):
    for i in range(l, n + 1):
        used = [False] * 26
        for j in range(i + 1, n + 1):
            ch = ord(s[j - 1]) - ord('a')
            if not used[ch]:
                dp[l + 1][j] += dp[l][i]
                used[ch] = True
total = 0
for l in range(n, -1, -1):
    sums = sum(dp[l])
    if sums >= k:
        total += (n - l) * k
        k = 0
        break
    total += (n - l) * sums
    k -= sums
if k > 0:
    total = -1
print(total)

n, k = map(int, input().split())
targets = [input()]
ans = 0
cur = 1
depth = 0

if cur >= k:
    print(ans)
    exit()

while depth <= n:
    depth += 1
    next_target = []
    for target in targets:
        for i in range(len(target)):
            check = target[:i] + target[i+1:]
            if check in next_target:
                continue
            next_target.append(target[:i] + target[i+1:])
            ans += depth
            cur += 1
            if cur >= k:
                print(ans)
                exit()
    targets = next_target
print(-1)

n,k=map(int,input().split())
s=input()
st=[set() for i in range(n+1)]
st[n].add(s)
c=1
k-=1
ans=0
for i in range(n,0,-1):
    for w in st[i]:
        for j in range(i):
            st[i-1].add(w[:j]+(w[j+1:] if j!=i-1 else ''))
    sz=len(st[i-1])
    if k<sz:
        ans+=(n-i+1)*k
        k=0
        break
    else:
        ans+=(n-i+1)*sz
        k-=sz
    #print(i,k,ans)
    if k<0:
        break
if k>0:
    print(-1)
else:
    print(ans)
#print(k,ans,st)

import sys
from itertools import combinations
from functools import lru_cache
from string import ascii_lowercase

@lru_cache()
def e(n, l):
    return sum(d(n, l, x) for x in letters)

@lru_cache()
def d(n, l, c):
    if n < l:
        return 0
    if s[n - 1] != c:
        return d(n - 1, l, c)
    return e(n - 1, l - 1) if l > 1 else 1

def solve(s, k):
    n = len(s)
    cost = 0
    for l in range(n, 0, -1):
        cnt = e(n, l)
        if k > cnt:
            k -= cnt
            cost += cnt * (n - l)
        else:
            cost += k * (n - l)
            k = 0
            break
    if k > 1:
        return -1
    if k == 1:
        cost += n
        k = 0
    return cost

n, k = map(int, input().split())
s = input()
letters = set(s)
print(solve(s, k))

n,k=map(int,input().split())
s=input()
s=[ord(c)-ord('a') for c in s]
dp=[[[0]*26 for i in range(n+1)]for i in range(n)]
dp[0][1][s[0]]=1
sm=None

for i in range(1,n):
    c=s[i]
    for cc in range(26):
        dp[i][1][cc]=dp[i-1][1][cc]
    dp[i][1][c]=1
    for j in reversed(range(2,n+1)):
        for cc in range(26):
            if cc!=c:
                dp[i][j][cc]=dp[i-1][j][cc]
            else:
                tm=0
                for t in range(26):
                    tm+=dp[i-1][j-1][t]
                dp[i][j][cc]=tm
# print(dp[-1][-1])
def get(x):
    if x==0:
        return 1
    ans=0
    for i in range(26):
        ans+=dp[-1][x][i]
    return ans
cnt=0
cost=0
for re in reversed(range(n+1)):
    x=get(re)
    if x+cnt>=k:
        cost+=(n-re)*(k-cnt)
        cnt=k
        break
    else:
        cost+=(n-re)*x
        cnt+=x
if cnt<k:
    print(-1)
else:
    print(cost)

n, tt = map(int, input().split())
s = input()

dp = [[0]*(n + 1) for i in range(n+1)]

for c in range(n+1):
	dp[0][c] = 1

last = [-1]*26

for c in range(1, n + 1):
	k = ord(s[c-1]) - ord('a')
	for r in range(1, n+1):
		dp[r][c] = dp[r][c-1] + dp[r-1][c-1]
	if last[k] == -1:
		last[k] = c - 1
		continue
	else:
		p = last[k]
		for r in range(1, n+1):
			dp[r][c] = dp[r][c] - dp[r-1][p]
		last[k] = c-1

su, ans, t = 0, 0, 0
for r in range(n+1):
	su = su + dp[r][n]
if su < tt:
	ans = -1
else:
	for i in range(n, -1, -1):
		r = min(tt, dp[i][n])
		ans += t*r
		tt -= r
		t += 1

print(ans)

import sys,os,math
from collections import Counter, defaultdict
import bisect
from sys import stdin, stdout
from itertools import repeat, izip

# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())
# sys.stdin = open('input')

def main():
    inf = int(1e12)
    n, k = map(int, raw_input().split())
    s = raw_input()
    sda = map(lambda c: ord(c)-ord('a'), s)
    last = [[-1 for i in range(27)] for j in range(n+1)]
    for i in range(n):
        for j in range(26):
            if i != 0:
                last[i][j] = last[i-1][j]
            if sda[i] == j:
                last[i][j] = i
    dp = [[0 for i in range(n)] for j in range(n+1)]
    dp[0] = [1 for i in range(n)]
    dp[1] = [1 for i in range(n)]
    for lenth in range(2, n+1):
        for idx in range(lenth-1, n):
            for j in range(26):
                dp[lenth][idx] += dp[lenth-1][last[idx-1][j]] if last[idx-1][j] != -1 else 0
                dp[lenth][idx] = min(dp[lenth][idx], inf)
    # print dp
    ans = 0
    # print last[n-1]
    for lenth in range(n, -1, -1):
        for j in range(26):
            if last[n-1][j] == -1:
                continue
            if dp[lenth][last[n-1][j]] >= k:
                # print lenth,k,ans
                print ans+k*(n-lenth)
                return
            else:
                ans += dp[lenth][last[n-1][j]] * (n-lenth)
                k -= dp[lenth][last[n-1][j]]
    # print k
    print -1

main()

import sys,os,math
from collections import Counter, defaultdict
import bisect
from sys import stdin, stdout
from itertools import repeat, izip

# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

def main():
    inf = int(1e12)
    n, k = map(int, raw_input().split())
    s = raw_input()
    sda = map(lambda c: ord(c)-ord('a'), s)
    last = [[-1 for i in range(27)] for j in range(n+1)]
    for i in range(n):
        for j in range(26):
            if i != 0:
                last[i][j] = last[i-1][j]
            if sda[i] == j:
                last[i][j] = i
    dp = [[0 for i in range(n)] for j in range(n+1)]
    dp[0] = [1 for i in range(n)]
    dp[1] = [1 for i in range(n)]
    for lenth in range(2, n+1):
        for idx in range(lenth-1, n):
            for j in range(26):
                dp[lenth][idx] += dp[lenth-1][last[idx-1][j]] if last[idx-1][j] != -1 else 0
                dp[lenth][idx] = min(dp[lenth][idx], inf)
    # print dp
    ans = 0
    # print last[n-1]
    for lenth in range(n, -1, -1):
        for j in range(26):
            if last[n-1][j] == -1:
                continue
            if dp[lenth][last[n-1][j]] >= k:
                # print lenth,k,ans
                print ans+k*(n-lenth)
                return
            else:
                ans += dp[lenth][last[n-1][j]] * (n-lenth)
                k -= dp[lenth][last[n-1][j]]
    # print k
    print -1

main()

n, k = map(int, input().split(' '))
s = input()
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
prev = [None] * 26
for i in range(1, n + 1):
    for l in range(2, i + 1):
        for j in range(26):
            if prev[j] is not None:
                dp[l][i] += dp[l - 1][prev[j]]
    ch = ord(s[i - 1]) - ord('a')
    if prev[ch] is None:
        dp[1][i] = 1
    prev[ch] = i
total = 0
for l in range(n, -1, -1):
    sums = sum(dp[l])
    if sums >= k:
        total += (n - l) * k
        k = 0
        break
    total += (n - l) * sums
    k -= sums
if k > 0:
    total = -1
print(total)

n, k = map(int, input().split())
s = input()
last = [n + 1] * 30
dp = [[0] * 102 for i in range(102)]

for i in range(0, n + 1):
    dp[i][0] = 1
for i in range(1, n + 1):
    nm = ord(s[i - 1]) - ord('a')
    for le in range(1, i + 1):
        dp[i][le] = dp[i - 1][le] + dp[i - 1][le - 1]
        if last[nm] < i:
            dp[i][le] -= (dp[last[nm]][le] - dp[last[nm] - 1][le])
    last[nm] = i

ans = 0
for le in range(n, -1, -1):
    if k == 0:
        break
    x = min(dp[n][le], k)
    ans += (n - le) * x
    k -= x
if k != 0:
    print(-1)
else:
    print(ans)

n, k = map(int, input().split())
s = input()
last = [n + 1] * 30
dp = [[0] * 102 for i in range(102)]

for i in range(0, n + 1):
    dp[i][0] = 1
for i in range(1, n + 1):
    nm = ord(s[i - 1]) - ord('a')
    for le in range(1, i + 1):
        dp[i][le] = dp[i - 1][le] + dp[i - 1][le - 1]
        if last[nm] < i:
            dp[i][le] -= dp[last[nm]][le]
        dp[i][le] = min(dp[i][le], k)
    last[nm] = i

ans = 0
for le in range(n, -1, -1):
    if k == 0:
        break
    x = min(dp[n][le], k)
    ans += (n - le) * x
    k -= x
if k != 0:
    print(-1)
else:
    print(ans)

n, k = map(int, input().split())
s = input()
last = [n + 1] * 30
dp = [[0] * 102 for i in range(102)]

for i in range(0, n + 1):
    dp[i][0] = 1
for i in range(1, n + 1):
    nm = ord(s[i - 1]) - ord('a')
    for le in range(1, i + 1):
        dp[i][le] = dp[i - 1][le] + dp[i - 1][le - 1]
        if last[nm] < i:
            dp[i][le] -= min(dp[last[nm]][le], k)
        dp[i][le] = min(dp[i][le], k * 2)
    last[nm] = i

ans = 0
for le in range(n, -1, -1):
    if k == 0:
        break
    x = min(dp[n][le], k)
    ans += (n - le) * x
    k -= x
if k != 0:
    print(-1)
else:
    print(ans)

from sys import stdin

n, k = [int(i) for i in stdin.readline().strip().split()]
s = stdin.readline().strip()

def get_f(s):
    F = [len(s) * [0] for _ in range((len(s) + 1))]
    size = 0
    for index in range(len(s)):
        F[size][index] = 1
    F[1][0] = 1

    p = {s[0]: 0}
    for i in range(1, len(s)):
        for k in range(1, len(s) + 1):
            if k > i + 1:
                val = 0
            else:
                val = F[k][i - 1] + F[k - 1][i - 1]
                if s[i] in p:
                    # sic: if k - 1 == 0 then answer is always 1
                    if k - 1 == 0:
                        val -= 1
                    if p[s[i]] - 1 >= 0:
                        val -= F[k - 1][p[s[i]] - 1]
            F[k][i] = val
        p[s[i]] = i
    return F

_F = get_f(s)

# for sz in range(len(s) + 1):
#     for index in range(len(s)):
#         print(_F[sz][index], end=' ')
#     print()

def count(size, index = None):
    return _F[size][index or (len(s) - 1)]

# recursive solution with memoization
previous_letter_index = {}
found = {}
for index, letter in enumerate(s):
    if letter in found:
        previous_letter_index[(letter, index)] = found[letter]
    found[letter] = index

_subsequences = {}

def subsequences(size, index):
    """Get number of distinct subsequences of given size in sequence[0:index + 1] slice"""
    if (size, index) not in _subsequences:
        if size == 0:
            res = 1
        elif size > index + 1:
            res = 0
        else:
            res = subsequences(size, index - 1) + subsequences(size - 1, index - 1)
            letter = s[index]
            if (letter, index) in previous_letter_index:
                res -= subsequences(size - 1, previous_letter_index[(letter, index)] - 1)
        _subsequences[(size, index)] = res
    return _subsequences[(size, index)]

total_cost = 0
for size in range(len(s), -1, -1):
    if k == 0:
        break
    step_cost = n - size
    sequence_count = count(size, len(s) - 1)
    # print('size = ', size, 'count = ', sequence_count)
    if sequence_count > k:
        sequence_count = k
    total_cost += step_cost * sequence_count
    k -= sequence_count

if k == 0:
    print(total_cost)
else:
    print(-1)

from sys import stdout, stdin

n, kk = map(int, stdin.readline().split())
s = stdin.readline().strip()
s += "$"
n = n+1

dp = [[0 for i in range(n)] for j in range(n)]
p = 10**12+5
for i in range(n):
    dp[i][0] = 1
for end in range(n):
    for length in range(1, n):
        seen = []
        ans = 0
        for k in range(end-1, -1, -1):
            if s[k] not in seen:
                seen.append(s[k])
                ans += dp[k][length-1]
                ans %= p
        dp[end][length] = ans

totals = [dp[n-1][length] for length in range(n)]
#print(totals)

ans = 0
idx = n-1
while idx >= 0 and kk > 0:
    ans += min(totals[idx], kk)*(n-1-idx)
    kk -= totals[idx]
    idx -= 1

if kk <= 0:
    stdout.write(str(ans) +"\n")
else:
    print(-1)

n, k = map(int, input().split())
s = '{' + input()
dp = [[0] * (n + 1) for _ in range(n + 1)]

# dp
dp[0][0] = 1
oa = ord('a')
for i in range(1, n + 1):
    for j in range(1, n + 1):
        hold = [0] * 30
        for l in range(0, i): # Transition from dp[l][j - 1]
            let = ord(s[l]) - oa;
            # db(i); db(j); db(dp[i][j]); db(dp[l][j - 1]); db(hold[let]); dbln;
            dp[i][j] += dp[l][j - 1] - hold[let];

            hold[let] = dp[l][j - 1];

        # dblb("ret"); db(i); db(j); db(dp[i][j]); dbln;

# sum costs
tot = 0;
for i in range(n, -1):
    cost = n - i
    dpsum = 0;
    hold = [0] * 30
    for j in range(0, n + 1):
        let = ord(s[j]) - oa;
        dpsum += dp[j][i] - hold[let];
        hold[let] = dp[j][i];

    sub = min(k, dpsum);
    # db(i); db(dpsum); dbln;

    tot += sub * cost;
    k -= sub;

if k > 0:
    print(-1)
else:
    print(tot)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File              : H.py
# Author            : JCHRYS <jchrys@me.com>
# Date              : 30.08.2019
# Last Modified Date: 30.08.2019
# Last Modified By  : JCHRYS <jchrys@me.com>
class const:
    size = 26; # size of lowercase alphabet

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

maxpos = [[-1 for _ in range(const.size)] for _ in range(n)];

for i in range(n):
    for j in range(const.size):
        if i > 0:
            maxpos[i][j] = maxpos[i - 1][j]
    maxpos[i][ord(s[i]) - ord('a')] = i

#print(*[row for row in maxpos], sep="\n")
dp = [[0 for _ in range(n)] for _ in range(n)];

for i in range(n):
    dp[i][1] = 1

for length in range(2, n):
    for endswith in range(1, n):
        for before in range(const.size):
            if maxpos[endswith - 1][before] != -1:
                dp[endswith][length] = dp[endswith][length] + dp[maxpos[endswith - 1][before]][length - 1];

#print(*[row for row in dp], sep="\n")
k -= 1;
ans = 0;
for length in range(n-1, 0, -1):
    temp = 0;
    for i in range(const.size):
        if (maxpos[n-1][i] != -1):
            temp += dp[maxpos[n-1][i]][length];

    if temp >= k:
        ans += k * (n - length);
        k = 0;
        break;
    else:
        k -= temp;
        ans += temp * (n-length);

if (k == 1):
    ans += n;

if k > 0:
    print(-1)
    exit()
print(ans)

line1 = input().split(' ')
n = int(line1[0])
k = int(line1[1])
s = list(input())

dp = [101*[0] for i in range(101)]
last = 26*[-1]

for i in range(n+1):
    dp[0][i] = 1

for l in range(1, n+1):
    dp[l][0] = 0
    for c in range(26):
        last[c] = -1
    for i in range(1, n+1):
        dp[l][i] = dp[l-1][i-1] + dp[l][i-1]
        if last[ord(s[i-1])-ord('a')] != -1:
            dp[l][i] -= dp[l][last[ord(s[i-1])-ord('a')]]
        last[ord(s[i-1])-ord('a')] = i

i = 0
res = 0
while i <= n and k >= 0:
    c = min(k, dp[n-i][n])
    k -= c
    res += c * i
    i += 1
if k > 0:
    print(-1)
else:
    print(res)

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

# ------------------------------

def c(chr): return ord(chr)-ord('a')

def main():
    n, k = RL()
    s = input()

    dp = [[0]*(n+1) for i in range(n+1)]
    rec = [-1]*26
    pre = [-1]*n
    dp[0][0] = 1

    for i in range(n):
        now = c(s[i])
        pre[i] = rec[now]
        rec[now] = i

    for i in range(1, n+1):
        for j in range(1, i+1):
            if j>i: break

            if i==j: dp[i][j] = 1; continue;

            dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
            if pre[i-1]!=-1:
                # if i==5 and j==4: print(pre[i-1], '+++')
                dp[i][j] -= dp[pre[i-1]-1][j-1]

    res = 0
    for j in range(n, -1, -1):
        for i in range(n, -1, -1):
            if k:
                num = min(k, dp[i][j])
                k-=num
                res += (n-j)*num

    print(res if k==0 else -1)

if __name__ == "__main__":
    main()

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

# ------------------------------

def c(chr): return ord(chr)-ord('a')

def main():
    n, k = RL()
    s = input()

    dp = [[0]*(n+1) for i in range(n+1)]
    rec = [-1]*26
    pre = [-1]*n
    dp[0][0] = 1

    for i in range(n):
        now = c(s[i])
        pre[i] = rec[now]
        rec[now] = i

    for i in range(1, n+1):
        for j in range(1, i+1):
            if j>i: break

            if i==j: dp[i][j] = 1; continue;

            dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
            if pre[i-1]!=-1:
                # if i==5 and j==4: print(pre[i-1], '+++')
                dp[i][j] -= dp[pre[i-1]][j-1]

    res = 0
    for j in range(n, -1, -1):
        for i in range(n, -1, -1):
            if k:
                num = min(k, dp[i][j])
                k-=num
                res += (n-j)*num

    print(res if k==0 else -1)

if __name__ == "__main__":
    main()

import sys
n,k=map(int,input().split())
s=input()
b=[]
for j in s:
    b.append(j)

dp=[[0 for i in range(n+1)] for j in range(n)]
last=dict()
dp[0][0]=1
dp[0][1]=1
last[b[0]]=0
for i in range(1,n):
    dp[i][0]=1
    for j in range(1,n+1):
        if b[i] in last.keys():
            dp[i][j]=dp[i-1][j]+dp[i-1][j-1]-dp[last[b[i]]][j]
        else:
            dp[i][j] = dp[i - 1][j] + dp[i - 1][j- 1]
    last[b[i]]=i

s=0
res=0

if sum(dp[-1])<k:
    print(-1)
    sys.exit()
j=n
while(j>=0):
    if s+dp[-1][j]<k:
        s+=dp[-1][j]
        res+=dp[-1][j]*(n-j)

    else:
        res+=(k-s)*(n-j)
        break

    j+=-1

print(res)

n, d = map(int,input().split())
s = input()
t = [[-1 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
	for j in range(i, n + 1):
		if j == i:
			t[i][j] = 1
		else:
			t[i][j] = 0
jes = [0] * 300
for i in range(1, n + 1):
	jes[ord(s[i - 1])] = 1
	t[i][1] = sum(jes)
for j in range(2, n + 1):
	ind = [-1] * 300
	ind[ord(s[j - 1])] = j - 1
	#obliczamy t[j + 1][j], t[j + 2][j], ...
	for i in range(j + 1, n + 1):
		if ind[ord(s[i - 1])] == -1:
			t[i][j] = t[i - 1][j] + t[i-1][j-1]
		else:
			t[i][j] = t[i - 1][j] + t[i - 1][j - 1] - t[ind[ord(s[i-1])]+1][j - 1]
		ind[ord(s[i - 1])] = i - 1
#t[n][1], t[n][2], ..., t[n][n]
rozne = [t[n][i] for i in range(1, n + 1)]
rozne.reverse()
roz = rozne + [1]
dupa = 0
wyn = 0
for i in range(n + 1):
	if dupa < d:
		k = min(roz[i], (d-dupa))
		dupa += k
		wyn += k * i
	else:
		break
if dupa >= d:
	print(wyn)
else:
	print(-1)

[n, k] = [int(i) for i in input().split()]
s = input()
cntsz = [0 for i in range(105)]
dp = [[0 for i in range(105)] for j in range(105)]
lst = [0 for i in range(105)]
prv = [0 for i in range(26)]
n = len(s)
s = '%' + s
for i in range(n + 1):
  dp[i][0]=1
for i in range(1, n + 1):
	lst[i] = prv[ord(s[i])-ord('a')]
	prv[ord(s[i]) - ord('a')] = i
for sz in range(1, n + 1):
	for i in range(1, n + 1):
		dp[i][sz] += dp[i - 1][sz]
		dp[i][sz] += dp[i - 1][sz - 1]
		if lst[i] != 0:
			 dp[i][sz] -= dp[lst[i]][sz]
for sz in range(1, n + 1):
	for i in range(1, n + 1):
		cntsz[sz] += dp[i][sz]
		cntsz[sz] -= dp[i - 1][sz]
cntsz[0] += 1
done = 0
ans = 0
for i in range(n, -1, -1):
    if done + cntsz[i] >= k:
       ans += (n - i) * (k - done)
       done = k
       break
    done += cntsz[i]
    ans += cntsz[i] * (n - i)
if done < k:
    print(-1)
else:
    print(ans)

n, k = map(int, input().split())
targets = [input()]
ans = 0
cur = 1
depth = 0
while depth <= n:
    depth += 1
    next_target = []
    for target in targets:
        for i in range(len(target)):
            check = target[:i] + target[i+1:]
            if check in next_target:
                continue
            next_target.append(target[:i] + target[i+1:])
            ans += depth
            cur += 1
            if cur >= k:
                print(ans)
                exit()
    targets = next_target
print(-1)

n, k = map(int, input().split())
str = str(input())
q = [str]
ans = 0
ma = {}
while len(q) != 0 and k > 1 :
    s = q.pop()
    for i in range(len(s)):
        ss = s
        s1 = ss[0:i]
        s2 = ss[i+1:]
        ss = s1 + s2
        if ss not in ma.keys() :
            ma[ss] = 1
            k -= 1
            ans += n - len(ss)
            q.append(ss)
            if k == 1 : break
if k == 1 :
    print(ans)
else :
    print(-1)

def check_word(word_list, word_need):
    unique = []
    for i in range(len(word_list)):
        # Pick each word in the list
        if word_need == 0:
            break
        for j in range(len(word_list[i])):
            if word_need == 0:
                break
            # Check word without 1 char is in unique
            new_word = word_list[i][:j]+word_list[i][j+1:]
            if new_word not in unique:
                unique.append(new_word)
                word_need -= 1
    return unique

def check_all():
    cost_sum = 0
    cost_each = 1
    [raw_length, raw_size] = input().split()
    size = int(raw_size)
    words = input().split()
    size -= 1
    while size>0:
        if len(words[0]) == 0:
            return -1
        words = check_word(words, size)
        print(len(words))
        cost_sum += len(words)*cost_each
        cost_each += 1
        size -= len(words)
    return cost_sum

print(check_all())

N, K = map(int, input().split())
pre = [input()]
ans = 0
k = 1
f = 0
while True:
    if len(pre) == 0:
        print(-1)
        break
    post = []
    for s in pre:
        for i in range(len(s)):
            t = s[:i] + s[i+1:]
            if t not in post:
                k += 1
                post.append(t)
                ans += N-len(t)
                if k >= K:
                    print(ans)
                    f = 1
                    break
        if f:
            break
    if f:
        break
    pre = post

def solve(n, k, s):

    set = {s: 0}
    ans = 0

    found = False
    for length in range(n, 0, -1):
        for i in range(1, n+1):
            for x in range(length):
                newS = s[:x] + s[x+i:length]
                if newS not in set:
                    set[newS] = i

    if len(set) < k:
        print(-1)
    else:
        arr = list(sorted(set.items(), key=lambda x: x[1]))
        for i in range(k):
            ans += arr[i][1]
        print(ans)

def main():

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

    s = input()

    solve(n, k, s)

if __name__ == "__main__":

    main()

#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
line = input()
need = int(line.split(' ')[1]) - 1
n = int(line.split(' ')[0])
s = input()

if need == 1:
    print(0)
else:
    queue = [s]
    d = {}
    head, tail, ans = 0, 1, 0
    solve = False

    while head < tail and not solve:
        top = queue[head]
        cost = len(top)-1
        for idx, c in enumerate(top):
            new = ''.join([top[:idx], top[idx + 1:]])
            h = new.__hash__()
            if not d.get(h):
                d[h] = 1
                queue.append(new)
                tail += 1
                ans += n - cost
                need -= 1
                if need == 0:
                    solve = True
                    break
        head += 1

    if not solve:
        print("-1")
    else:
        print(ans)

n,k=map(int,input().split())
s=input()
st=[set() for i in range(n+1)]
st[n].add(s)
c=1
k-=1
ans=0
for i in range(n,0,-1):
    for w in st[i]:
        for j in range(i):
            st[i-1].add(w[:j]+(w[j+1:] if j!=i-1 else ''))
    sz=len(st[i-1])
    if k<sz:
        ans+=(n-i+1)*k
        break
    else:
        ans+=(n-i+1)*sz
        k-=sz
    if k<0:
        break
if k<0:
    print(-1)
else:
    print(ans)

from sys import stdin

n, k = [int(i) for i in stdin.readline().strip().split()]
s = stdin.readline().strip()

class Subsequences:
    def __init__(self, sequence):
        self._seq = list(sequence)
        self._F = [len(sequence) * [0] for _ in range((len(sequence) + 1))]
        self._calc()

    def _calc(self):
        # iterative solution F[size][index] given number of distinct subsequences of given size
        # in slice [0: index + 1] of original sequence
        F = self._F
        size = 0
        for index in range(len(s)):
            F[size][index] = 1
        F[1][0] = 1

        p = {s[0]: 0}
        for i in range(1, len(s)):
            for k in range(1, len(s) + 1):
                if k > i + 1:
                    val = 0
                else:
                    val = F[k][i - 1] + F[k - 1][i - 1]
                    if s[i] in p:
                        val -= F[k - 1][p[s[i]] - 1]
                F[k][i] = val
            p[s[i]] = i

    def count(self, size, index=None):
        index = index or (len(self._seq) - 1)
        return self._F[size][index]

# recursive solution with memoization
previous_letter_index = {}
found = {}
for index, letter in enumerate(s):
    if letter in found:
        previous_letter_index[(letter, index)] = found[letter]
    found[letter] = index

_subsequences = {}

def subsequences(size, index):
    """Get number of distinct subsequences of given size in sequence[0:index + 1] slice"""
    if (size, index) not in _subsequences:
        if size == 0:
            res = 1
        elif size > index + 1:
            res = 0
        else:
            res = subsequences(size, index - 1) + subsequences(size - 1, index - 1)
            letter = s[index]
            if (letter, index) in previous_letter_index:
                res -= subsequences(size - 1, previous_letter_index[(letter, index)] - 1)
        _subsequences[(size, index)] = res
    return _subsequences[(size, index)]

ss = Subsequences(s)

total_cost = 0
for size in range(len(s), 0, -1):
    if k == 0:
        break
    step_cost = n - size
    sequence_count = subsequences(size, len(s) - 1)
    if sequence_count > k:
        sequence_count = k
    total_cost += step_cost * sequence_count
    k -= sequence_count

if k == 0:
    print(total_cost)
else:
    print(-1)

import queue

def process_test_case():
    n, k = list(map(int, input().split()))
    S = input()
    q = queue.Queue()
    output = set()
    cost=0
    count=1
    output.add(S)
    q.put((S,0))

    while not q.empty():
        string, point_cost = q.get()
        # print(string, point_cost)
        for i in range(len(string)):
            temp = string[:i]+string[i+1:]
            if temp not in output:
                # print(temp, temp in output, output)
                output.add(temp)
                q.put((temp,point_cost+1))
                cost += point_cost+1
                count+=1
                if count>=k:
                    return cost
    if len(output)<k:
        return -1
    return cost

if __name__=="__main__":
    print(process_test_case())

import queue

def process_test_case():
    n, k = list(map(int, input().split()))
    S = input()
    q = queue.Queue()
    output = set()
    cost=0
    output.add(S)
    q.put((S,0))

    while not q.empty():
        string, point_cost = q.get()
        # print(string, point_cost)
        for i in range(len(string)):
            temp = string[:i]+string[i+1:]
            if temp not in output:
                # print(temp, temp in output, output)
                output.add(temp)
                q.put((temp,point_cost+1))
                cost += point_cost+1
                if len(output)>=k:
                    return cost
    if len(output)<k:
        return -1
    return cost

if __name__=="__main__":
    print(process_test_case())

import queue

def process_test_case():
    n, k = list(map(int, input().split()))
    q = queue.Queue()
    S = input()
    output = set()
    cost=0
    count=1
    output.add(S)
    q.put((S,0))

    while not q.empty():
        string, point_cost = q.get()
        # print(string, point_cost)
        for i in range(len(string)):
            temp = string[:i]+string[i+1:]
            if temp not in output:
                # print(temp, temp in output, output)
                output.add(temp)
                q.put((temp,point_cost+1))
                cost += point_cost+1
                count+=1
                if count>=k:
                    return cost
    if len(output)<k:
        return -1
    return count

if __name__=="__main__":
    print(process_test_case())

import itertools
def sub_lists(list1):
    # store all the sublists
    sublist = [[]]

    # first loop
    for i in range(len(list1) + 1):

        # second loop
        for j in range(i + 1, len(list1) + 1):
            # slice the subarray
            sub = list1[i:j]
            sublist.append(sub)

    return sublist

n,k=input().split()
n=int(n)
k=int(k)
string=input()
lst=[]
for i in string:
    lst.append(i)
temp=sub_lists(lst)
temp.sort(key=len)
temp=list(temp for temp,_ in itertools.groupby(temp))
if len(temp)<k:
    print(-1)
else:
    z=0
    ans=0
    while k>0:
        k-=1
        ans+=len(temp[z])
        z+=1
    print(ans)

n, k = map(int, input().split())
s = input()
c = 0
q = [s]
d = set()
x = 0
while q:
    p = q.pop(0)
    print(p)
    if p not in d:
        x += 1
        c += (n - len(p))
        if x == k:
            break
        d.add(p)
        for i in range(len(p)):
            t = p[:i] + p[i + 1:]
            if t not in d:
                q.append(t)
if x == k:
    print(c)
else:
    print(-1)

n,k=map(int,input().split())
dict1={}
sumx=0
ans=1
def func1(arr,k,l):
	global dict1
	global sumx
	global ans
	arr1=[]
	#print(ans)
	for i in range(len(arr)):
		for j in range(len(arr[i])):
			try:
				dict1[arr[i][:j]+arr[i][j+1:]]+=1
			except:
				KeyError
				dict1[arr[i][:j]+arr[i][j+1:]]=1
				arr1.append(arr[i][:j]+arr[i][j+1:])
				ans+=1
				#print(ans)
				if(ans==k):
					return arr1
	return arr1

s=str(input())
arr=[s]
flag=0
for i in range(n-1,-1,-1):
	if(len(arr)>0):
		arr=func1(arr,k,i)
		if(ans>=k):
			flag=1
			break
if(flag==0):
	print(-1)
else:
	sumx=0
	n=len(s)
	for i in dict1.keys():
		#print(i)
		sumx+=n-len(i)
	print(sumx)
#print(dict1)

import sys,math
from fractions import gcd
from bisect import bisect_left, bisect
from collections import defaultdict
from io import BytesIO
sys.stdin = BytesIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
#n = int(input())
n,k = [int(_) for _ in input().split()]
st = input()
resset = set()

curs = {st}
m = 1
res = 0
ns = set()
while m < k:
    if len(curs):
        x = curs.pop()
        for i in range(len(x)):
            ch = x[:i] + x[i+1:]
            if ch not in ns:
                ns.add(ch)
                m += 1
                res += n - len(ch)
                if m == k:
                    print(res)
                    exit(0)
    else:
        if len(ns):
            curs = ns
            ns = set()
        else:
            print(-1)
            exit(0)

S = set()
custo = 0
generated = []
def generate(ln, k):
    for st in list(generated[ln]):
        for i in xrange(len(st)):
            to_add = st[:i] + st[i+1:]
            generated[ln-1].add(to_add)
            S.add(to_add)
            if len(S) == k: return

n, k = map(int, raw_input().split())
s = raw_input()
S.add(s)
for i in xrange(n+1): generated.append(set())
generated[0].add('')
generated[-1].add(s)
print generated
if (pow(2, n) < k): print -1
elif (k == 1): print 0
else:
    for l in xrange(n, 0, -1):
        generate(l, k)
        if len(S) == k: break

    if len(S) < k: print -1
    else:
        generated = list(S)
        for i in xrange(len(S)): custo += (n - len(generated[i]))
        print custo

S = set()
custo = 0
generated = []
def generate(s, k):
    if len(S) == k: return
    for i in xrange(len(s)):
        new = s[:i] + s[i+1:]
        S.add((len(new), new))
        if len(S) == k: return
        generate(new, k)

n, k = map(int, raw_input().split())
s = raw_input()
if (pow(2, n) < k): print -1
elif (k == 1): print 0
else:
    generate(s, k)
    generated = list(S)
    generated.append((n, s))
    generated.sort()
    if len(generated) < k: print -1
    else:
        for i in xrange(len(generated)-1, len(generated)-k-1, -1): custo += (n - generated[i][0])
        print custo

# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 16:11:00 2019

@author: dake3
"""

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

b = True

if n>=k**2:
    print(1)
    b = False
    exit()

def all_subs(word):
    sub = []
    for i in range(len(word)):
        for j in range(i, len(word)):
            sub.append(word[i:j+1])
    return set(sub)

# Function which returns subset or r length from n
from itertools import combinations

def rSubset(arr, r):

	# return list of all subsets of length r
	# to deal with duplicate subsets use
	# set(list(combinations(arr, r)))
	return list(combinations(arr, r))

S = []
S.append(s)
for x in range(n):
    arr = list(s)
    S += [''.join(i) for i in rSubset(arr, x)]

cost = 0

S = list(set(S))
S.sort(key=len, reverse=True)

if len(S) < k and b == True:
    print('-1')
elif b == True:
    S = S[0:k]
    for i in range(k):
        cost += n-len(S[i])
    print(cost)
#print(S)
#print(len(S))

from itertools import combinations

#n, k = map(int, input().split())
#s = str(input())
#n = length of string
#k = size of set
#s = string
n = 10
k = 100
s = 'ajihiushda'

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def single(s):
    S = []
    S.append(s)
    for i in range(len(s)):
        S.append(s[0:i])
    S.sort(key=len)
    S = S[::-1]
    return S

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = sorted(B, key=len)
        B = B[::-1]
        B.append("")
        B = B[0:k]
        cost = 0
        for i in range(k):
            cost += n-len(B[i])
        return cost

if n>k:
    print(k-1)
elif repeat(s) == True:
    A = (single(s))
    print(test(A))
else:
    A = []
    arr = list(s)
    A += [''.join(i) for i in rSubset(list(s), n-1)]
    B = []
    B.append(s)
    B = set(B) #.update
    B.update(A)
    z = 0
    while n-1-z>0:
        z += 1
        if len(B) > k:
            break
        for x in range(len(A)):
            B.update([''.join(i) for i in rSubset(list(s), n-1-z)])
            B = list(B)
            B = sorted(B, key=len)
            B = B[::-1]
            if len(B) > k:
                break
            else:
                B = set(B)
    print(test(B))

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

def rSubset(arr, r):
	return list(set(list(combinations(arr, r))))

if n>k:
    print(k-1)
else:
    S = []
    for x in range(n, -1, -1):
        arr = list(s)
        S += [''.join(i) for i in rSubset(arr, x)]
        if len(S) > k:
            break
    if len(S) < k:
        print('-1')
    else:
        S = S[0:k]
        print(S)
        cost = 0
        for i in range(k):
            cost += n-len(S[i])
        print(cost)

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'
#cost = 233

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def single(s):
    S = []
    S.append(s)
    for i in range(len(s)):
        S.append(s[0:i])
    S.sort(key=len)
    S = S[::-1]
    return S

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = sorted(B, key=len)
        B = B[::-1]
        B.append("")
        B = B[0:k-1]
        cost = 0
        for i in range(k-1):
            cost += n-len(B[i])
        return cost

if n>k:
    print(k-1)
elif repeat(s) == True:
    A = (single(s))
    print(test(A))
else:
    master = []
    A = []
    arr = list(s)
    A += list(rSubset(arr, n-1))
    B = set()
    B.update(A)
    A = set(A)
    for z in range(len(s)):
        if len(A) > k-1:
            A = list(A)
            A.sort(key=len)
            A = A[::-1]
            break
        for x in B:
            A.update(list(rSubset(x, len(x)-z)))
            if len(A) > k-1:
                A = list(A)
                A.sort(key=len)
                break
            master = list(master)
            master += B
            master = set(master)
            A = list(A)
            A.sort(key=len)
            A = A[::-1]
            A = set(A)
    print(test(A))

"""
list of sets = [{s}]
while it's not enough:
    new set = set()
    for sigma in listofsets[-1]:
        newset.update(rsubset(sigma, len(sigma) - 1))
    listofsets.append(new set)

you can do the rest

queue = however you make aqueue in python
aset = set()

queue add s
aset add s

while len(aset) < k:
    astring = queue...remove()
    for eachstring in rsbubset(astring poop):
        if eachstring not in aset:
            aset add eachstring
            queue add eachstring
            if len(aset) == k:
                break break
"""

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

def rSubset(arr, r):
	return list(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == l[0]:
            l2.append(True)
    if False in l2:
        return False
    else:
        return True

def single(s):
    S = []
    S.append(s)
    for i in range(len(s)):
        S.append(s[0:i])
    S.sort(key=len)
    S = S[::-1]
    return S

def test(S):
    if len(S) < k:
        return '-1'
    else:
        S = S[0:k]
        cost = 0
        for i in range(k):
            cost += n-len(S[i])
        return cost

if n>k:
    print(k-1)
elif repeat(s) == True:
    S = (single(s))
    print(test(S))
else:
    S = []
    for x in range(n, -1, -1):
        arr = list(s)
        S += [''.join(i) for i in rSubset(arr, x)]
        if len(S) > k:
            break
    print(test(S))

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'
#cost = 233

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def single(s):
    S = []
    S.append(s)
    for i in range(len(s)):
        S.append(s[0:i])
    S.sort(key=len)
    S = S[::-1]
    return S

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = B[0:k]
        cost = 0
        for x in B:
            cost += n-len(x)
        return cost

def testS(B):
    if len(B) < k:
        return '-1'
    else:
        B = B[0:k]
        cost = 0
        for i in range(k):
            cost += n-len(B[i])
        return cost

if n>k:
    print(k-1)
elif repeat(s) == True:
    A = (single(s))
    print(testS(A))
else:
    master = []
    B = {s}
    A = set()
    for z in range(len(s)):
        if len(master) >= k:
            break
        for x in B:
            A.update(list(rSubset(x, len(x)-1)))
            if len(A) > k:
                A = list(A)
                A.sort(key=len)
                break
        master += B
        B=A
        A=set()
    master.append('')
    print(test(master))

"""
list of sets = [{s}]
while it's not enough:
    new set = set()
    for sigma in listofsets[-1]:
        newset.update(rsubset(sigma, len(sigma) - 1))
    listofsets.append(new set)

you can do the rest

queue = however you make aqueue in python
aset = set()

queue add s
aset add s

while len(aset) < k:
    astring = queue...remove()
    for eachstring in rsbubset(astring poop):
        if eachstring not in aset:
            aset add eachstring
            queue add eachstring
            if len(aset) == k:
                break break
"""

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'
#cost = 233

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = B[0:k]
        cost = 0
        for x in B:
            cost += n-len(x)
        return cost

if n>k:
    print(k-1)
else:
    master = []
    B = {s}
    A = set()
    for z in range(len(s)):
        if len(master) >= k:
            break
        for x in B:
            A.update(list(rSubset(x, len(x)-1)))
            if len(A) > k:
                A = list(A)
                A.sort(key=len)
                break
        master += B
        B=A
        A=set()
    master.append('')
    print(test(master))

"""
list of sets = [{s}]
while it's not enough:
    new set = set()
    for sigma in listofsets[-1]:
        newset.update(rsubset(sigma, len(sigma) - 1))
    listofsets.append(new set)

you can do the rest

queue = however you make aqueue in python
aset = set()

queue add s
aset add s

while len(aset) < k:
    astring = queue...remove()
    for eachstring in rsbubset(astring poop):
        if eachstring not in aset:
            aset add eachstring
            queue add eachstring
            if len(aset) == k:
                break break
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 16:11:00 2019

@author: dake3
"""

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

b = True

if n>k**2:
    print(1)
    b = True

def all_subs(word):
    sub = []
    for i in range(len(word)):
        for j in range(i, len(word)):
            sub.append(word[i:j+1])
    return set(sub)

# Function which returns subset or r length from n
from itertools import combinations

def rSubset(arr, r):

	# return list of all subsets of length r
	# to deal with duplicate subsets use
	# set(list(combinations(arr, r)))
	return list(combinations(arr, r))

S = []
S.append(s)
for x in range(n):
    arr = list(s)
    S += [''.join(i) for i in rSubset(arr, x)]

cost = 0

S = list(set(S))
S.sort(key=len, reverse=True)

if len(S) < k and b == True:
    print('-1')
elif b == True:
    S = S[0:k]
    for i in range(k):
        cost += n-len(S[i])
    print(cost)
#print(S)
#print(len(S))

# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 16:11:00 2019

@author: dake3
"""

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

def all_subs(word):
    sub = []
    for i in range(len(word)):
        for j in range(i, len(word)):
            sub.append(word[i:j+1])
    return set(sub)

# Function which returns subset or r length from n
from itertools import combinations

def rSubset(arr, r):

	# return list of all subsets of length r
	# to deal with duplicate subsets use
	# set(list(combinations(arr, r)))
	return list(combinations(arr, r))

if n>=k:
    print(k-1)
else:
    S = []
    S.append(s)
    for x in range(n):
        arr = list(s)
        S += [''.join(i) for i in rSubset(arr, x)]
    S = list(set(S))
    S.sort(key=len, reverse=True)
    if len(S) < k:
        print('-1')
    else:
        S = S[0:k]
        cost = 0
        for i in range(k):
            cost += n-len(S[i])
        print(cost)
#print(S)
#print(len(S))

from itertools import combinations

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'
#cost = 233

def rSubset(arr, r):
    return(set(list(combinations(arr, r))))

def repeat(s):
    l = list(s)
    l2 = []
    for i in range(len(s)):
        if l[i] == str(s[0]):
            l2.append(True)
        else:
            l2.append(False)
    if False in l2:
        return False
    else:
        return True

def single(s):
    S = []
    S.append(s)
    for i in range(len(s)):
        S.append(s[0:i])
    S.sort(key=len)
    S = S[::-1]
    return S

def test(B):
    if len(B) < k:
        return '-1'
    else:
        B = sorted(B, key=len)
        B = B[::-1]
        B.append("")
        B = B[0:k-1]
        cost = 0
        for i in range(k-1):
            cost += n-len(B[i])
        return cost

def testS(B):
    if len(B) < k:
        return '-1'
    else:
        B = B[0:k]
        cost = 0
        for i in range(k):
            cost += n-len(B[i])
        return cost

if n>k:
    print(k-1)
elif repeat(s) == True:
    A = (single(s))
    print(testS(A))
else:
    master = []
    A = []
    arr = list(s)
    A += list(rSubset(arr, n-1))
    B = set()
    B.update(A)
    A = set(A)
    for z in range(len(s)):
        if len(A) > k-1:
            A = list(A)
            A.sort(key=len)
            A = A[::-1]
            break
        for x in B:
            A.update(list(rSubset(x, len(x)-z)))
            if len(A) > k-1:
                A = list(A)
                A.sort(key=len)
                break
            master = list(master)
            master += B
            master = set(master)
            A = list(A)
            A.sort(key=len)
            A = A[::-1]
            A = set(A)
    print(test(A))

"""
list of sets = [{s}]
while it's not enough:
    new set = set()
    for sigma in listofsets[-1]:
        newset.update(rsubset(sigma, len(sigma) - 1))
    listofsets.append(new set)

you can do the rest

queue = however you make aqueue in python
aset = set()

queue add s
aset add s

while len(aset) < k:
    astring = queue...remove()
    for eachstring in rsbubset(astring poop):
        if eachstring not in aset:
            aset add eachstring
            queue add eachstring
            if len(aset) == k:
                break break
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 16:11:00 2019

@author: dake3
"""

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

b = True

if n>k:
    print(1)
    b = False

def all_subs(word):
    sub = []
    for i in range(len(word)):
        for j in range(i, len(word)):
            sub.append(word[i:j+1])
    return set(sub)

# Function which returns subset or r length from n
from itertools import combinations

def rSubset(arr, r):

	# return list of all subsets of length r
	# to deal with duplicate subsets use
	# set(list(combinations(arr, r)))
	return list(combinations(arr, r))

S = []
S.append(s)
for x in range(n):
    arr = list(s)
    S += [''.join(i) for i in rSubset(arr, x)]

cost = 0

S = list(set(S))
S.sort(key=len, reverse=True)

if len(S) < k and b == True:
    print('-1')
elif b == True:
    S = S[0:k]
    for i in range(k):
        cost += n-len(S[i])
    print(cost)
#print(S)
#print(len(S))

from collections import deque
n, k = map(int, input().split())

s = input()

queue = deque([s])
visited = set()

cost = 0
num_of_words = 1

while queue:
    new = queue.popleft()
    for i in range(len(new)):
        neigh = new[0:i] + new[i + 1:]
        if neigh not in visited :
            cost += n - len(new) + 1
            num_of_words += 1
            visited.add(neigh)
            queue.append(neigh)

        if num_of_words >= k:
            break
    #print(queue)

if num_of_words < k:
    print(-1)
else:
    print(cost)

from queue import Queue
n,k = [int(x) for x  in input().split()]
s = input()
if k==1:
    print(s)
    exit()
k = k-1
q = Queue()
q.put((s,0))
added = 1
count = 0
answer = 0
found = False
st = set()
while (not found) and (not q.empty()):
    el = q.get()
    e = el[0]
    #st = set()
    for i in range(len(e)):
        subs = e[0:i]+e[i+1:]
        #print('subs is ',subs)
        if subs in st:
            continue
        st.add(subs)
    #for e in st:
        q.put((subs,1+el[1]))
        #print("added ",(subs,1+el[1]))
        answer = answer + el[1]+1
        count += 1
        if count == k:
            found = True
            print(answer)
            break
    #print(q.queue)
if not found:
    print(-1)

import sys
from itertools import combinations
from functools import lru_cache
from string import ascii_lowercase

@lru_cache()
def e(n, l):
    return sum(d(n, l, x) for x in letters)

@lru_cache()
def d(n, l, c):
    if n < l:
        return 0
    if s[n - 1] != c:
        return d(n - 1, l, c)
    return e(n - 1, l - 1) if l > 1 else 1

def solve(s, k):
    n = len(s)
    cost = 0
    for l in range(n, 0, -1):
        cnt = e(n, l)
        if k > cnt:
            k -= cnt
            cost += cnt * (n - l)
        else:
            cost += k * (n - l)
            k = 0
            break
    if k > 1:
        return -1
    if k == 1:
        cost += n
        k = 0
    return cost

# n, k = map(int, input().split())
# s = input()
n, k = 100, 100
s = 'a' * 100
letters = set(s)
print(solve(s, k))