做法:动态规划
思路
- 用pre[i]存上一次'a'+i这个字母出现的位置,设dp[i][j]:前i个字符中长度为j的数量
- 如果一个字母上次出现过,需要减去
dp[pre[s[i]-'a']-1][j-1]
重复的子序列 - 每次删最少的字符即长度越长的子序列优先
代码
// Problem: Subsequences (hard version)
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/problem/113788
// Memory Limit: 524288 MB
// Time Limit: 4000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp(aa,bb) make_pair(aa,bb)
#define _for(i,b) for(int i=(0);i<(b);i++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,b,a) for(int i=(b);i>=(a);i--)
#define mst(abc,bca) memset(abc,bca,sizeof abc)
#define X first
#define Y second
#define lowbit(a) (a&(-a))
#define debug(a) cout<<#a<<":"<<a<<"\n"
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
typedef long double ld;
const int N=105;
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-6;
const double PI=acos(-1.0);
int n;
int pre[N];
ll k,ans,num;
ll dp[N][N];//dp[i][j]:前i个字符中长度为j的数量
string s;
void solve(){
cin>>n>>k;
cin>>s;s=" "+s;
rep(i,0,n) dp[i][0]=1;
rep(i,1,n){
rep(j,1,i){
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
if(pre[s[i]-'a']) dp[i][j]-=dp[pre[s[i]-'a']-1][j-1];
}
pre[s[i]-'a']=i;
}
rep(i,0,n) {
num+=dp[n][i];
}
if(num<k){
cout<<"-1\n";
}
else{
per(i,n,0){
if(dp[n][i]<k){
k-=dp[n][i];
ans+=dp[n][i]*(n-i);
}
else{
ans+=k*(n-i);
cout<<ans<<"\n";
return;
}
}
}
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
// int t;cin>>t;while(t--)
solve();
return 0;
}