#include<bits/stdc++.h>
#define ll long long
#define f(i,n) for(int i=0;i<n;i++)
#define fr(i,a,b) for(int i=a;i<b;i++)
#define F first
#define S second
#define mp make_pair
#define pb push_back
using namespace std;
int fun(vector<int> a)
{
int size = a.size();
f(i,size)if(a[i]==0)a[i]=-1;
int max_so_far = INT_MIN, max_ending_here = 0,
start =0, end = 0, s=0;
for (int i=0; i< size; i++ )
{
max_ending_here += a[i];
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
if(max_so_far>0){
int sum = 0;
f(i,size){
if(i>=start and i<=end){
if(a[i]==-1)sum++;
}else{
if(a[i]==1)sum++;
}
}
return sum;
}else
return 0;
}
void test(){
ll n,k;
cin>>n>>k;
string s;
cin>>s;
int total = 0;
f(i,n){
total = total + (s[i]-'0');
}
ll ans = n;
int index = -1;
for(int i=k-1;i>=0;i--){
vector<int> v;
int temp=0;
for(int j=n-(k-i);j>=0;j=j-k){
v.pb(s[j]-'0');
temp = temp + (s[j]-'0');
}
ll cal = total-temp;
cal = cal + fun(v);
ans = min(ans,cal);
}
cout<<ans<<"\n";
}
int main(){
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t=1;
cin>>t;
while(t--){
test();
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSBsbCBsb25nIGxvbmcgCiNkZWZpbmUgZihpLG4pIGZvcihpbnQgaT0wO2k8bjtpKyspIAojZGVmaW5lIGZyKGksYSxiKSBmb3IoaW50IGk9YTtpPGI7aSsrKSAKI2RlZmluZSBGIGZpcnN0IAojZGVmaW5lIFMgc2Vjb25kIAojZGVmaW5lIG1wIG1ha2VfcGFpciAKI2RlZmluZSBwYiBwdXNoX2JhY2sgCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKaW50IGZ1bih2ZWN0b3I8aW50PiBhKSAKeyAKCglpbnQgc2l6ZSA9IGEuc2l6ZSgpOwogICAgZihpLHNpemUpaWYoYVtpXT09MClhW2ldPS0xOwoJaW50IG1heF9zb19mYXIgPSBJTlRfTUlOLCBtYXhfZW5kaW5nX2hlcmUgPSAwLCAKICAgICAgIHN0YXJ0ID0wLCBlbmQgPSAwLCBzPTA7IAogIAogICAgZm9yIChpbnQgaT0wOyBpPCBzaXplOyBpKysgKSAKICAgIHsgCiAgICAgICAgbWF4X2VuZGluZ19oZXJlICs9IGFbaV07IAogIAogICAgICAgIGlmIChtYXhfc29fZmFyIDwgbWF4X2VuZGluZ19oZXJlKSAKICAgICAgICB7IAogICAgICAgICAgICBtYXhfc29fZmFyID0gbWF4X2VuZGluZ19oZXJlOyAKICAgICAgICAgICAgc3RhcnQgPSBzOyAKICAgICAgICAgICAgZW5kID0gaTsgCiAgICAgICAgfSAKICAKICAgICAgICBpZiAobWF4X2VuZGluZ19oZXJlIDwgMCkgCiAgICAgICAgeyAKICAgICAgICAgICAgbWF4X2VuZGluZ19oZXJlID0gMDsgCiAgICAgICAgICAgIHMgPSBpICsgMTsgCiAgICAgICAgfSAKICAgIH0gCiAgICBpZihtYXhfc29fZmFyPjApewogICAgCWludCBzdW0gPSAwOwogICAgCWYoaSxzaXplKXsKICAgIAkJaWYoaT49c3RhcnQgYW5kIGk8PWVuZCl7CiAgICAJCQlpZihhW2ldPT0tMSlzdW0rKzsKCQkJfWVsc2V7CgkJCQlpZihhW2ldPT0xKXN1bSsrOwoJCQl9CgkJfQoJCXJldHVybiBzdW07Cgl9ZWxzZQoJCXJldHVybiAwOyAKfSAKCgoKdm9pZCB0ZXN0KCl7CglsbCBuLGs7CgljaW4+Pm4+Pms7CglzdHJpbmcgczsKCWNpbj4+czsKCQoJaW50IHRvdGFsID0gMDsKCWYoaSxuKXsKCQl0b3RhbCA9IHRvdGFsICsgKHNbaV0tJzAnKTsKCX0KCWxsIGFucyA9IG47CglpbnQgaW5kZXggPSAtMTsKCWZvcihpbnQgaT1rLTE7aT49MDtpLS0pewoJCXZlY3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