用dpijkl记录每个状态的子序列最大长度
i,j,k,l表示以c,h,e,f结尾的合法子序列个数
因为k<=32所以每个最多只需要记录到32
假如当前f结尾的合法子序列个数=K
那么后面的f都得删掉
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <queue>
#include <cstdio>
#include <map>
#include <set>
#include <utility>
#include <stack>
#include <cstring>
#include <cmath>
#include <vector>
#include <ctime>
#include <bitset>
using namespace std;
#define pb push_back
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define sld(n) scanf("%lld",&n)
#define sldd(n,m) scanf("%lld%lld",&n,&m)
#define slddd(n,m,k) scanf("%lld%lld%lld",&n,&m,&k)
#define sf(n) scanf("%lf",&n)
#define sff(n,m) scanf("%lf%lf",&n,&m)
#define sfff(n,m,k) scanf("%lf%lf%lf",&n,&m,&k)
#define ss(str) scanf("%s",str)
#define ansn() printf("%d\n",ans)
#define lansn() printf("%lld\n",ans)
#define r0(i,n) for(int i=0;i<(n);++i)
#define r1(i,e) for(int i=1;i<=e;++i)
#define rn(i,e) for(int i=e;i>=1;--i)
#define mst(abc,bca) memset(abc,bca,sizeof abc)
#define lowbit(a) (a&(-a))
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define pll pair<long long,long long>
#define mp(aa,bb) make_pair(aa,bb)
#define lrt rt<<1
#define rrt rt<<1|1
#define X first
#define Y second
#define PI (acos(-1.0))
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const ll mod = 1000000007 ;
const double eps=1e-9;
const int inf=0x3f3f3f3f;
const ll infl = 100000000000000000;//1e17
const int maxn= 2e5+20;
const int maxm = 3e3+20;
//muv[i]=(p-(p/i))*muv[p%i]%p;
int in(int &ret)
{
char c;
int sgn ;
if(c=getchar(),c==EOF)return -1;
while(c!='-'&&(c<'0'||c>'9'))c=getchar();
sgn = (c=='-')?-1:1;
ret = (c=='-')?0:(c-'0');
while(c=getchar(),c>='0'&&c<='9')ret = ret*10+(c-'0');
ret *=sgn;
return 1;
}
int dp[34][34][34][34];
int pre[maxn];
char s[maxn];
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif // LOCAL
int t;
sd(t);
while(t--)
{
int n,K;
sdd(n,K);
ss(s+1);
mst(dp,-1);
dp[0][0][0][0] = 0;
int ans = 0;
r1(i,n)
{
pre[i] = pre[i-1];
if(s[i]=='f')++pre[i];
}
for(int i=1; i<=n; ++i)
{
for(int q=32; q>=0; --q)
{
for(int l=32;l>=0;--l)
{
for(int k =32;k>=0;--k)
{
for(int j=32;j>=0;--j)
{
if(dp[j][k][l][q]==-1)continue;
if(s[i]=='c')
{
dp[j+1][k][l][q] = max(dp[j][k][l][q]+1,dp[j+1][k][l][q]);
// printf("%d %d %d %d\n",j+1,k,l,q);
if(q==K)ans = max(ans,dp[j+1][k][l][q]+(n-i-(pre[n]-pre[i])));
}
else if(s[i]=='h')
{
if(j+k<=32)dp[j][j+k][l][q] = max(dp[j][k][l][q]+1,dp[j][j+k][l][q]);
if(q==K)ans = max(ans,dp[j][k+j][l][q]+(n-i-(pre[n]-pre[i])));
}
else if(s[i]=='e')
{
if(k+l<=32)dp[j][k][l+k][q] = max(dp[j][k][l][q]+1,dp[j][k][l+k][q]);
if(q==K)ans = max(ans,dp[j][k][l+k][q]+(n-i-(pre[n]-pre[i])));
}
else
{
if(q+l<=32)dp[j][k][l][q+l] = max(dp[j][k][l][q]+1,dp[j][k][l][q+l]);
if(q+l==K)ans = max(ans,dp[j][k][l][q+l]+(n-i-(pre[n]-pre[i])));
}
}
}
}
}
}
if(ans==0)puts("-1");
else
{
ans = n - ans;
ansn();
}
}
return 0;
}