#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
const int maxn=1000000;
using namespace std;
int t,k,len,sum;
__int64 ans;
char a[maxn+10],flag[maxn+10];
int main()
{
scanf("%d",&t);
for(int h=1;h<=t;h++){
memset(flag,0,sizeof(flag));
scanf("%s%d",a,&k);
len=strlen(a);
// printf("%d\n",len);
int head=0,tail=0,sum=0;
ans=0;
for(;;){
while(head<len&&sum<k){
if(!flag[a[head]-'A']) {
sum++;
}
flag[a[head]-'A']++;
head++;
// printf("1\n");
}
if(sum<k) break;
ans+=(len-head+1);
//printf("%I64d\n",ans);
while(tail<head&&sum>=k){
if(flag[a[tail]-'A']) {
flag[a[tail]-'A']--;
if(!flag[a[tail]-'A']) sum--;
}
if(sum>=k) ans+=(len-head+1);
tail++;
}
// printf("%d\n",head);
}
printf("%I64d\n",ans);
}
return 0;
}