Meaning of the questions and ideas: https://blog.csdn.net/mmk27_word/article/details/93999633
The first time I saw this DP, a bit like thinking back backpack, and if found to have the same alphabet as possible and re-calculate earlier, the case is subtracted.
Code:
#include <bits/stdc++.h> #define LL long long using namespace std; const int maxn = 110; int pre[30]; LL dp[maxn][maxn]; char s[maxn]; int main() { int n; LL k, cost = 0; scanf("%d%lld", &n, &k); scanf("%s",s + 1); dp[0][0] = 1; memset(pre, -1, sizeof(pre)); for (int i = 1; i <= n; i++) { int now = s[i] - 'a'; int tmp = i - pre[now]; dp[i][0] = 1; for (int j = 1; j <= i; j++) { dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; if(pre[now] != -1 && j >= tmp) dp[i][j] -= dp[pre[now] - 1][j - tmp]; dp[i][j] = min(dp[i][j], k); } pre[now] = i; } for (int i = 0; i <= n; i++) { LL tmp = min(dp[n][i], k); cost += tmp * i; k -= tmp; if(k == 0) break; } if(k > 0) printf("-1\n"); else printf("%lld\n", cost); }