#include <bits/stdc++.h>
using namespace std;
vector<int> v[1000010];
int n, k;
string s;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> k >> s;
    int ss = 0;
    for (int i = 0, j = 0; i < n; i++, j++) {
      if (j == k) j = 0;
      if (s[i] == '1') {
        v[j].push_back(i / k);
        ss++;
      }
    }
    int mii = 1000000000;
    for (int i = 0; i < k; i++) {
      int tot = v[i].size();
      int ans = 1000000000, an = 1000000000;
      for (int j = tot - 1; j >= 0; j--) {
        int curr = v[i][j] - 2 * j;
        ans = min(ans, curr);
        an = min(tot + ans - curr - 2, an);
      }
      if (an != 1000000000) mii = min(mii, ss - tot + an);
      v[i].clear();
    }
    if (mii == 1000000000) mii = -1;
    cout << mii + 1 << '\n';
  }
  return 0;
}
