#include<bits/stdc++.h>
#define int long long
using namespace std;
int t;
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>t;
while (t--)
{
map<char,int>b;
string s;int k;
cin>>s>>k;
int dem=0,ans=0;
for (int l=0,r=0;r<s.size();r++)
{
if (b[s[r]]==0)
{
b[s[r]]=1;
}
else b[s[r]]++;
while (b[s[r]] > k)
{
b[s[l]]--;
if (b[s[r]]==k)
{
dem--;
}
l++;
}
ans+=r-l+1;
}
cout<<ans<<"\n";
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSBpbnQgbG9uZyBsb25nCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCB0OwpzaWduZWQgbWFpbigpCnsKICAgIGlvc19iYXNlOjpzeW5jX3dpdGhfc3RkaW8oMCk7CiAgICBjaW4udGllKDApO2NvdXQudGllKDApOwogICAgY2luPj50OwogICAgd2hpbGUgKHQtLSkKICAgIHsKICAgICAgICBtYXA8Y2hhcixpbnQ+YjsKICAgICAgICBzdHJpbmcgcztpbnQgazsKICAgICAgICBjaW4+PnM+Pms7CiAgICAgICAgaW50IGRlbT0wLGFucz0wOwogICAgICAgIGZvciAoaW50IGw9MCxyPTA7cjxzLnNpemUoKTtyKyspCiAgICAgICAgewogICAgICAgICAgICBpZiAoYltzW3JdXT09MCkKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgYltzW3JdXT0xOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgYltzW3JdXSsrOwogICAgICAgICAgICB3aGlsZSAoYltzW3JdXSA+IGspCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIGJbc1tsXV0tLTsKICAgICAgICAgICAgICAgIGlmIChiW3Nbcl1dPT1rKQogICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgIGRlbS0tOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgbCsrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGFucys9ci1sKzE7CiAgICAgICAgfQogICAgICAgIGNvdXQ8PGFuczw8IlxuIjsKICAgIH0KfQo=