#include <bits/stdc++.h>
using namespace std;
int l;
int dp[1000001][2][2];
int func(vector<char>& V) {
  l = V.size();
  int cost0 = V[l - 1] == '0' ? 0 : 1;
  int cost1 = V[l - 1] == '1' ? 0 : 1;
  dp[l - 1][0][0] = cost0;
  dp[l - 1][0][1] = cost0;
  dp[l - 1][1][0] = cost1;
  dp[l - 1][1][1] = cost1;
  for (int i = l - 2; i >= 0; i--) {
    cost0 = V[i] == '0' ? 0 : 1;
    cost1 = V[i] == '1' ? 0 : 1;
    dp[i][0][0] = cost0 + min(dp[i + 1][0][1],
                              min(dp[i + 1][1][0],
                                  min(dp[i + 1][1][1], dp[i + 1][0][0])));
    dp[i][0][1] = cost0 + dp[i + 1][0][1];
    dp[i][1][0] =
        cost1 + min(dp[i + 1][0][1], min(dp[i + 1][1][0], dp[i + 1][1][1]));
    dp[i][1][1] = cost1 + dp[i + 1][0][1];
  }
  return min(dp[0][0][1], min(dp[0][1][0], min(dp[0][1][1], dp[0][0][0])));
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int(testow);
  cin >> testow;
  while (testow--) {
    int(n), (k);
    cin >> n >> k;
    string s;
    cin >> s;
    int total = 0;
    for (auto it : s)
      if (it == '1') total++;
    if (total == 0) {
      cout << 0 << "\n";
      continue;
    }
    int ans = total - 1;
    for (int i = 0; i < k; i += 1) {
      vector<char> V;
      int cnt = 0;
      for (int j = i; j < n; j += k) {
        V.push_back(s[j]);
        if (s[j] == '1') cnt++;
      }
      int val = total - cnt;
      val += func(V);
      ans = min(ans, val);
    }
    cout << ans << "\n";
  }
  return 0;
}
