题意及思路:https://blog.csdn.net/mmk27_word/article/details/93999633
第一次见这种DP,有点像退背包的思想,如果发现有可能因为字母相同和前面算重时,把这种情况减去。
代码:
#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); }
原文地址:https://www.cnblogs.com/pkgunboat/p/11105299.html
时间: 2024-10-10 00:39:06