1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> using namespace std;
#define int long long const int CN = 210;
int read(){ int s = 0,ne = 1; char c = getchar(); while(c < '0' || c > '9') ne = c == '-' ? -1 : 1, c = getchar(); while(c >= '0' && c <= '9') s = (s << 1) + (s << 3) + c - '0', c = getchar(); return s * ne; }
int n, d, f[CN][CN][CN], ans; char s[CN], c1, c2;
void DP1(){ memset(f, -0x3f, sizeof(f)), f[0][0][0] = 0; int c = 0; for(int i = 1; i <= n; i++){ f[i][c + (s[i] == c1)][0] = f[i - 1][c][0]; c += (s[i] == c1); if(s[i] == c2) f[i][c][0] += c; } for(int k = 0; k <= d; k++) for(int c = 0; c <= n; c++) for(int i = 0; i <= n; i++){ if(s[i + 1] == c2) f[i + 1][c][k] = max(f[i + 1][c][k], f[i][c][k] + c); else if(s[i + 1] == c1) f[i + 1][c + 1][k] = max(f[i + 1][c + 1][k], f[i][c][k]); else f[i + 1][c][k] = max(f[i + 1][c][k], f[i][c][k]); if(s[i + 1] != c1) f[i + 1][c + 1][k + 1] = max(f[i + 1][c + 1][k + 1], f[i][c][k]); if(s[i + 1] != c2) f[i + 1][c][k + 1] = max(f[i + 1][c][k + 1], f[i][c][k] + c); } } void DP2(){ memset(f, -0x3f, sizeof(f)), f[0][0][0] = 0; int c = 0; for(int i = 1; i <= n; i++){ f[i][c + (s[i] == c1)][0] = f[i - 1][c][0]; if(s[i] == c1) c++, f[i][c][0] += c - 1; } for(int k = 0; k <= d; k++) for(int c = 0; c <= n; c++) for(int i = 0; i <= n; i++){ if(s[i + 1] == c1) f[i + 1][c + 1][k] = max(f[i + 1][c + 1][k], f[i][c][k] + c); else f[i + 1][c][k] = max(f[i + 1][c][k], f[i][c][k]); if(s[i + 1] != c1) f[i + 1][c + 1][k + 1] = max(f[i + 1][c + 1][k + 1], f[i][c][k] + c); } }
signed main(){ freopen("_in.in", "r", stdin);
n = read(), d = read(), cin >> (s + 1) >> c1 >> c2; if(c1 != c2) DP1(); else DP2(); for(int x = 0; x <= n; x++) for(int k = 0; k <= d; k++) ans = max(ans, f[n][x][k]); printf("%lld", ans); }
|