/**
video: https://w...content-available-to-author-only...e.com/watch?v=VBerLS1JG4E
contest: https://c...content-available-to-author-only...s.com/group/FxFJrQUeaZ/contest/527641
problem: https://c...content-available-to-author-only...s.com/group/FxFJrQUeaZ/contest/527641/problem/F
rank: https://c...content-available-to-author-only...s.com/group/FxFJrQUeaZ/contest/527641/standings/groupmates/true
profile(me): https://c...content-available-to-author-only...s.com/profile/ThanhSteve2k11 (k1ngch0m-imissmath-nguyenquangthanh)
date/school/country: (SUN/06/OCT/2024-ChuVanAnSecondarySchool-DANANG-VIETNAM)
**/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define double long double
#define FAST ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl "\n"
#define sz(s) (int)s.size()
#define gl(s) string s;getline(cin,s)
#define cin(n) int n;cin >> n
#define __lcm(a,b) a/__gcd(a,b)*b
#define fset(x) fixed << setprecision(x)
#define MOD (int)1e9+7
#define maxn (int)1e5+1
void FREOPEN(){freopen(".inp","r",stdin);freopen(".out","w",stdout);}
int cnt[255+1], pref[255+1][maxn];
bool ok(int l,int r,int k) {
// kt doan l->r co ok ko
// tinh nhanh so luong tung chu cai & kt chung co vuot qua k ko
for(int i='a';i<='z';i++) {
// dem so luong kitu i trong doan l->r
int cnt = pref[i][r] - pref[i][l-1];
if (cnt>k) return false;
}
return true;
}
void k1ngch0m() {
string s; cin >> s;
int SZ = sz(s);
s = '1'+s;// dich vi tri xau s ve 1
cin(k);
for(int i='a';i<='z';i++) {
// mang cong don cho kitu i
// pref[i][j] dung cho kitu da tinh so luong kitu i tu 1->j
for(int j=1;j<=SZ;j++) {
int x;
if (s[j]==i) x=1;
else x=0;
pref[i][j] = pref[i][j-1]+x;
}
}
// dem so cap i j sao cho tu i->j ko co kitu nao xuat hien qua k lan
int ans=0;
for(int i=1;i<=SZ;i++) {
int l=i, r=SZ, mid, pos=i-1;
while(l<=r) {
mid = (l+r)/2;
// kt doan tu i->mid co ok ko
if (ok(i,mid,k)) pos=mid, l=mid+1;
else r = mid-1;
}
ans+=pos-i+1;
}
cout << ans << endl;
// C2: binary_search + prefix_sum
}
signed main() {
/**FREOPEN();**/ FAST;
int test=1; cin >> test;
while (test--) k1ngch0m();
}