Description:
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.
Input
The first line of the input contains two integers n and k (1≤n≤100,1≤k≤1012) — 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.
Output
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.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In 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.
题意:
给出一个长度为n的字符串s,从s中删去某些字符可以得到s的不同子串,问累计删去多少个字符可以得到k个不同的子串,如果没有k个,输出-1。
解法:
这道题的核心在于求出每个长度的不同子串有多少个。
设dp[i][j]为以s[i]结尾,长度为j的子串的个数,则该个数为以a到z结尾,长度为j-1的子串的个数和。用pos数组记录每个字母此时在字符串中最后出现的位置(因为位置越往后,同样长度的子串就会越多),三重循环就可以求出dp数组。
用sum[i]记录长度为i的子串的个数,也就是以a到z结尾,长度为i的子串的个数和。对于k,每次和sum[i]作比较即可。
注意数组大小,一开始开小了然而没有报RE或者MLE,检查了好久的代码。
注意k归零之后的break,没加会WA35,又检查了好久的代码。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stdlib.h>
#include<cstring>
#include<set>
using namespace std;
long long n,k;
long long ans=0;
int pos[26+5];
char s[100+5];
long long dp[100+5][100+5];
long long sum[100+5];
int main()
{
scanf("%lld%lld%s",&n,&k,s+1);
for(int i=1;i<=n;i++){
dp[i][1]=1;
for(int j=2;j<=i;j++){
for(int t=1;t<=26;t++){
dp[i][j]+=dp[pos[t]][j-1];
}
}
pos[s[i]-'a'+1]=i;
}
sum[0]=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=26;j++)sum[i]+=dp[pos[j]][i];
}
for(int i=n;i>=0;i--){
if(k<sum[i]){ans+=k*(n-i);k=0;break;}
else {ans+=sum[i]*(n-i);k-=sum[i];}
}
if(k==0)printf("%lld\n",ans);
else printf("-1\n");
return 0;
}