#define _GLIBCXX_FILESYSTEM
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")
int n,k,q;
string s;
ll f(int x) {
int now = 0, cnt = 0;
ll tot = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '?') {
if(now < x) cnt++, now++;
} else if(s[i] == 'A') cnt++;
else if(s[i] == 'B') tot += 1ll * cnt;
}
for(int i = n - 1; i >= 0; i--) {
if(s[i] == 'A') cnt--;
else if(s[i] == '?') {
if(now >= q) break;
now++;
tot += 1ll * cnt;
}
}
return tot;
}
void solve() {
cin >> n >> k >> s;
q = 0;
for(auto c: s) if(c == '?') q++;
q = min(q, k);
int l = 0, r = q, m1,m2;
ll ans = 0;
while(r - l + 1 >= 3) {
m1 = l + (r - l) / 3;
m2 = r - (r - l) / 3;
ll f1 = f(m1), f2 = f(m2);
if(f1 > f2) r = m2 - 1;
else l = m1 + 1;
}
for(int i = l; i <= r; i++) {
ans = max(ans, f(i));
}
cout << ans << '\n';
return;
}
int32_t main() {
ios_base::sync_with_stdio(false);cin.tie(NULL);
int tc = 1;
cin >> tc;
for(int kase = 1; kase <= tc; kase++) {
//cout << "Case " << kase << ": ";
solve();
}
return 0;
}