#include<bits/stdc++.h>
using namespace std;
const int N=5e3+50,inf=1e9;
int n,m,f[N][N],g[N][N],T,a[N],b[N],w1[N],w2[N],fir[3][N],t1,t2;
char s[N],t[N];
void clear()
{
for(int i=0;i<=m;i++)
for(int j=0;j<=n+m;j++)f[i][j]=g[i][j]=0;
for(int i=0;i<=m;i++)w1[i]=w2[i]=b[i]=0;
t1=t2=0;
}
int chk(int k)
{
for(int t=0;t<=m;t++)
{
int c1=t1+fir[1][t]-(t-2*(k-n));
int c2=t2+fir[2][t]-(k-n);
if(c1<0||c2<0||!g[t][c2]||f[t][c2]>c1)continue;
return 1;
}
return 0;
}
int F(int i,int j)
{
if(j>n+m||j<0)return inf;
return f[i][j];
}
void sol()
{
cin>>n>>m>>(s+1)>>(t+1);
for(int i=1;i<=n;i++)a[i]=s[i]=='B'?2:(s[i]=='Q'?1:0),t1+=a[i]==1,t2+=a[i]==2;
for(int i=1;i<=m;i++)b[i]=t[i]=='B'?2:(t[i]=='Q'?1:0),w1[i]=b[i]==1,w2[i]=b[i]==2,fir[1][i]=fir[1][i-1]+w1[i],fir[2][i]=fir[2][i-1]+w2[i];
for(int i=m-1;i>=0;i--)
{
int f1=w1[i+1],f2=w2[i+1];
for(int j=0;j<=n+m;j++)f[i][j]=min(max(1,F(i+1,j+f2)+1-f1),j?max(0,F(i+2,j-1+f2)-f1):inf);
}
g[0][t2]=1;
for(int i=0;i<m;i++)for(int j=0;j<=t2+fir[2][i];j++)if(g[i][j])
{
int c2=j,c1=t1+fir[1][i]-(i-2*(t2+fir[2][i]-j));
if(c2>0)g[min(m,i+2)][j-1+w2[i+1]+w2[i+2]]=1;if(c1>0)g[i+1][j+w2[i+1]]=1;
}
for(int k=n;k<=n+m;k++)if(chk(k)){cout<<k<<'\n';return;}
puts("IMPOSSIBLE");
}
main()
{
// freopen("in.txt","r",stdin);
cin>>T;
while(T--)sol(),clear();
}