#include<bits/stdc++.h>
#define MOD 1000000007
#define MAX 100005
#define ll long long
#define slld(t) scanf("%lld",&t)
#define sd(t) scanf("%d",&t)
#define pd(t) printf("%d\n",t)
#define plld(t) printf("%lld\n",t)
#define pcc pair<char,char>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define tr(container,it) for(typeof(container.begin()) it=container.begin();it!=container.end();it++)
#define mp(a,b) make_pair(a,b)
#define FF first
#define SS second
#define pb(x) push_back(x)
#define vi vector<int>
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
char s[MAX];
vi curr;
int a[28];
int main(){
int t;
sd(t);
while(t--){
scanf("%s",s);
int k;sd(k);
clr(a);
int l=strlen(s);
for(int i=0;i<l;i++){
a[s[i]-'a']++;
}
curr.clear();
for(int i=0;i<28;i++){
if(a[i]) curr.pb(a[i]);
}
sort(curr.begin(),curr.end());
int ans=MOD;
for(int i=0;i<curr.size();i++){
int mn=curr[i];
int now=0;
for(int j=0;j<i;j++){
now+=curr[j];
}
for(int j=i+1;j<curr.size();j++){
if(curr[j]>mn+k){
now+=curr[j]-(mn+k);
}
}
ans=min(ans,now);
}
pd(ans);
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KCiNkZWZpbmUgTU9EIDEwMDAwMDAwMDcKI2RlZmluZSBNQVggMTAwMDA1CiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgc2xsZCh0KSBzY2FuZigiJWxsZCIsJnQpCiNkZWZpbmUgc2QodCkgc2NhbmYoIiVkIiwmdCkKI2RlZmluZSBwZCh0KSBwcmludGYoIiVkXG4iLHQpCiNkZWZpbmUgcGxsZCh0KSBwcmludGYoIiVsbGRcbiIsdCkKI2RlZmluZSBwY2MgcGFpcjxjaGFyLGNoYXI+CiNkZWZpbmUgcGlpIHBhaXI8aW50LGludD4KI2RlZmluZSBwbGwgcGFpcjxsbCxsbD4KI2RlZmluZSB0cihjb250YWluZXIsaXQpIGZvcih0eXBlb2YoY29udGFpbmVyLmJlZ2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