You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$.

In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).

The garland is called $k$-periodic if the distance between each pair of adjacent turned on lamps is exactly $k$. Consider the case $k=3$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.

Your task is to find the minimum number of moves you need to make to obtain $k$-periodic garland from the given one.

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 25~ 000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 10^6; 1 \le k \le n$) — the length of $s$ and the required period. The second line of the test case contains the string $s$ consisting of $n$ characters '0' and '1'.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$ ($\sum n \le 10^6$).


-----Output-----

For each test case, print the answer — the minimum number of moves you need to make to obtain $k$-periodic garland from the given one.


-----Example-----
Input
6
9 2
010001010
9 3
111100000
7 4
1111111
10 3
1001110101
1 1
1
1 1
0

Output
1
2
5
4
0
0

Difficulty: HARD
Tags: Dynamic programming

Complete search

Greedy algorithms
Skill types: Dynamic programming

Complete search

Greedy algorithms

Starter code:

Solutions:
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ones = s.count('1')
	ans = ones
	for i in range(k):
		pre = 0
		for j in range(i, n, k):
			if s[j] == '1':
				pre += 1
			else:
				pre -= 1
			pre = max(pre, 0)
			ans = min(ans, ones - pre)
	print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	s = stdin.readline()
	x = s.count('1')
	ans = x
	for i in range(k):
		arr = [(int(s[i]) ^ 1) - (int(s[i]) ^ 0)]
		for j in range(i + k, n, k):
			y = int(s[j])
			arr.append(arr[-1] + (y ^ 1) - (y ^ 0))
		mini = 10 ** 10
		max_so_far = su = 0
		for b in arr:
			mini = min(mini, b - max_so_far)
			max_so_far = max(max_so_far, b)
		ans = min(ans, mini + x)
	print(ans)


def car():
	for i in range(int(input())):
		(n, k) = map(int, input().split())
		s = input().strip()
		c1 = s.count('1')
		ans = n
		for i in range(k):
			su = 0
			for j in range(i, n, k):
				if s[j] == '1':
					su += 1
				else:
					su -= 1
					su = max(0, su)
				ans = min(ans, c1 - su)
		print(ans)
car()


import sys
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	s = list(input())
	al = s.count(49)
	res = al
	p = [0] * n
	ctr = 0
	for i in range(n):
		if i - k >= 0 and s[i - k] == 49:
			ctr -= 1
		p[i] = ctr
		if s[i] == 49:
			ctr += 1
	dp = [0] * n
	c = 0
	for i in range(n):
		if s[i] == 49:
			if i >= k:
				tmp = min(c, dp[i - k] + p[i])
			else:
				tmp = c
			c += 1
		else:
			tmp = 1
			if i >= k:
				tmp += min(c, dp[i - k] + p[i])
			else:
				tmp += c
		dp[i] = tmp
		res = min(res, dp[i] + (al - c))
	print(res)


t = int(input())
for i in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = [int(x) for x in list(input())]
	ln = len(s)
	mp = ln
	for j in range(k):
		(sm, mn, md) = (0, 0, 0)
		for c in range(j, ln, k):
			sm += 2 * s[c] - 1
			if sm <= mn:
				mn = sm
			if sm - mn > md:
				md = sm - mn
		mp = min(mp, -md)
	print(sum(s) + mp)


import sys
import os
import heapq
try:
	path = './file/input.txt'
	if os.path.exists(path):
		sys.stdin = open(path, 'r')
except:
	pass
t = int(input())

def printd(value):
	pass
for _ in range(t):
	arr = list(map(int, input().split(' ')))
	(n, k) = (arr[0], arr[1])
	str = input()
	count = len(str)
	leftone = [0] * count
	leftzero = [0] * count
	rightone = [0] * count
	rightzero = [0] * count
	one = [0] * count
	sum = 0
	for (i, c) in enumerate(str):
		if i > 0:
			sum += 1 if str[i - 1] == '1' else 0
		if i >= k:
			sum -= 1 if str[i - k] == '1' else 0
		one[i] = sum
	printd(str)
	printd(one)
	for (i, c) in enumerate(str):
		number = 1 if c == '0' else 0
		numberzero = 0 if c == '0' else 1
		if i >= k:
			number += min(leftone[i - k], leftzero[i - k])
			numberzero += leftzero[i - k]
		leftone[i] = one[i] + number
		leftzero[i] = one[i] + numberzero
	printd(leftone)
	printd(leftzero)
	printd('--right---')
	str = str[::-1]
	sum = 0
	for (i, c) in enumerate(str):
		if i > 0:
			sum += 1 if str[i - 1] == '1' else 0
		if i >= k:
			sum -= 1 if str[i - k] == '1' else 0
		one[i] = sum
	printd(str)
	printd(one)
	for (i, c) in enumerate(str):
		number = 1 if c == '0' else 0
		numberzero = 0 if c == '0' else 1
		if i >= k:
			number += min(rightone[i - k], rightzero[i - k])
			numberzero += rightzero[i - k]
		rightone[i] = one[i] + number
		rightzero[i] = one[i] + numberzero
	printd(rightone)
	printd(rightzero)
	leftone.reverse()
	leftzero.reverse()
	result = 99999999
	for (i, c) in enumerate(str):
		value = leftone[i] + rightone[i]
		value -= 1 if c == '0' else 0
		result = min(result, value)
		value = leftzero[i] + rightzero[i]
		value -= 0 if c == '0' else 1
		result = min(result, value)
	print(result)


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	k -= 1
	s = input()
	pref = []
	cnt = 0
	for c in s:
		if c == '1':
			cnt += 1
		pref.append(cnt)
	out = [0] * n
	for i in range(n - 2, -1, -1):
		if s[i] == '0':
			a = pref[n - 1] - pref[i]
			if i + k + 1 < n:
				b = 1 + pref[i + k] - pref[i] + out[i + k + 1]
			else:
				b = 1 + pref[n - 1] - pref[i]
			out[i] = min(a, b)
		else:
			if i + k + 1 < n:
				a = pref[i + k] - pref[i] + out[i + k + 1]
			else:
				a = pref[n - 1] - pref[i]
			b = 1 + pref[n - 1] - pref[i]
			out[i] = min(a, b)
	for i in range(1, n):
		out[i] = out[i] + pref[i - 1]
	print(min(out))


import sys
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def read():
	tc = 0
	if tc:
		input = sys.stdin.readline
	else:
		sys.stdin = open('input1.txt', 'r')
		sys.stdout = open('output1.txt', 'w')

def solve():
	for _ in range(ii()):
		(n, k) = mi()
		s = si()
		s = list(s)
		once = s.count('1')
		ans = once
		for i in range(k):
			diff = 0
			for j in range(i, n, k):
				if s[j] == '1':
					diff += 1
				else:
					diff -= 1
				if diff < 0:
					diff = 0
				ans = min(ans, once - diff)
		print(ans)
solve()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
nw = int(input())
for ik in range(nw):
	(n, k) = map(int, input().split())
	s = list(input())
	s = [int(s[i]) for i in range(n)]
	s1 = [0] * (n + 1)
	for i in range(1, n + 1):
		s1[i] = s1[i - 1] + s[i - 1]
	dp = [[0 for i in range(3)] for j in range(n)]
	for i in range(k):
		dp[i][1] = 1 - s[i] + s1[i] - s1[0]
		dp[i][0] = s[i] + s1[i] - s1[0]
		dp[i][2] = dp[i - 1][2] + s[i]
	for i in range(k, n):
		dp[i][1] = min(dp[i - k][1], dp[i - k][2]) + s1[i] - s1[i - k + 1] + (1 - s[i])
		dp[i][0] = min(dp[i - k][0], dp[i - k][1]) + s1[i] - s1[i - k + 1] + s[i]
		dp[i][2] = dp[i - 1][2] + s[i]
	ans = s1[n] - s1[0]
	for i in range(n):
		ans = min(ans, min(dp[i]) + s1[n] - s1[i + 1])
	print(ans)


import sys
input = sys.stdin.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input().strip())):
		(n, k) = map(int, input().split())
		garland = input().strip()
		modi = []
		for i in range(k):
			summ = [0]
			for j in range(i, n, k):
				summ.append((garland[j] == '1') + summ[-1])
			modi.append(summ)
		total = sum([val[-1] for val in modi])
		modchanges = []
		for mod in modi:
			i_mins = [mod[-1]]
			for i in range(1, len(mod)):
				i_mins.append(min(i_mins[-1] - (mod[i] - mod[i - 1] == 1) + (mod[i] - mod[i - 1] == 0), mod[-1] - (mod[i] - mod[i - 1] == 1)))
			modchanges.append(min(i_mins) + total - mod[-1])
		print(min(modchanges))
prog()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	pre = [0] * n
	if s[0] == '1':
		pre[0] = 1
	for i in range(1, n):
		pre[i] = pre[i - 1]
		if s[i] == '1':
			pre[i] += 1
	dp = [0] * n
	dp1 = [0] * n
	for i in range(k):
		atleast = 0
		count = 0
		for j in range(i, n, k):
			if s[j] == '1':
				count += 1
		atleast += pre[n - 1] - count
		count = 0
		for j in range(i, n, k):
			if j >= k:
				if s[j] == '0':
					dp[j] += 1
				dp[j] += atleast + min(dp[j - k], count)
			elif s[j] == '0':
				dp[j] = atleast + 1
			else:
				dp[j] = atleast
			if s[j] == '1':
				count += 1
			last = j
		count = 0
		for j in range(last, -1, -k):
			if j + k < n:
				dp1[j] = dp1[j + k]
				if s[j + k] == '0':
					dp1[j] += 1
				dp1[j] = min(dp1[j], count)
			if s[j] == '1':
				count += 1
	fa = pre[n - 1]
	for i in range(n):
		fa = min(fa, dp[i] + dp1[i])
	print(fa)


import sys
strs = iter(sys.stdin.read().split())
ints = (int(x) for x in strs)
sys.setrecursionlimit(3000)

def main():
	ntc = next(ints)
	for tc in range(1, ntc + 1):
		(n, k) = (next(ints) for i in range(2))
		s = next(strs)
		R = (n + k - 1) // k
		m = [[int(i * k + j < n and s[i * k + j] == '1') for i in range(R)] for j in range(k)]
		s = [sum(m[j]) for j in range(k)]
		s_sum = sum(s)
		ans = [0] * k
		for j in range(k):
			off = [0] * (R + 1)
			on = [0] * (R + 1)
			for i in range(R - 1, -1, -1):
				off[i] = m[j][i] + off[i + 1]
				on[i] = 1 - m[j][i] + min(on[i + 1], off[i + 1])
			for i in range(R + 1):
				off[i] = (i and off[i - 1]) + (i < R and m[j][i])
				on[i] = on[i] + (i and off[i - 1])
			ans[j] = s_sum - s[j] + min(on)
		print(min(ans))
	return
main()


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = input()
	(ans, count, total) = (0, 0, 0)
	for i in range(k):
		count = 0
		for j in range(i, n, k):
			if a[j] == '1':
				count += 1
				total += 1
			else:
				count -= 1
				if count < 0:
					count = 0
			ans = max(ans, count)
	print(total - ans)


import sys
readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	(n, k) = nm()
	s = list(map(int, list(ns())))
	w = sum(s)
	sc = n
	for i in range(k):
		t = s[i::k]
		m = len(t)
		dp = [[0] * 3 for j in range(m + 1)]
		for j in range(m):
			dp[j + 1][0] = dp[j][0] + t[j]
			dp[j + 1][1] = min(dp[j][0], dp[j][1]) + 1 - t[j]
			dp[j + 1][2] = min(dp[j][1], dp[j][2]) + t[j]
		sc = min(sc, min(dp[m]) + w - sum(t))
	print(sc)
	return
T = ni()
for _ in range(T):
	solve()


t = int(input())
answers = []
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	vals = [0 if i == '0' else 1 for i in s]
	total_on = sum(vals)
	ans = n
	for j in range(k):
		counter = j
		sub_arr = []
		while counter < n:
			sub_arr.append(vals[counter])
			counter += k
		last = sub_arr[0]
		already_on = sum(sub_arr)
		compulsory = total_on - already_on
		if compulsory > ans:
			continue
		num_lamps = len(sub_arr)
		sub_sub_arr = []
		s = 0
		mult = 1 if last == 1 else -1
		for i in range(len(sub_arr)):
			if last == sub_arr[i]:
				s += 1
			else:
				sub_sub_arr.append(mult * s)
				mult = -1 * mult
				s = 1
			if i == len(sub_arr) - 1:
				sub_sub_arr.append(mult * s)
			last = sub_arr[i]
		curr_best = 0
		best = 0
		for i in range(len(sub_sub_arr)):
			if sub_sub_arr[i] > 0:
				curr_best += sub_sub_arr[i]
			else:
				el = sub_sub_arr[i]
				if curr_best + el < 0:
					curr_best = 0
				else:
					curr_best = curr_best + el
			best = max(curr_best, best)
		option = min(num_lamps - already_on, already_on, already_on - best)
		ans = min(compulsory + option, ans)
	answers.append(ans)
print(*answers, sep='\n')


for u in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	m = 0
	c = 0
	total = 0
	for i in range(k):
		c = 0
		for j in range(i, n, k):
			if s[j] == '1':
				c += 1
				total += 1
			else:
				c -= 1
				if c < 0:
					c = 0
			m = max(c, m)
	print(total - m)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ar = input()
	xx = ar.count('1')
	ans = xx
	for i in range(k):
		score = 0
		for j in range(i, n, k):
			if ar[j] == '1':
				score += 1
			else:
				score -= 1
			score = max(score, 0)
			ans = min(ans, xx - score)
	print(ans)


from sys import stdin
from collections import Counter, deque
from heapq import heappush, heappop
from itertools import product
input = stdin.buffer.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	lp = str(input())[2:n + 2]

	def get_dp(p, sz):
		(a0, a1) = ([0] * sz, [0] * sz)
		for i in range(sz):
			a0[i] = (a0[i - 1] if i > 0 else 0) + (p[i] != '0')
			a1[i] = (min(a0[i - 1], a1[i - 1]) if i > 0 else 0) + (p[i] != '1')
		return (a0, a1)

	def get_min(p):
		sz = len(p)
		(a0, a1) = get_dp(p, sz)
		(b0, b1) = get_dp(p[::-1], sz)
		(b0, b1) = (b0[::-1], b1[::-1])
		mn = sz
		for i in range(sz + 1):
			lv = min(a0[i - 1], a1[i - 1]) if i > 0 else 0
			rv = min(b0[i], b1[i]) if i < sz else 0
			mn = min(mn, lv + rv)
		return mn
	sm = lp.count('1')
	mn = sm
	for i in range(k):
		tp = [lp[j] for j in range(i, n, k)]
		p = ''.join(tp)
		tmn = sm - p.count('1') + get_min(p)
		mn = min(mn, tmn)
	print(mn)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	ar = input()
	s = 0
	pre = []
	dp = [0 for i in range(n)]
	for i in range(n):
		pre.append(s + int(ar[i]))
		s += int(ar[i])
	for i in range(n - 1, -1, -1):
		if i > n - k - 1:
			dp[i] = pre[n - 1] - pre[i]
		else:
			dp[i] = min(pre[n - 1] - pre[i] + int(ar[i]), pre[i + k - 1] - pre[i] + 1 - int(ar[i]) + dp[i + k])
	ans = dp[0]
	for i in range(1, n):
		ans = min(ans, dp[i] + pre[i - 1])
	print(ans)


import math
from sys import stdin, stdout
from heapq import heapify, heappop, heappush
from collections import Counter
T = int(stdin.readline())
for i in range(T):
	(N, K) = list(map(int, stdin.readline().split()))
	s = stdin.readline()
	s = list(s[:-1])
	pre = [0] * N
	pre[0] = ord(s[0]) - ord('0')
	for i in range(1, N):
		pre[i] += pre[i - 1] + ord(s[i]) - ord('0')
	ans = pre[-1]
	dp = [0] * N
	for r in range(N - 1, -1, -1):
		cnt1 = 0
		cnt2 = 0
		if r:
			cnt1 = pre[-1] - pre[r - 1]
		else:
			cnt1 = pre[-1]
		pos = min(r + K - 1, N - 1)
		cnt2 = pre[pos] - pre[r]
		if s[r] == '0':
			cnt2 += 1
		if r + K < N:
			dp[r] = min(cnt1, cnt2 + dp[r + K])
		else:
			dp[r] = min(cnt1, cnt2)
	for i in range(1, N):
		dp[i] += pre[i - 1]
	print(min(dp))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	cnt = s.count('1')
	ans = cnt
	for i in range(k):
		cur = 0
		for j in range(i, len(s), k):
			if s[j] == '1':
				cur += 1
			else:
				cur -= 1
			cur = max(0, cur)
			ans = min(ans, cnt - cur)
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ones = s.count('1')
	best = 0
	for i in range(k):
		count = 0
		for j in range(i, n, k):
			if s[j] == '1':
				count += 1
			else:
				count = max(0, count - 1)
			best = max(count, best)
	print(ones - best)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		(n, k) = [int(x) for x in input().split()]
		s = input()
		(ps, l) = ([0] * n, 0)
		for i in range(n):
			if s[i] == '1':
				l += 1
			ps[i] = l
		dp = [0] * n
		for i in range(n - 1, -1, -1):
			change100 = 1 if s[i] == '0' else 0
			if i + k < n:
				change100 += ps[i + k - 1] - ps[i]
			else:
				change100 += ps[n - 1] - ps[i]
			if i + k < n:
				change100 += dp[i + k]
			change000 = ps[n - 1] - ps[i] + (1 if s[i] == '1' else 0)
			dp[i] = min(change100, change000)
		minn = 9999999
		for i in range(n):
			minn = min(minn, dp[i] + ps[i] - (1 if s[i] == '1' else 0))
		print(minn)
	t = int(input())
	for i in range(t):
		solve()
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(input().rstrip())
	tt = [[] for i in range(k)]
	for i in range(n):
		tt[i % k].append(s[i])
	ans = 10 ** 9
	cnt1 = s.count('1')
	for i in range(k):
		t = tt[i]
		else_res = cnt1 - t.count('1')
		all_t_cnt1 = t.count('1')
		partial_ans = t.count('1')
		dp = [0] * len(t)
		pre = 0
		for j in range(len(t)):
			cur_stand = t[j] == '1'
			pre += cur_stand
			dp[j] = 1 - cur_stand
			if j > 0:
				dp[j] += min(dp[j - 1], pre - cur_stand)
			partial_ans = min(partial_ans, dp[j] + all_t_cnt1 - pre)
		ans = min(ans, else_res + partial_ans)
	print(ans)


import sys

def solve_clear(values: str, n: int, k: int) -> int:
	prefix_sums = [0]
	cur_sum = 0
	for v in values:
		if v == '1':
			cur_sum += 1
		prefix_sums.append(cur_sum)
	for _ in range(k):
		prefix_sums.append(cur_sum)
	dp = [0] * (n + k)
	for i in range(n - 1, -1, -1):
		dp[i] = min(prefix_sums[n] - prefix_sums[i + 1], (values[i] == '0') + prefix_sums[i + k] - prefix_sums[i + 1] + dp[i + k])
	return min((p + d for (p, d) in zip(prefix_sums, dp)))

def solve(values: str, n: int, k: int) -> int:
	dp = [0] * n
	total_ones = values.count('1')
	prefix_sums = [total_ones] * (n + 1)
	cur_sum = total_ones
	result = n
	for i in range(n - 1, -1, -1):
		cost_to_one = values[i] != '1'
		if not cost_to_one:
			cur_sum -= 1
		prefix_sums[i] = cur_sum
		dp[i] = prefix_sums[n] - prefix_sums[i + 1]
		if i + k < n:
			tmp = cost_to_one + prefix_sums[i + k] - prefix_sums[i + 1] + dp[i + k]
			if dp[i] > tmp:
				dp[i] = tmp
		ans = dp[i] + cur_sum
		if ans < result:
			result = ans
	return result

def do_job():
	T = int(input())
	for _testcase in range(T):
		(n, k) = map(int, input().split())
		values = input()
		result = solve(values, n, k)
		print(result)
	sys.stdout.flush()
do_job()


t = int(input())
while t > 0:
	t -= 1
	(n, k) = map(int, input().split())
	i = 1
	s = list(input())
	total = s.count('1')
	ans = total
	for x in range(k):
		dif = 0
		for y in range(x, n, k):
			if s[y] == '1':
				dif += 1
			else:
				dif -= 1
			dif = max(0, dif)
			ans = min(ans, total - dif)
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(map(int, list(input().strip())))
	dp = [[0, 0] for i in range(n)]
	dp[0] = [s[0], 1 - s[0]]
	p = [s[0]]
	for i in range(1, n):
		p.append(p[-1] + s[i])
	for i in range(1, n):
		dp[i][0] = s[i] + min(dp[i - 1])
		if i - k < 0:
			dp[i][1] = 1 - s[i] + p[i - 1]
		else:
			dp[i][1] = 1 - s[i] + min(dp[i - k][1] + p[i - 1] - p[i - k], p[i - 1])
	print(min(dp[-1]))


from sys import stdin, stdout
import sys
from math import *

def c(s, ar, k):
	ans = [0] * len(s)
	for i in range(len(s)):
		if i < k:
			if s[i] == '1':
				if i > 0:
					ans[i] = ar[i - 1]
			elif i == 0:
				ans[i] = 1
			else:
				ans[i] = 1 + ar[i - 1]
		elif s[i] == '1':
			ans[i] = min(ar[i - 1], ar[i - 1] - ar[i - k] + ans[i - k])
		else:
			ans[i] = min(ar[i - 1], ar[i - 1] - ar[i - k] + ans[i - k]) + 1
	return ans
for __ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ar1 = [0] * n
	ar2 = [0] * n
	for i in range(n):
		if i == 0:
			if s[i] == '1':
				ar1[i] = 1
		elif s[i] == '1':
			ar1[i] = ar1[i - 1] + 1
		else:
			ar1[i] = ar1[i - 1]
	for i in range(n - 1, -1, -1):
		if i == n - 1:
			if s[i] == '1':
				ar2[i] = 1
		elif s[i] == '1':
			ar2[i] = ar2[i + 1] + 1
		else:
			ar2[i] = ar2[i + 1]
	a = c(s, ar1, k)
	s = s[::-1]
	ar2 = ar2[::-1]
	b = c(s, ar2, k)
	b = b[::-1]
	s = s[::-1]
	ans = s.count('1')
	for i in range(n):
		if s[i] == '1':
			ans = min(ans, a[i] + b[i])
		else:
			ans = min(ans, a[i] + b[i] - 1)
	print(ans)


from math import gcd

def solve():
	(n, k) = map(int, input().split())
	s = input()
	oncnt = [0] * (n + 1)
	for i in range(1, n):
		oncnt[i] = oncnt[i - 1]
		if s[i - 1] == '1':
			oncnt[i] += 1
	anson = [0] * n
	ansoff = [0] * n
	ansoff[0] = int(s[0])
	anson[0] = (int(s[0]) + 1) % 2
	for i in range(1, len(s)):
		ansoff[i] = min(anson[i - 1], ansoff[i - 1])
		if s[i] == '1':
			ansoff[i] += 1
		on = oncnt[i]
		if i - k + 1 > -1:
			on -= oncnt[i - k + 1]
		if i - k > -1:
			anson[i] = anson[i - k] + on
		else:
			anson[i] = on
		if s[i] == '0':
			anson[i] += 1
		on2 = oncnt[i]
		if s[i] == '0':
			on2 += 1
		anson[i] = min(anson[i], on2)
	print(min(ansoff[n - 1], anson[n - 1]))
n = int(input())
for _ in range(n):
	solve()


from sys import stdin
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
hg = lambda x, y: (y + x - 1) // x * x
for _ in range(I()):
	(n, k) = R()
	s = S()
	m = t = 0
	for i in range(k):
		c = 0
		for j in range(i, n, k):
			if s[j] == '1':
				c += 1
				t += 1
			else:
				c -= 1
				if c < 0:
					c = 0
			m = max(m, c)
	print(t - m)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	(n, k) = rl()
	S = input()
	zero_blocks = dd(int)
	cost_all_zeros = 0
	rem = 0
	for (i, c) in enumerate(S):
		if c == '1':
			cost_all_zeros += 1
			zero_blocks[rem] += 1
		rem += 1
		if rem == k:
			rem = 0
	global_best = n
	for offset in range(k):
		zero_others = cost_all_zeros - zero_blocks[offset]
		(pre, mid, post) = (0, n, n)
		for i in range(offset, n, k):
			if S[i] == '1':
				new_pre = pre + 1
				new_mid = min(mid, pre)
				new_post = min(post + 1, mid + 1)
			else:
				new_pre = pre
				new_mid = min(mid + 1, pre + 1)
				new_post = min(post, mid)
			(pre, mid, post) = (new_pre, new_mid, new_post)
		best = min(pre, mid, post)
		global_best = min(global_best, best + zero_others)
	print(global_best)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


t = int(input())
for _ in range(0, t):
	(n, k) = map(int, input().split())
	s = input()
	arr = [[] for i in range(0, k)]
	for i in range(0, n):
		if s[i] == '1':
			arr[i % k].append(1)
		else:
			arr[i % k].append(-1)
	ans = -10 ** 9 + 7
	for i in range(0, k):
		ss = 0
		for j in range(0, len(arr[i])):
			ss += arr[i][j]
			ss = max(0, ss)
			ans = max(ans, ss)
		ans = max(ans, ss)
	print(s.count('1') - ans)


import math

def ri():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def inp():
	return int(input())

def si():
	return input()

def pYes():
	print('YES')

def pNo():
	print('NO')

def plist(l):
	print(''.join(l))
t = int(input())
for t1 in range(t):
	(n, k) = ri()
	s = input()
	cnt = 0
	res = 0
	for i in range(k):
		a = 0
		for j in range(i, n, k):
			if s[j] == '1':
				cnt += 1
				a = a + 1
			else:
				a = a - 1
			a = max(a, 0)
			res = max(res, a)
	print(cnt - res)


import sys

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		(n, k) = MI()
		s = SI()
		cnt1 = [0] * k
		aaa = [[] for _ in range(k)]
		for (i, c) in enumerate(s):
			cnt1[i % k] += int(c)
			aaa[i % k].append(int(c))
		tot = sum(cnt1)
		ans = tot
		for m in range(k):
			aa = aaa[m]
			if not aa:
				continue
			n = len(aa)
			cs = [0]
			L = [0]
			for a in aa:
				cs.append(cs[-1] + 1 - a)
				L.append(L[-1] + a)
			R = [0] * (n + 1)
			for i in range(n - 1, -1, -1):
				R[i] = R[i + 1] + aa[i]
			inf = 10 ** 9
			Lmin = [inf] * (n + 1)
			for i in range(n + 1):
				Lmin[i] = min(Lmin[i - 1], L[i] - cs[i])
			Rmin = [inf] * (n + 1)
			Rmin[n] = cs[n] + R[n]
			for i in range(n - 1, -1, -1):
				Rmin[i] = min(Rmin[i + 1], R[i] + cs[i])
			cur = min((Lmin[i] + Rmin[i + 1] for i in range(n))) + tot - cnt1[m]
			if cur < ans:
				ans = cur
		print(ans)
main()


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, K, S):
	allCount = S.count('1')
	if allCount <= 1:
		return 0
	best = allCount - 1
	for kStart in range(K):
		indices = []
		for i in range(kStart, N, K):
			if S[i] == '1':
				indices.append(i)
		otherCost = allCount - len(indices)
		myCost = 0
		if len(indices) > 1:
			bestMyCost = float('inf')
			keep = [indices[0]]
			onesSeen = 1
			for i in indices[1:]:
				dropBackCost = len(indices) - onesSeen
				bestMyCost = min(bestMyCost, myCost + dropBackCost)
				fillCost = myCost + (i - keep[-1]) // K - 1
				dropCost = onesSeen
				if fillCost < dropCost:
					myCost += (i - keep[-1]) // K - 1
					keep.append(i)
				else:
					myCost = dropCost
					keep = [i]
				onesSeen += 1
			myCost = min(myCost, bestMyCost)
		cost = otherCost + myCost
		best = min(best, cost)
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, K) = [int(x) for x in input().split()]
	S = input().decode().rstrip()
	ans = solve(N, K, S)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		(n, k) = RL()
		arr = list(input())
		num = arr.count('1')
		res = num
		for i in range(k):
			now = 0
			for j in range(i, n, k):
				if arr[j] == '1':
					now += 1
				else:
					now = max(0, now - 1)
				res = min(res, num - now)
		print(res)
main()


a = int(input())
for i in range(a):
	(n, k) = map(int, input().split())
	s = input()
	ans = []
	for i in range(len(s)):
		ans.append(int(s[i]))
	prefix = []
	for i in range(len(ans)):
		prefix.append(ans[i])
	for i in range(len(ans) - 2, -1, -1):
		ans[i] += ans[i + 1]
	dp = [0 for i in range(len(s))]
	for i in range(1, len(prefix)):
		prefix[i] += prefix[i - 1]
	for i in range(len(s)):
		if i < k:
			dp[i] = prefix[i]
			if s[i] == '1':
				dp[i] -= 1
		else:
			zeros = prefix[i - 1] - prefix[i - k]
			dp[i] = min(dp[i - k] + int(s[i] == '0') + zeros, prefix[i] - int(s[i] == '1'))
	for i in range(len(dp)):
		dp[i] += ans[i]
		if s[i] == '1':
			dp[i] -= 1
	print(min(min(dp), prefix[-1]))


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	prefix = [0]
	for i in range(1, n + 1):
		prefix.append(prefix[i - 1] + int(s[i - 1]))
	dp = [0] * n
	for i in range(n - 1, -1, -1):
		if s[i] == '1':
			if i + k < n:
				dp[i] = min(prefix[n] - prefix[i + 1] + 1, dp[i + k] + prefix[i + k] - prefix[i + 1])
			else:
				dp[i] = prefix[n] - prefix[i + 1]
		elif i + k < n:
			dp[i] = min(dp[i + k] + prefix[i + k] - prefix[i + 1] + 1, prefix[n] - prefix[i + 1])
		else:
			dp[i] = prefix[n] - prefix[i + 1]
	mini = inf
	s = 0
	for i in range(n):
		s = dp[i]
		s += prefix[i]
		mini = min(s, mini)
	print(mini)


import sys
import math
t = int(sys.stdin.readline())
for i in range(t):
	(n, k) = map(int, sys.stdin.readline().split())
	s = input()
	cnt = s.count('1')
	ans = cnt
	for i in range(k):
		cur = 0
		for j in range(i, n, k):
			if s[j] == '1':
				cur += 1
			else:
				cur -= 1
			cur = max(0, cur)
			ans = min(ans, cnt - cur)
	print(ans)


import sys
import io, os
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, ko) = map(int, input().split())
	garl = [int(i) for i in input() if i != '\n']
	sum_ = sum(garl)
	net_same = 0
	for j in range(ko):
		same = 0
		for k in range(j, n, ko):
			if garl[k] == 1:
				same += 1
			else:
				same -= 1
				if same < 0:
					same = 0
			net_same = max(net_same, same)
	print(sum_ - net_same)


from sys import stdin
input = stdin.readline
for Ti in range(int(input().strip())):
	(n, k) = [int(x) for x in input().strip().split()]
	s = input().strip().strip('0')
	slen = len(s)
	oc = s.count('1')
	ans = float('inf')

	def kadanes(a):
		(ms, cs) = (float('-inf'), float('-inf'))
		for i in range(len(a)):
			cs = max(a[i], a[i] + cs)
			ms = max(ms, cs)
		return ms
	for si in range(k):
		i = si
		zc = 0
		cnt = 0
		t = []
		while i < slen:
			if s[i] == '0':
				t.append(-1)
				zc += 1
			else:
				cnt += 1
				t.append(1)
			i += k
		ts = kadanes(t)
		ans = min(ans, oc - max(ts, 0))
	print(ans)


t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	k = int(l[1])
	s = input()
	howmany = [0 for i in range(n)]
	sumi = 0
	for i in range(n):
		if s[i] == '1':
			sumi += 1
		howmany[i] = sumi
	dp = [[0 for i in range(2)] for i in range(n)]
	if s[0] == '0':
		dp[0][0] = 0
		dp[0][1] = 1
	else:
		dp[0][0] = 1
		dp[0][1] = 0
	for i in range(1, n):
		if s[i] == '0':
			dp[i][0] = min(dp[i - 1][0], dp[i - 1][1])
		else:
			dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]) + 1
		if s[i] == '1':
			if i >= k:
				dp[i][1] = min(howmany[i - 1], dp[i - k][1] + howmany[i - 1] - howmany[i - k])
			else:
				dp[i][1] = howmany[i - 1]
		elif i >= k:
			dp[i][1] = min(howmany[i - 1], dp[i - k][1] + howmany[i - 1] - howmany[i - k]) + 1
		else:
			dp[i][1] = howmany[i - 1] + 1
	print(min(dp[n - 1][0], dp[n - 1][1]))


import sys
input = sys.stdin.readline
t = int(input())
out = []
for i in range(t):
	(n, k) = map(int, input().split())
	s = list(input())
	count = [0]
	for j in s:
		if j == '1':
			count.append(count[-1] + 1)
		else:
			count.append(count[-1])
	ans = count[-1]
	dp = []
	for j in range(n):
		cost = count[j]
		if j >= k:
			cost = min(cost, dp[j - k] + count[j] - count[j - k + 1])
		if s[j] == '0':
			cost += 1
		dp.append(cost)
		ans = min(ans, cost + count[-1] - count[j + 1])
	out.append(ans)
for i in out:
	print(i)


from sys import stdin, stdout

def cal(s):
	state = [-1] * 3
	for (i, x) in enumerate(s):
		tmp_state = [-1] * 3
		if i == 0:
			tmp_state[0] = x
			tmp_state[1] = 0
		elif i == 1:
			tmp_state[0] = state[0]
			tmp_state[1] = x
			tmp_state[2] = 0
		elif i % 2 == 0:
			tmp_state[0] = state[0] + x
			tmp_state[1] = min(state[0], state[1])
			tmp_state[2] = min(state[1] + x, state[2] + x)
		elif i % 2 == 1:
			tmp_state[0] = state[0]
			tmp_state[1] = min(state[0] + x, state[1] + x)
			tmp_state[2] = min(state[1], state[2])
		state = tmp_state
	return min(state[0], state[1], state[2])

def main():
	t = int(stdin.readline())
	for z in range(t):
		(n, k) = list(map(int, stdin.readline().split()))
		s = stdin.readline().rstrip()
		one = 0
		for x in s:
			if x == '1':
				one += 1
		mn = max(0, one - 1)
		for i in range(1, k + 1):
			cur = i - 1
			cnt_one = 0
			add = 0
			real_add = 0
			started = False
			tmp = 0
			arr = []
			while cur < n:
				if s[cur] == '1':
					cnt_one += 1
					started = True
					real_add += add
					if add > 0:
						arr.append(add)
					add = 0
					tmp += 1
				if started and s[cur] == '0':
					if tmp > 0:
						arr.append(tmp)
					add += 1
					tmp = 0
				cur += k
			if tmp > 0:
				arr.append(tmp)
			res = one - cnt_one
			if len(arr) > 2:
				res = cal(arr) + one - cnt_one
			mn = min(mn, res)
		stdout.write(str(mn) + '\n')
main()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	total = ans = s.count('1')
	for j in range(k):
		diff = 0
		for l in range(j, n, k):
			if s[l] == '1':
				diff += 1
			else:
				diff -= 1
			diff = max(diff, 0)
			ans = min(ans, total - diff)
	print(ans)


import sys
import bisect
import heapq
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(int(ri())):
	(n, k) = Ri()
	a = ri()
	a = [int(i) for i in a]
	dp1 = [INF] * n
	dp0 = [INF] * n
	cnt = [0] * n
	cn = 0
	for i in range(k):
		if a[i] == 1:
			cn += 1
	cnt[k - 1] = cn
	for i in range(k, n):
		if a[i - k] == 1:
			cn -= 1
		if a[i] == 1:
			cn += 1
		cnt[i] = cn
	ocnt = [0] * n
	if a[0] == 1:
		ocnt[0] = 1
	for i in range(1, n):
		if a[i] == 1:
			ocnt[i] = ocnt[i - 1] + 1
		else:
			ocnt[i] = ocnt[i - 1]
	oocnt = [0] * n
	if a[-1] == 1:
		oocnt[-1] = 1
	for i in range(n - 2, -1, -1):
		if a[i] == 1:
			oocnt[i] = oocnt[i + 1] + 1
		else:
			oocnt[i] = oocnt[i + 1]
	for i in range(0, n):
		if i - k >= 0:
			if a[i] == 1:
				dp1[i] = min(dp1[i - k] + cnt[i] - 1, ocnt[i] - 1)
			else:
				dp1[i] = min(dp1[i - k] + cnt[i] + 1, ocnt[i] + 1)
		elif a[i] == 1:
			dp1[i] = ocnt[i] - 1
		else:
			dp1[i] = ocnt[i] + 1
	ans = INF
	for i in range(n):
		if a[i] == 1:
			ans = min(dp1[i] + oocnt[i] - 1, ans)
		else:
			ans = min(ans, ocnt[i] + oocnt[i], dp1[i] + oocnt[i])
	print(ans)


import sys, math, cmath, time
start_time = time.time()
global tt

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def solve():
	(n, k) = invr()
	s = insr()
	q = [0]
	for i in range(len(s)):
		if s[i] == '1':
			q.append(q[-1] + 1)
		else:
			q.append(q[-1])
	qw = q[-1]
	w = []
	for i in range(len(s)):
		qq = q[i]
		if i >= k:
			ww = w[i - k] + q[i] - q[i - k + 1]
			qq = min(qq, ww)
		if s[i] == '0':
			qq = qq + 1
		qw = min(qw, qq + q[-1] - q[i + 1])
		w.append(qq)
	print(qw)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
	sys.stdout.close()

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	b = input()
	if k < 5:
		s = b
		m = 0
		c = 0
		total = 0
		for i in range(k):
			c = 0
			for j in range(i, n, k):
				if s[j] == '1':
					c += 1
					total += 1
				else:
					c -= 1
					if c < 0:
						c = 0
				m = max(c, m)
		print(total - m)
	else:
		y = []
		for j in range(n // k):
			y.append(['0'] * (k + 1))
		x = []
		j = 0
		while j < n:
			p = b[j:min(n, j + k)]
			x.append([p, p.count('1')])
			j += k
		if len(x) == 1 or len(x) == len(y):
			x.append([[], 0])
		j = len(x) - 2
		(c, p) = (x[j + 1][0], x[j + 1][1])
		(a, q) = (x[j][0], x[j][1])
		i = 0
		while i < k + 1:
			if i == 0:
				y[j][i] = p + q
			else:
				if a[i - 1] == '1':
					s = q - 1
				else:
					s = q + 1
				if len(c) < i:
					w = p
				elif c[i - 1] == '1':
					w = p - 1
				else:
					w = p + 1
				y[j][i] = min(s + w, s + p)
			i += 1
		j += -1
		while j >= 0:
			i = 0
			(a, q) = (x[j][0], x[j][1])
			while i < k + 1:
				if i == 0:
					r = y[j + 1][0]
					y[j][i] = q + r
				else:
					if a[i - 1] == '1':
						s = q - 1
					else:
						s = q + 1
					y[j][i] = min(y[j + 1][i] + s, s + r)
				i += 1
			j += -1
		A = min(y[0])
		j = 0
		s = 0
		while j < len(y) - 1:
			s += x[j][1]
			A = min(A, s + min(y[j + 1]))
			j += 1
		s += x[j][1]
		q = x[-1][1]
		A = min(A, s + max(q - 1, 0))
		print(A)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input()))
	pre = [0] * n
	pre[0] = a[0]
	for i in range(1, n):
		pre[i] = pre[i - 1] + a[i]
	b = [0] * n
	for i in range(n - 1, -1, -1):
		ss = a[i] ^ 1
		if i + k - 1 < n:
			ss += pre[i + k - 1] - pre[i]
		else:
			ss += pre[n - 1] - pre[i]
		if i + k < n:
			ss += b[i + k]
		oo = pre[n - 1] - pre[i] + a[i]
		b[i] = min(ss, oo)
	ans = 99999999
	for i in range(n):
		hop = b[i]
		if i - 1 >= 0:
			hop += pre[i - 1]
		ans = min(ans, hop)
	print(ans)


for i in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(map(int, input()))
	sr = s[::-1]
	pref = [0]
	for i in range(n):
		pref.append(pref[-1] + s[i])
	dp = []
	for i in range(k):
		dp.append(pref[i] + 1 - s[i])
	for i in range(n - k):
		i += k
		dp.append(min(pref[i] + 1 - s[i], dp[i - k] + pref[i] - pref[i - k + 1] + 1 - s[i]))
	prefr = [0]
	for i in range(n):
		prefr.append(prefr[-1] + sr[i])
	dpr = []
	for i in range(k):
		dpr.append(prefr[i] + 1 - sr[i])
	for i in range(n - k):
		i += k
		dpr.append(min(prefr[i] + 1 - sr[i], dpr[i - k] + prefr[i] - prefr[i - k + 1] + 1 - sr[i]))
	dpr.reverse()
	ans = pref[-1]
	for i in range(n):
		ans = min(ans, dp[i] + dpr[i] - (s[i] + 1) % 2)
	print(ans)


import sys
input = sys.stdin.readline
for i in range(int(input())):
	(n, k) = map(int, input().split())
	s = input().strip()
	c1 = s.count('1')
	ans = n
	for i in range(k):
		su = 0
		for j in range(i, n, k):
			if s[j] == '1':
				su += 1
			else:
				su -= 1
				su = max(0, su)
			ans = min(ans, c1 - su)
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = []
	for (i, x) in enumerate(input()):
		s.append(int(x))

	def f(s):
		SUM = [0]
		for x in s:
			SUM.append(SUM[-1] + x)
		dp = []
		for (i, x) in enumerate(s[:k]):
			dp.append(SUM[i] - SUM[0] + int(not s[i]))
		for i in range(k, n):
			dp.append(min(dp[i - k] + SUM[i] - SUM[i - k + 1], SUM[i]) + int(not s[i]))
		return dp
	a = f(s)
	b = f(s[::-1])[::-1]
	MIN = sum(s)
	for i in range(n):
		MIN = min(MIN, a[i] + b[i] - int(not s[i]))
	print(MIN)


import sys
input = sys.stdin.readline
t = int(input())
while t:
	(n, k) = map(int, input().split())
	s = input().split()[0]
	pre = [int(s[0])]
	for i in range(1, n):
		pre.append(pre[-1] + int(s[i]))
	dp = [[0] * 2 for i in range(n)]
	dp[0][0] = int(s[0])
	dp[0][1] = 1 - int(s[0])
	for i in range(1, k):
		dp[i][0] = int(s[i]) + min(dp[i - 1][0], dp[i - 1][1])
		dp[i][1] = 1 - int(s[i]) + pre[i - 1]
	for i in range(k, n):
		dp[i][0] = int(s[i]) + min(dp[i - 1][0], dp[i - 1][1])
		dp[i][1] = 1 - int(s[i]) + min(dp[i - k][1] + pre[i - 1] - pre[i - k], pre[i - 1])
	print(min(dp[n - 1][0], dp[n - 1][1]))
	t -= 1


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(int(inp())):
	(n, k) = map(int, inp().split())
	s = inp()
	ll = [i for i in s]
	dp = [0] * n
	pos = n - 1
	ct = 0
	sz = 0
	gct = 0
	for i in range(n - 1, -1, -1):
		if ll[i] == '1' and i + k < n:
			dp[i] = dp[i + k]
			dp[i] += ct
		elif i + k < n:
			dp[i] = min(gct, 1 + dp[i + k] + ct)
		else:
			dp[i] = gct
		if ll[pos] == '1' and sz == k - 1:
			ct -= 1
		if sz == k - 1:
			pos -= 1
		if ll[i] == '1':
			gct += 1
			ct += 1
		if sz < k - 1:
			sz += 1
	ans = n + 1
	ct = 0
	for i in range(n):
		if ll[i] == '1':
			ans = min(dp[i] + ct, ans)
			ct += 1
	if ans == n + 1:
		ans = 0
	print(ans)


for i in range(int(input())):
	(n, k) = list(map(int, input().split()))
	a = input()
	z = 0
	for i in range(k):
		b = 0
		c = []
		for j in range(i, n, k):
			if a[j] == '1':
				b += 1
			else:
				if b:
					c.append(b)
				c.append(-1)
				b = 0
		c.append(b)
		p = [0]
		d = 0
		for j in range(len(c)):
			p.append(p[j] + c[j])
			z = max(z, p[j + 1] - d)
			d = min(d, p[j + 1])
	print(a.count('1') - z)


rri = lambda : int(input())
rrm = lambda : list(map(int, input().split(' ')))

def solve(N, K, A):
	oo = 0
	for j in range(n):
		if A[j] == 1:
			oo += 1
	ans = oo
	for mod in range(k):
		delta = 0
		for j in range(mod, n, k):
			if A[j] == 1:
				delta -= 1
			else:
				delta += 1
			delta = min(0, delta)
			ans = min(ans, oo + delta)
	return ans
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split(' ')]
	ll = [int(i) for i in list(input())]
	print(solve(n, k, ll))


INF = 10 ** 6
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, input()))
	on_sum = sum(s)
	ans = INF
	for i in range(k):
		cnt = on_sum
		for e in s[i::k]:
			cnt -= e
		off = 0
		off_on = INF
		off_on_off = INF
		for e in s[i::k]:
			off_on_off = min(off_on_off + e, off_on + e)
			off_on = min(off_on + 1 - e, off + 1 - e)
			off = off + e
		cnt += min(off, off_on, off_on_off)
		ans = min(ans, cnt)
	print(ans)


from sys import stdin, setrecursionlimit
import threading

def low(ind, line, k, mem, sMem, oneCount, start=False):
	if ind >= len(line):
		return 0
	if start:
		if ind in sMem:
			return sMem[ind]
		if line[ind] == 0:
			sMem[ind] = low(ind + 1, line, k, mem, sMem, oneCount, True)
			return sMem[ind]
		else:
			sMem[ind] = low(ind + 1, line, k, mem, sMem, oneCount, True) + 1
	elif ind in mem:
		return mem[ind]
	count = 0
	if line[ind] == 0:
		count += 1
	count += oneCount[ind + 1] - oneCount[min(len(line), ind + k)]
	mem[ind] = min(count + low(ind + k, line, k, mem, sMem, oneCount), oneCount[ind])
	if start:
		sMem[ind] = min(sMem[ind], mem[ind])
		return sMem[ind]
	return mem[ind]

def main():
	for case in range(int(stdin.readline())):
		(n, k) = [int(x) for x in stdin.readline().split()]
		line = [int(x) for x in stdin.readline().strip()]
		oneCount = [0]
		for x in range(n):
			oneCount.append(oneCount[-1])
			if line[-x - 1] == 1:
				oneCount[-1] += 1
		oneCount = oneCount[::-1]
		mem = {}
		sMem = {}
		for x in range(n - 1, -1, -1):
			low(x, line, k, mem, sMem, oneCount, True)
			low(x, line, k, mem, sMem, oneCount)
		print(low(0, line, k, mem, sMem, oneCount, True))
main()


ord0 = b'0'[0]
qqq = int(input())
ans = []
for _ in range(qqq):
	(n, k) = [int(x) for x in input().split()]
	s = [c - ord0 for c in input().encode('ascii')]
	res = 10 ** 9
	tot = sum(s)
	for rem in range(k):
		c = s[rem:n:k]
		m = len(c)
		cnt = sum(c)
		(x0, x1, x2) = (0, 0, 0)
		for x in c:
			if x == 0:
				(x1, x2) = (min(x0, x1) + 1, min(x0, x1, x2))
			else:
				(x0, x1, x2) = (x0 + 1, min(x0, x1), min(x0, x1, x2) + 1)
		res = min(res, tot - cnt + min(x0, x1, x2))
	ans.append(res)
print('\n'.join((str(x) for x in ans)))


import sys

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in range(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def bit_combination(n, base=2):
	rt = []
	for tb in range(base ** n):
		s = [tb // base ** bt % base for bt in range(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
input = lambda : sys.stdin.readline().rstrip()
show_flg = False
show_flg = True
ans = 0

def fast_consecutize(a):
	if sum(a) == 0:
		return 0
	n = len(a)
	dp0 = [0] * (n + 1)
	dp1 = [0] * (n + 1)
	dp2 = [0] * (n + 1)
	rt = n
	for i in range(n):
		dp0[i + 1] = dp0[i] + a[i]
		dp1[i + 1] = min(dp1[i] + 1 - a[i], dp0[i] + 1 - a[i])
		dp2[i + 1] = min(dp2[i] + a[i], dp1[i] + 1 - a[i], dp0[i])
	return dp2[n]

def consecutize(a):
	if sum(a) == 0:
		return 0
	n = len(a)
	rt = n
	aon = [0]
	aoff = [0]
	for i in a:
		aon += [aon[-1] + i]
		aoff += [aoff[-1] + 1 - i]
	for l in range(n):
		for r in range(l, n):
			tmp = 0
			tmp += aon[l] - aon[0]
			tmp += aoff[r + 1] - aoff[l]
			tmp += aon[n] - aon[r + 1]
			rt = min(rt, tmp)
	return rt
xx = '01'
A = [int(i) for i in xx]
T = I()
for _ in range(T):
	(n, k) = LI()
	a = [int(i) for i in input()]
	ans = a
	c = 0
	r = [[] for i in range(k)]
	cnt = [0] * k
	for i in range(n):
		cnt[c] += a[i]
		r[c] += [a[i]]
		c += 1 if c != k - 1 else -k + 1
	ans = n
	s = sum(cnt)
	for i in range(k):
		tmp = s - cnt[i] + fast_consecutize(r[i])
		if ans > tmp:
			ans = tmp
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, list(input())))
	prefix = []
	ans = 0
	for i in range(n):
		ans += l[i]
		prefix.append(ans)
	dp = [0 for i in range(n)]
	l = l[::-1]
	prefix1 = []
	ans = 0
	for i in range(n):
		ans += l[i]
		prefix1.append(ans)
	for j in range(n):
		h = 0
		if j < k:
			if j == 0:
				dp[j] = 0
			else:
				dp[j] = min(prefix1[j - 1], prefix1[j - 1] + (l[j] ^ 1))
		else:
			dp[j] = min(prefix1[j], dp[j - k] + (prefix1[j - 1] - prefix1[j - k]) + (l[j] ^ 1))
	dp = dp[::-1]
	for k in range(1, n):
		dp[k] += prefix[k - 1]
	print(min(dp))


t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	arr = [int(x) for x in input()]
	dp = [0 for i in range(n)]
	count1 = [x for x in arr]
	for i in range(1, len(arr)):
		count1[i] = count1[i - 1] + arr[i]
	count1.append(count1[-1])
	for i in range(n - 1, -1, -1):
		case1 = 1 if arr[i] == 0 else 0
		l = i + k if i + k < n else n
		case1 += count1[l - 1] - count1[i]
		if l < n:
			case1 += dp[l]
		case2 = 1 if arr[i] == 1 else 0
		case2 += count1[n - 1] - count1[i]
		dp[i] = min(case1, case2)
	for i in range(1, len(arr)):
		dp[i] += count1[i - 1]
	print(min(dp))


from sys import stdin, stdout
read = stdin.readline
T = int(read())
for i in range(T):
	(n, k) = map(int, read().split())
	s = read()[:-1]
	ones = sum([c == '1' for c in s])
	cnt = [0 for i in range(k)]
	for i in range(n):
		if s[i] == '1':
			cnt[i % k] += 1
	ans = ones
	dp = [[0 for j in range(3)] for i in range(n)]
	for i in range(n - 1, n - k - 1, -1):
		if s[i] == '1':
			dp[i][0] = 1
			dp[i][2] = 1
		else:
			dp[i][1] = 1
	for i in range(n - k - 1, -1, -1):
		if s[i] == '1':
			dp[i][0] = dp[i + k][0] + 1
			dp[i][1] = min(dp[i + k][0], dp[i + k][1])
			dp[i][2] = min(dp[i + k][1], dp[i + k][2]) + 1
		else:
			dp[i][0] = dp[i + k][0]
			dp[i][1] = min(dp[i + k][0], dp[i + k][1]) + 1
			dp[i][2] = min(dp[i + k][1], dp[i + k][2])
	for i in range(k):
		ans = min(ans, ones - cnt[i] + min(dp[i]))
	stdout.write(str(ans) + '\n')


import sys
t = int(input())
for __ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	o = s.count('1')
	ans = o
	for i in range(k):
		cnt = 0
		for j in range(i, n, k):
			if s[j] == '1':
				cnt += 1
			else:
				cnt -= 1
			cnt = max(0, cnt)
			ans = min(ans, o - cnt)
	print(ans)


T = int(input())
for _ in range(0, T):
	(n, k) = map(int, input().split())
	s = input()
	tot = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == '1':
			tot += 1
	ans = tot
	for i in range(k):
		D = []
		tt = tot
		for j in range(i, len(s), k):
			D.append(s[j])
			if s[j] == '1':
				tt -= 1
		ct0 = []
		ct1 = []
		mn = []
		c0 = 0
		c1 = 0
		for j in range(0, len(D)):
			if D[j] == '1':
				c1 += 1
			else:
				c0 += 1
			ct0.append(c0)
			ct1.append(c1)
		diff = c1
		mnn = 1000000000
		for j in range(len(D) - 1, -1, -1):
			mnn = min(mnn, diff - ct1[j] + ct0[j])
			kk1 = 0
			kk2 = 0
			if j - 1 >= 0:
				kk1 = ct0[j - 1]
				kk2 = ct1[j - 1]
			mn.append(mnn - kk1 + kk2)
		tt += min(mn)
		ans = min(ans, tt)
	print(ans)


test = int(input())
number = []
interval = []
col = []
for i in range(test):
	k = list(map(int, input().split()))
	number.append(k[0])
	interval.append(k[1])
	col.append(input())
for i in range(test):
	dp0 = []
	dp1 = []
	start = 0
	start_pos = 0
	cycle = 0
	one_count = 0
	inter_count = 0
	for j in range(number[i]):
		if cycle == 1:
			if col[i][j] == '0':
				dp0.append(min(dp0[j - 1], dp1[j - 1]))
				min_count = min(dp1[j - interval[i]] + inter_count, one_count)
				dp1.append(min_count + 1)
			if col[i][j] == '1':
				dp0.append(min(dp0[j - 1], dp1[j - 1]) + 1)
				min_count = min(dp1[j - interval[i]] + inter_count, one_count)
				dp1.append(min_count)
		if start == 1 and j < start_pos + interval[i]:
			if col[i][j] == '0':
				dp0.append(min(dp0[j - 1], dp1[j - 1]))
				dp1.append(one_count + 1)
			if col[i][j] == '1':
				dp0.append(min(dp0[j - 1], dp1[j - 1]) + 1)
				dp1.append(one_count)
		if start == 0 and col[i][j] == '0':
			dp0.append(0)
			dp1.append(0)
		if start == 0 and col[i][j] == '1':
			dp0.append(1)
			dp1.append(0)
			start = 1
			start_pos = j
		if start == 1 and j == start_pos + interval[i] - 1:
			cycle = 1
		if start == 1 and cycle == 0:
			if col[i][j] == '1':
				inter_count += 1
		if cycle == 1:
			if col[i][j - interval[i] + 1] == '1':
				inter_count -= 1
			if col[i][j] == '1':
				inter_count += 1
		if col[i][j] == '1':
			one_count += 1
	print(min(dp0[number[i] - 1], dp1[number[i] - 1]))


t = int(input())
for q in range(t):
	(n, k) = map(int, input().split())
	s = input()
	ans = 0
	count = 0
	total = 0
	for i in range(k):
		count = 0
		for j in range(i, n, k):
			if s[j] == '1':
				count += 1
				total += 1
			else:
				count -= 1
				if count < 0:
					count = 0
			ans = max(count, ans)
	print(total - ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, K) = map(int, input().split())
	s = input()
	cnt = [int(s[i]) for i in range(n)]
	for i in range(1, n):
		cnt[i] += cnt[i - 1]
	dp = [0 for i in range(n)]
	dp[0] = s[0] == '0'
	for i in range(1, K):
		dp[i] = (s[i] == '0') + cnt[i - 1]
	for i in range(K, n):
		dp[i] = (s[i] == '0') + min(cnt[i - 1], cnt[i - 1] - cnt[i - K] + dp[i - K])
	ans = min((dp[i] + cnt[-1] - cnt[i] for i in range(n)))
	print(min(ans, cnt[-1]))


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

def L():
	return list(map(int, input().split()))

def In():
	return map(int, input().split())

def I():
	return int(input())
P = 1000000007

def main():
	for t in range(I()):
		(n, k) = In()
		s = input()
		arr = []
		arr.append(int(s[0]))
		dp = []
		dp.append(0)
		for i in range(1, n):
			arr.append(int(s[i]) + arr[i - 1])
			dp.append(0)
		for i in range(n - 1, -1, -1):
			a = int(s[i]) ^ 1
			if i + k - 1 < n:
				a += arr[i + k - 1] - arr[i]
			else:
				a += arr[n - 1] - arr[i]
			if i + k < n:
				a += dp[i + k]
			b = int(s[i]) + arr[n - 1] - arr[i]
			dp[i] = min(a, b)
		mn = dp[0]
		for i in range(1, n):
			dp[i] += arr[i - 1]
			mn = min(dp[i], mn)
		print(mn)
main()


from collections import defaultdict, deque
from itertools import permutations
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
import heapq
int_input = lambda : int(stdin.readline())
string_input = lambda : stdin.readline().split()
multi_int_input = lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input = lambda : list(map(int, stdin.readline().split()))
string_list_input = lambda : list(string_input())
MOD = pow(10, 9) + 7
test = int_input()
for _ in range(test):
	(n, k) = multi_int_input()
	state = input()
	total = 0
	for i in state:
		if i == '1':
			total += 1
	ans = total
	for i in range(0, k):
		diff = 0
		for j in range(i, n, k):
			if state[j] == '1':
				diff += 1
			elif state[j] == '0':
				diff -= 1
			diff = max(0, diff)
			ans = min(ans, total - diff)
	print(ans)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	(n, k) = mapi()
	a = input().strip()
	res = float('inf')
	if n == 1:
		print(0)
		continue
	pre = [0] * (n + 1)
	for i in range(n):
		pre[i + 1] = pre[i]
		if a[i] == '1':
			pre[i + 1] += 1
	dp1 = [0] * (n + 1)
	dp2 = [0] * (n + 1)
	ones = lambda x, y: pre[y] - pre[x]
	for i in range(1, n + 1):
		dp1[i] = pre[i - 1]
		if i - k >= 1:
			dp1[i] = min(dp1[i], dp1[i - k] + ones(i - k, i - 1)) + (a[i - 1] == '0')
	for i in range(n, 0, -1):
		dp2[i] = pre[n] - pre[i]
		if i + k <= n:
			dp2[i] = min(dp2[i], dp2[i + k] + ones(i, i + k)) + (a[i - 1] == '0')
	for i in range(1, n + 1):
		res = min(res, dp1[i] + dp2[i] - (a[i - 1] == '0'))
	print(max(res, 0))


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	s = input()
	ones = best = 0
	for i in range(k):
		cnt = 0
		for j in range(i, n, k):
			if s[j] == '1':
				cnt += 1
				ones += 1
			else:
				cnt = max(0, cnt - 1)
			best = max(cnt, best)
	print(ones - best)


import sys
input = sys.stdin.readline
import heapq
import copy
import math

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

class Node:

	def _init_(self, val):
		self.data = val
		self.left = None
		self.right = None

def bin_search(arr, l, r, val):
	if arr[r] <= val:
		return r + 1
	if r - l < 2:
		if arr[l] > val:
			return l
		else:
			return r
	mid = int((l + r) / 2)
	if arr[mid] <= val:
		return bin_search(arr, mid, r, val)
	else:
		return bin_search(arr, l, mid, val)

def pr_list(a):
	print(*a, sep=' ')

def find_permut(hashm, l):
	ans = 1
	total = math.factorial(l)
	for i in hashm:
		if i != 0:
			ans = ans * math.factorial(i)
	return int(total / ans)

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	for test in range(tests):
		[n, k] = inlt()
		s = insr()
		pre = [int(s[0])]
		for i in range(1, len(s)):
			pre.append(pre[-1] + int(s[i]))
		for i in range(k + 1):
			pre.append(pre[-1])
		dp = [[0 for i in range(n + k + 1)] for j in range(2)]
		for i in range(n - 2, -1, -1):
			if s[i] == '0':
				a = 1
			else:
				a = 0
			dp[0][i] = min(dp[0][i + 1], dp[1][i + 1]) + int(s[i])
			dp[1][i] = min(dp[1][i + k], pre[-1] - pre[i + k - 1]) + pre[i + k - 1] - pre[i] + a
		print(min(dp[0][0], dp[1][0]))
main()


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	c = s.count('1')
	ans = float('inf')
	for i in range(k):
		vals = []
		for j in range(i, n, k):
			vals.append(int(s[j]))
		diff = 0
		for i in vals:
			if i:
				diff += 1
			else:
				diff -= 1
			diff = max(diff, 0)
			ans = min(ans, c - diff)
	print(ans)


def main():
	import sys, math
	from heapq import heapify, heappush, heappop
	from collections import defaultdict as dd, deque, Counter

	def data():
		return sys.stdin.readline().strip()

	def mdata():
		return list(map(int, data().split()))

	def out(*var, end='\n'):
		sys.stdout.write('\n'.join(map(str, var)) + end)
	sys.setrecursionlimit(100000)
	INF = float('inf')
	mod = int(1000000000.0) + 7
	for t in range(int(data())):
		(n, k) = mdata()
		s = data()
		m = 0
		total = s.count('1')
		for i in range(k):
			a = 0
			for j in range(i, n, k):
				if s[j] == '1':
					a += 1
				else:
					a = max(0, a - 1)
				m = max(m, a)
		print(total - m)
main()


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')

def solve(n, k, s):
	result = float('inf')
	ones = s.count(1)
	for i in range(k):
		prefix_sum = 0
		for item in s[i::k]:
			prefix_sum = max(0, prefix_sum + item)
			result = min(result, ones - prefix_sum)
	return result
for i in range(int_in()):
	(n, k) = arr_in()
	s = [1 if x == '1' else -1 for x in str_in()]
	out(solve(n, k, s))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input()))
	tot = sum(l)
	ans = tot
	for t in range(k):
		qw = 0
		for i in range(t, n, k):
			if l[i]:
				qw += 1
			else:
				qw -= 1
			qw = max(0, qw)
			ans = min(ans, tot - qw)
	print(ans)


import sys
read = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, read().split())
	s = read()
	ss = [[] for _ in range(k)]
	all1 = 0
	for i in range(n):
		c = int(s[i])
		ss[i % k].append(c)
		all1 += c
	ans = 1 << 30
	for i in range(k):
		cnt = sum(ss[i])
		res = cnt
		n = len(ss[i])
		left = 0
		dp = [0] * n
		for j in range(n):
			c = ss[i][j]
			dp[j] = min(dp[j - 1] + 1 - c, left)
			left += c
			res = min(res, dp[j] + cnt - left)
		ans = min(ans, res + all1 - cnt)
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	(obsh, ans) = (s.count('1'), 10 ** 19)
	for i in range(k):
		temp = 0
		for j in range(i, n, k):
			if s[j] == '1':
				temp -= 1
			else:
				temp += 1
			temp = min(temp, 0)
			ans = min(ans, temp + obsh)
	print(ans)


def get1Cnts(p, l, r):
	if l == 0:
		return p[r]
	else:
		return p[r] - p[l - 1]

def findMinToMakeOneModHaveAtMost1GroupOfOnes(oneSArr):
	n = len(oneSArr)
	p = [0 for _ in range(n)]
	for i in range(n):
		if oneSArr[i] == 1:
			p[i] += 1
		if i > 0:
			p[i] += p[i - 1]
	ans = get1Cnts(p, 0, n - 1)
	for i in range(n):
		if i == 0:
			nMoves = 0
		else:
			nMoves = min(nMovesPrev, get1Cnts(p, 0, i - 1))
		if oneSArr[i] == 0:
			nMoves += 1
		if i + 1 < n:
			setAfterToZero = get1Cnts(p, i + 1, n - 1)
		else:
			setAfterToZero = 0
		ans = min(ans, nMoves + setAfterToZero)
		nMovesPrev = nMoves
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inf = float('inf')
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = [int(x) for x in input()]
	oneCntsMod = [0 for _ in range(k)]
	sArr = [[] for _ in range(k)]
	for i in range(n):
		if s[i] == 1:
			oneCntsMod[i % k] += 1
		sArr[i % k].append(s[i])
	total1s = sum(oneCntsMod)
	ans = inf
	for i in range(k):
		ans = min(ans, total1s - oneCntsMod[i] + findMinToMakeOneModHaveAtMost1GroupOfOnes(sArr[i]))
	print(ans)


T = int(input())
for test in range(T):
	(n, k) = list(map(int, input().split()))
	a = [[] for _ in range(n)]
	s = input()
	count = 0
	for i in range(n):
		if s[i] == '1':
			count += 1
			ans = (i + 1) % k
			a[ans].append(i + 1)
	if count == 0:
		print(0)
		continue
	result = int(1000000000.0)
	for x in a:
		if len(x) == 0:
			continue
		dp = [0]
		for i in range(1, len(x)):
			ans = int((x[i] - x[i - 1]) / k - 1)
			dp.append(min(dp[-1] + ans, i))
		res = int(1000000000.0)
		for i in range(len(dp)):
			res = min(res, dp[i] + len(dp) - i - 1)
		result = min(result, res + count - len(x))
	print(result)


import sys
import heapq
import math
import bisect

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, input().split())

def rlinput():
	return list(map(int, input().split()))

def srlinput(fl=False):
	return sorted(list(map(int, input().split())), reverse=fl)

def main():
	(n, k) = rinput()
	lam = [int(i) for i in list(input())]
	lamrev = lam[::-1]
	(q, qrev) = ([0], [0])
	(w, wrev) = ([], [])
	for i in range(n):
		q.append(q[-1] + lam[i])
	for i in range(k):
		t = q[i] + 1 - lam[i]
		w.append(t)
	for i in range(n - k):
		i += k
		(t, f) = (q[i] + 1 - lam[i], i - k)
		w.append(t + min(0, w[f] - q[f + 1]))
	for i in range(n):
		qrev.append(qrev[-1] + lamrev[i])
	for i in range(k):
		t = qrev[i] + 1 - lamrev[i]
		wrev.append(t)
	for i in range(n - k):
		i += k
		(t, f) = (qrev[i] + 1 - lamrev[i], i - k)
		wrev.append(t + min(0, wrev[f] - qrev[f]))
	wrev.reverse()
	print(min(min((w[i] + wrev[i] - (lam[i] + 1) % 2 for i in range(n))), q[-1]))
for sdfghjkl in range(iinput()):
	main()


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, k) = map(int, input().split())
	s = input()
	pre = [0 for i in range(n)]
	steps = [0 for i in range(n)]
	su = 0
	for i in range(1, n):
		su += int(s[i - 1])
		pre[i] = su
	sol = steps[n - 1] + pre[n - 1]
	for i in range(n - 2, -1, -1):
		if i >= n - k:
			steps[i] = pre[n - 1] + int(s[n - 1]) - pre[i + 1]
		else:
			x = pre[i + k] - pre[i + 1] + 1 - int(s[i]) + steps[i + k]
			y = pre[n - 1] - pre[i + 1] + int(s[i] + s[n - 1])
			steps[i] = min(x, y)
		sol = min(sol, steps[i] + pre[i])
	print(sol)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = input()
	t_ones = 0
	max_one = 0
	for i in range(k):
		c = 0
		for j in range(i, n, k):
			if l[j] == '1':
				c += 1
				t_ones += 1
			else:
				c -= 1
				if c < 0:
					c = 0
			max_one = max(max_one, c)
	print(t_ones - max_one)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	cnt = ans = s.count('1')
	for j in range(k):
		score = 0
		for r in range(j, n, k):
			if s[r] == '1':
				score += 1
			else:
				score -= 1
			score = max(0, score)
			ans = min(ans, cnt - score)
	print(ans)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(INT()):
	(N, K) = MAP()
	S = list(map(int, input()))
	A = [[] for i in range(K)]
	for (i, s) in enumerate(S):
		A[i % K].append(s)
	cnt1all = S.count(1)
	ans = INF
	for i in range(K):
		M = len(A[i])
		dp0 = [INF] * (M + 1)
		dp1 = [INF] * (M + 1)
		dp2 = [INF] * (M + 1)
		dp0[0] = 0
		cnt1 = 0
		for j in range(M):
			cnt1 += A[i][j] == 1
			dp0[j + 1] = min(dp0[j + 1], dp0[j] + (A[i][j] == 1))
			dp1[j + 1] = min(dp1[j + 1], dp0[j] + (A[i][j] == 0))
			dp1[j + 1] = min(dp1[j + 1], dp1[j] + (A[i][j] == 0))
			dp2[j + 1] = min(dp2[j + 1], dp1[j] + (A[i][j] == 1))
			dp2[j + 1] = min(dp2[j + 1], dp2[j] + (A[i][j] == 1))
		cost = min(dp0[M], dp1[M], dp2[M])
		ans = min(ans, cnt1all - cnt1 + cost)
	print(ans)


def main():
	T = int(input())
	for _ in range(T):
		(N, K) = list(map(int, input().split()))
		s = input()
		arr = []
		for i in range(len(s)):
			arr.append(int(s[i]))
		upper_bound = 0
		for i in range(len(arr)):
			upper_bound += arr[i]
		res = N
		for k in range(K):
			i = k
			gain = 0
			while i < len(arr):
				if arr[i] == 1:
					gain += 1
				else:
					gain -= 1
				gain = max(0, gain)
				res = min(res, upper_bound - gain)
				i += K
		print(res)
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	data = input()
	total = 0
	splited = [[] for _ in range(k)]
	for i in range(n):
		splited[i % k].append(ord(data[i]) - ord('0'))
		total += ord(data[i]) - ord('0')
	result = total
	for array in splited:
		dp = [0] * len(array)
		dp[0] = array[0]
		for i in range(1, len(array)):
			if array[i] == 1:
				dp[i] = dp[i - 1] + 1
			elif array[i] == 0:
				dp[i] = max(dp[i - 1] - 1, 0)
		result = min(result, total - max(dp))
	print(result)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	count_1_l = [0] * n
	count_1_r = [0] * n
	for i in range(n):
		if i == 0:
			if s[i] == '1':
				count_1_l[i] = 1
		else:
			count_1_l[i] = count_1_l[i - 1]
			if s[i] == '1':
				count_1_l[i] += 1
	for i in range(n):
		j = n - 1 - i
		if j == n - 1:
			if s[j] == '1':
				count_1_r[j] = 1
		else:
			count_1_r[j] = count_1_r[j + 1]
			if s[j] == '1':
				count_1_r[j] += 1
	fl_on = [0] * n
	if s[0] == '0':
		fl_on[0] = 1
	for i in range(1, n):
		if i < k:
			fl_on[i] = count_1_l[i - 1]
			if s[i] == '0':
				fl_on[i] += 1
		else:
			j = i - k
			fl_on[i] = min(fl_on[j], count_1_l[j]) + count_1_l[i - 1] - count_1_l[j]
			if s[i] == '0':
				fl_on[i] += 1
	fr_on = [0] * n
	if s[n - 1] == '0':
		fr_on[n - 1] = 1
	for h in range(1, n):
		i = n - 1 - h
		if i > n - 1 - k:
			fr_on[i] = count_1_r[i + 1]
			if s[i] == '0':
				fr_on[i] += 1
		else:
			j = i + k
			fr_on[i] = min(fr_on[j], count_1_r[j]) + count_1_r[i + 1] - count_1_r[j]
			if s[i] == '0':
				fr_on[i] += 1
	result = count_1_l[n - 1]
	for i in range(n):
		result = min(result, fl_on[i] + fr_on[i])
	print(result)


from sys import stdin, stdout
from heapq import heappush, heapify, heappop
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	c = s.count('1')
	ans = float('inf')
	for i in range(k):
		vals = []
		for j in range(i, n, k):
			vals.append(int(s[j]))
		dp = [[0 for y in range(2)] for x in range(len(vals))]
		dp[0][0] = vals[0]
		dp[0][1] = vals[0] ^ 1
		p = [vals[0] for x in range(len(vals))]
		for j in range(1, len(vals)):
			if vals[j]:
				p[j] = p[j - 1] + 1
			else:
				p[j] = p[j - 1]
		for j in range(1, len(vals)):
			dp[j][0] = vals[j] + min(dp[j - 1][0], dp[j - 1][1])
			p1 = p[j - 1]
			dp[j][1] = (vals[j] ^ 1) + min(dp[j - 1][1], p1)
		ans = min(ans, c - vals.count(1) + min(dp[-1][0], dp[-1][1]))
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
ans = []
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, list(input().rsplit()[0])))
	tot = sum(s)
	ret = 1 << 100
	for i in range(k):
		D = [0] * 3
		cnt = 0
		for j in range(i, n, k):
			cnt += s[j]
			P = [0] * 3
			if s[j]:
				P[0] = D[0] + 1
				P[1] = min(D[0], D[1])
				P[2] = min(D[1], D[2]) + 1
			else:
				P[0] = D[0]
				P[1] = min(D[0], D[1]) + 1
				P[2] = min(D[1], D[2])
			D = P[:]
		ret = min(ret, tot - cnt + min(D))
	ans.append(ret)
print('\n'.join(map(str, ans)))


def solve():
	(n, k) = map(int, input().split())
	s = input()
	if n == 1:
		print(0)
	else:
		cnt = 0
		maxc = 0
		ones = 0
		for i in range(k):
			for j in range(i, n, k):
				if s[j] == '1':
					cnt += 1
					ones += 1
					maxc = max(maxc, cnt)
				else:
					cnt -= 1
					if cnt < 0:
						cnt = 0
			maxc = max(maxc, cnt)
			cnt = 0
		print(ones - maxc)
t = int(input())
for _ in range(t):
	solve()


t = int(input())

def dp(l):
	dp = [[float('INF')] * 3 for m in range(len(l) + 1)]
	dp[0][0] = 0
	dp[0][1] = 0
	c = 0
	for m in range(len(l)):
		x = l[m]
		c += x
		dp[m + 1][0] = dp[m][0] + x
		dp[m + 1][1] = min(dp[m][0], dp[m][1]) + abs(1 - x)
		dp[m + 1][2] = min(dp[m][1], dp[m][2]) + x
	return min(dp[-1]) - c

def main():
	import sys
	input = sys.stdin.readline
	for i in range(t):
		(n, k) = map(int, input().split())
		s = list(input())
		l = [[] for j in range(k)]
		count = 0
		for j in range(n):
			if s[j] == '0':
				l[j % k].append(0)
			else:
				count += 1
				l[j % k].append(1)
		ans = count
		for j in range(k):
			ans = min(ans, dp(l[j]) + count)
		print(ans)
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	(ans, ones) = (n, s.count('1'))
	for t in range(k):
		step = 0
		for i in range(t, n, k):
			step = max(0, step - 1) if s[i] == '0' else step + 1
			ans = min(ans, ones - step)
	print(ans)


INF = int(100000000.0)
for _ in [0] * int(input()):
	(n, k) = map(int, input().split())
	a = [0] + [*map(int, input())]
	b = [0] * (n + 1)
	for i in range(1, n + 1):
		b[i] += b[i - 1] + a[i]
	r = [INF] * (n + 1)
	r[0] = 0
	for i in range(1, n + 1):
		r[i] = min(r[i], b[i - 1] + (a[i] < 1))
		if i > k:
			r[i] = min(r[i], r[i - k] + b[i - 1] - b[i - k] + (a[i] < 1))
	c = b[n]
	for i in range(1, n + 1):
		c = min(c, r[i] + b[n] - b[i])
	print(c)


T = int(input())
for kase in range(T):
	(n, k) = map(int, input().split())
	s = input()
	(one, ans) = (s.count('1'), n)
	for i in range(0, k):
		d = 0
		for j in range(i, n, k):
			d = max(0, d - 1) if s[j] == '0' else d + 1
			ans = min(ans, one - d)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(a, b) = list(map(int, input().split()))
	s = input().rstrip()
	s = list(s)
	s = [int(x) for x in s]
	total = sum(s)
	best = 0
	for j in range(b):
		c = 0
		for k in range(j, a, b):
			if s[k] == 1:
				c += 1
			else:
				c -= 1
				if c < 0:
					c = 0
			best = max(best, c)
	print(total - best)


def answer(s, k):
	if len(s) == 1:
		return 0
	dp = [0] * len(s)
	presum = [0] * len(s)
	for i in range(len(s) - 1, -1, -1):
		if i == len(s) - 1:
			presum[i] += int(s[i])
		else:
			presum[i] += int(s[i]) + presum[i + 1]
	for i in range(len(s) - 2, -1, -1):
		t = 0
		if i + k >= len(s):
			t = presum[i + 1]
		elif s[i] == '1':
			t = min(1 + presum[i + 1], dp[i + k] + presum[i + 1] - presum[i + k])
		else:
			t = min(presum[i + 1], 1 + dp[i + k] + presum[i + 1] - presum[i + k])
		dp[i] = t
	for i in range(1, len(dp)):
		dp[i] = dp[i] + presum[0] - presum[i]
	return min(dp)
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	print(answer(s, k))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(50001)]
pp = []

def SieveOfEratosthenes(n=50000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for i in range(50001):
		if prime[i]:
			pp.append(i)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ones = s.count('1')
	best = 0
	for i in range(k):
		cnt = 0
		for j in range(i, n, k):
			if s[j] == '1':
				cnt += 1
			else:
				cnt = max(0, cnt - 1)
			best = max(cnt, best)
	print(ones - best)


for f in range(int(input())):
	(n, k) = map(int, input().split())
	s2 = input()
	s = [0] * n
	tot = 0
	for i in range(n):
		if s2[i] == '1':
			tot += 1
			s[i] = 1
	bestmin = n
	for i in range(k):
		j = i
		pretot = 0
		keep = 0
		nkeep = 0
		curlights = 0
		curdark = 0
		light = 0
		if s[j] == 1:
			curlights = 1
			light = 1
		j += k
		while j < n:
			if light == 1:
				if s[j] == 1:
					curlights += 1
				else:
					light = 0
					nkeep = curlights + min(keep, nkeep)
					keep = min(keep + curdark, pretot)
					pretot += curlights
					curlights = 0
					curdark = 1
			elif s[j] == 0:
				curdark += 1
			else:
				light = 1
				curlights = 1
			j += k
		if light == 1:
			nkeep = curlights + min(keep, nkeep)
			keep = min(keep + curdark, pretot)
		pretot += curlights
		curmin = min(keep, nkeep)
		curmin += tot
		curmin -= pretot
		bestmin = min(bestmin, curmin)
	print(bestmin)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, list(input())))
	prf = []
	dp = []
	ans = 0
	for i in range(n):
		ans += l[i]
		prf.append(ans)
		dp.append(0)
	for j in range(1, n):
		if j < k:
			dp[n - 1 - j] = min(prf[-1] - prf[n - 1 - j] + (l[n - 1 - j] ^ 0), prf[-1] - prf[n - j - 1] + (l[n - 1 - j] ^ 1))
		else:
			dp[n - 1 - j] = min(prf[-1] - prf[n - 1 - j] + (l[n - 1 - j] ^ 0), dp[n - 1 - j + k] + (prf[n - 2 - j + k] - prf[n - 1 - j]) + (l[n - 1 - j] ^ 1))
	for i1 in range(1, n):
		dp[i1] += prf[i1 - 1]
	print(min(dp))


import sys
input = sys.stdin.readline
rInt = lambda : int(input())
mInt = lambda : map(int, input().split())
rLis = lambda : list(map(int, input().split()))
outs = []
t = rInt()
for _ in range(t):
	(n, k) = mInt()
	s = input()
	pref = [0]
	for c in s:
		if c == '1':
			pref.append(pref[-1] + 1)
		else:
			pref.append(pref[-1])
	best = pref[-1]
	dp = []
	for i in range(n):
		cost = pref[i]
		if i >= k:
			case2 = dp[i - k] + pref[i] - pref[i - k + 1]
			if case2 < cost:
				cost = case2
		if s[i] == '0':
			cost += 1
		dp.append(cost)
		actual = cost + pref[-1] - pref[i + 1]
		if actual < best:
			best = actual
	outs.append(best)
print(*outs, sep='\n')


T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	s = input()
	count = 0
	for i in s:
		if i == '1':
			count += 1
	ans = 1000000000
	for i in range(k):
		Sum = 0
		for j in range(i, n, k):
			if s[j] == '1':
				Sum += 1
			else:
				Sum -= 1
			if Sum < 0:
				Sum = 0
			ans = min(ans, count - Sum)
	print(ans)


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	s = input()
	best = float('inf')
	total = s.count('1')
	for i in range(k):
		cur = [s[j] for j in range(i, n, k)]
		j = 0
		cnt = 0
		m = len(cur)
		while j < m:
			if cur[j] == '1':
				cnt += 1
			else:
				cnt = max(0, cnt - 1)
			best = min(total - cnt, best)
			j += 1
	print(best)


t = int(input())

def solve(N, K, A):
	P = [0]
	for x in A:
		P.append(P[-1] + x)
	for _ in range(K + 1):
		P.append(P[-1])
	ans = sum(A)
	if ans > 0:
		ans -= 1
	INF = float('inf')
	dp = [INF] * (N + 1)
	for i in range(N - 1, -1, -1):
		cost = A[i] ^ 1
		dp[i] = basecost = cost + P[-1] - P[i + 1]
		if i + K < N:
			cand = cost + P[i + K] - P[i + 1] + dp[i + K]
			if cand < basecost:
				dp[i] = cand
	s = 0
	for (i, x) in enumerate(A):
		dp[i] += s
		s += x
	ans2 = min(dp)
	if ans2 < ans:
		ans = ans2
	return ans
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	s = list(map(int, list(input())))
	print(solve(n, k, s))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	S = input().strip()
	DIV = [[] for i in range(k)]
	SUM1 = 0
	for i in range(n):
		if S[i] == '0':
			DIV[i % k].append(0)
		else:
			DIV[i % k].append(1)
			SUM1 += 1
	ANS = 1 << 30
	for i in range(k):
		A = SUM1 - DIV[i].count(1)
		LEN = len(DIV[i])
		DP0 = [1 << 30] * (LEN + 1)
		DP1 = [1 << 30] * (LEN + 1)
		DP2 = [1 << 30] * (LEN + 1)
		DP0[0] = 0
		DP1[0] = 0
		DP2[0] = 0
		for j in range(LEN):
			if DIV[i][j] == 0:
				DP0[j + 1] = DP0[j]
				DP1[j + 1] = min(DP0[j] + 1, DP1[j] + 1)
				DP2[j + 1] = min(DP2[j], DP1[j])
			else:
				DP0[j + 1] = DP0[j] + 1
				DP1[j + 1] = min(DP0[j], DP1[j])
				DP2[j + 1] = min(DP2[j] + 1, DP1[j] + 1)
		ANS = min(ANS, A + min(DP0[-1], DP1[-1], DP2[-1]))
	print(ANS)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nlargest, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, log
from collections import defaultdict as dd, deque, Counter as C, OrderedDict as od
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353
inf = int(1e+20)

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	(n, k) = sp()
	s = data()
	temp = s.count('1')
	answer = temp
	for i in range(k):
		cnt = 0
		for j in range(i, n, k):
			cnt += (-1, 1)[s[j] == '1']
			cnt = max(cnt, 0)
			answer = min(answer, temp - cnt)
	out(answer)


qqq = int(input())
ans = []
for _ in range(qqq):
	(n, k) = [int(x) for x in input().split()]
	s = input()
	res = 10 ** 9
	tot = sum((int(x) for x in s))
	for rem in range(k):
		c = s[rem:n:k]
		m = len(c)
		cnt = sum((int(x) for x in c))
		dp = [[0, 0, 0]]
		for x in c:
			if x is '0':
				dp.append([dp[-1][0], min(dp[-1][0], dp[-1][1]) + 1, min(dp[-1])])
			else:
				dp.append([dp[-1][0] + 1, min(dp[-1][0], dp[-1][1]), min(dp[-1]) + 1])
		res = min(res, tot - cnt + min(dp[-1]))
	ans.append(res)
print('\n'.join((str(x) for x in ans)))


tcs = int(input())
for tc in range(tcs):
	(n, k) = map(int, input().split())
	s = input()
	total = 0
	for i in range(n):
		if s[i] == '1':
			total += 1
	ans = total
	for i in range(k):
		dif = 0
		for j in range(i, n, k):
			if s[j] == '1':
				dif += 1
			else:
				dif -= 1
			dif = max(dif, 0)
			ans = min(ans, total - dif)
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	totsum = len(s.replace('0', ''))
	ans = totsum
	for i in range(0, k):
		prefsum = 0
		for j in range(i, n, k):
			prefsum += 1 if s[j] == '1' else -1
			prefsum = max(prefsum, 0)
			ans = min(ans, totsum - prefsum)
	print(ans)


def findMinToMakeOneModHaveAtMost1GroupOfOnes(oneSArr):
	n = len(oneSArr)
	dp1left = [0 for _ in range(n)]
	dp2left = [0 for _ in range(n)]
	for i in range(n):
		if i > 0:
			dp1left[i] += dp1left[i - 1]
			dp2left[i] = min(dp1left[i - 1], dp2left[i - 1])
		if oneSArr[i] == 0:
			dp2left[i] += 1
		if oneSArr[i] == 1:
			dp1left[i] += 1
	dp1right = [0 for _ in range(n)]
	dp2right = [0 for _ in range(n)]
	for i in range(n - 1, -1, -1):
		if i + 1 < n:
			dp1right[i] += dp1right[i + 1]
			dp2right[i] = min(dp1right[i + 1], dp2right[i + 1])
		if oneSArr[i] == 0:
			dp2right[i] += 1
		if oneSArr[i] == 1:
			dp1right[i] += 1
	ans = inf
	for i in range(n - 1):
		ans = min(ans, dp1left[i] + dp1right[i + 1], dp1left[i] + dp2right[i + 1], dp2left[i] + dp1right[i + 1], dp2left[i] + dp2right[i + 1])
	if ans == inf:
		ans = 0
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inf = float('inf')
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = [int(x) for x in input()]
	oneCntsMod = [0 for _ in range(k)]
	sArr = [[] for _ in range(k)]
	for i in range(n):
		if s[i] == 1:
			oneCntsMod[i % k] += 1
		sArr[i % k].append(s[i])
	total1s = sum(oneCntsMod)
	ans = inf
	for i in range(k):
		ans = min(ans, total1s - oneCntsMod[i] + findMinToMakeOneModHaveAtMost1GroupOfOnes(sArr[i]))
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	all = s.count('1')
	s = s.strip('0')
	new_len = len(s)
	ans = new_len
	for i in range(k):
		cnt0 = 0
		cnt1 = 0
		succ = 0
		for j in range(i, new_len, k):
			if s[j] == '0':
				cnt0 += 1
				succ = max(succ - 1, 0)
			else:
				succ += 1
				cnt1 += 1
			ans = min(ans, all - cnt1 + cnt0, all - succ)
	print(ans)


from collections import defaultdict
from math import inf
T = int(input().rstrip())
for _ in range(T):
	(n, k) = map(int, input().rstrip().split())
	cum_before = list()
	cum_after = list()
	bitset = list()
	tot = 0
	for x in map(lambda a: a == '1', input().rstrip()):
		bitset.append(x)
		cum_before.append(tot)
		if x:
			tot += 1
		cum_after.append(tot)
	dp = [-1 for _ in range(n + 1)]
	dp[n] = inf
	for i in range(k):
		dp[i] = cum_before[i]
	for i in range(n):
		if dp[i] < 0:
			continue
		if i + k >= n:
			dp[n] = min(dp[n], tot, dp[i] + tot - cum_after[i] + (0 if bitset[i] else 1))
		else:
			dp[i + k] = min(cum_before[i + k], dp[i] + (0 if bitset[i] else 1) + (cum_before[i + k] - cum_after[i]))
			dp[n] = min(dp[n], dp[i] + tot - cum_after[i] + (0 if bitset[i] else 1))
	print(dp[-1])


T = int(input())
while T != 0:
	T -= 1
	ans = 10 ** 9
	(n, k) = map(int, input().split())
	s = input()
	tot = s.count('1')
	for i in range(k):
		sum = 0
		maxn = 0
		for j in range(i, n, k):
			sum = max(0, sum - 1) if s[j] == '0' else sum + 1
			maxn = max(maxn, sum)
		ans = min(ans, tot - maxn)
	print(ans)


for i in range(int(input())):
	(n, k) = map(int, input().split())
	sr = input()
	dp = [0] * n
	per = [0] * n
	for i in range(n):
		if i == 0:
			per[i] = int(sr[i])
		else:
			per[i] = int(sr[i]) + per[i - 1]
	for i in range(n - 1, -1, -1):
		x = int(sr[i]) ^ 1
		if i + k - 1 < n:
			x += per[i + k - 1] - per[i]
		else:
			x += per[n - 1] - per[i]
		if i + k < n:
			x += dp[i + k]
		temp = per[n - 1] - per[i] + int(sr[i])
		dp[i] = min(x, temp)
	ct = 1000000000000000
	for i in range(n):
		val = dp[i]
		if i > 0:
			val += per[i - 1]
		ct = min(ct, val)
	print(ct)


import sys
input = lambda : sys.stdin.readline().strip()
t = int(input())
while t:
	t -= 1
	(n, k) = map(int, input().split())
	s = input()
	if n == 1:
		print(0)
		continue
	tot = 0
	for i in range(n):
		if s[i] == '1':
			tot += 1
	ans = tot
	for i in range(k):
		dif = 0
		for j in range(i, n, k):
			if s[j] == '1':
				dif += 1
			else:
				dif -= 1
			dif = max(dif, 0)
			ans = min(ans, tot - dif)
	print(ans)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = list(input())
	count = [0]
	for j in range(n):
		if s[j] == '1':
			count.append(count[-1] + 1)
		else:
			count.append(count[-1])
	ans = count[-1]
	dp = []
	for j in range(n):
		cost = count[j]
		if j >= k:
			cost = min(cost, dp[j - k] + count[j] - count[j - k + 1])
		if s[j] == '0':
			cost += 1
		dp.append(cost)
		ans = min(ans, cost + count[-1] - count[j + 1])
	print(ans)


import sys
input = sys.stdin.readline

def main():
	test = int(input())
	for _ in range(test):
		(n, k) = map(int, input().split())
		ara = input()
		total = 0
		for i in range(n):
			total += int(ara[i] == '1')
		ans = total
		for i in range(k):
			dif = 0
			for j in range(i, n, k):
				if ara[j] == '1':
					dif += 1
				else:
					dif -= 1
				dif = max(dif, 0)
				ans = min(ans, total - dif)
		print(ans)
main()


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

def li():
	return list(map(int, sys.stdin.readline().split()))

def mp():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(sys.stdin.readline())

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	(n, k) = mp()
	s = st()
	ans = INF
	l = list(map(int, s))
	su = sum(l)
	for i in range(k):
		c = 0
		for j in range(i, n, k):
			if l[j] == 1:
				c += 1
			else:
				c -= 1
			c = max(c, 0)
			ans = min(ans, su - c)
	pr(ans)
for _ in range(inp()):
	solve()


import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
import heapq as h, time
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def getInt():
	return int(input())

def getStrs():
	return input().split()

def getInts():
	return list(map(int, input().split()))

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def getBin():
	return list(map(int, list(input())))

def isInt(s):
	return '0' <= s[0] <= '9'

def ceil_(a, b):
	return a // b + (a % b > 0)
MOD = 10 ** 9 + 7

def solve():
	(N, K) = getInts()
	S = getBin()
	pref = [0]
	curr = 0
	for s in S:
		curr += s
		pref.append(curr)
	dp = [0 for i in range(N + 1)]
	dp[0] = 10 ** 18
	S = [0] + S
	for i in range(1, N + 1):
		dp[i] = pref[i - 1] + (S[i] ^ 1)
		if i > K:
			dp[i] = min(dp[i], dp[i - K] + pref[i - 1] - pref[i - K] + (S[i] ^ 1))
	ans = pref[-1]
	for i in range(1, N + 1):
		ans = min(ans, dp[i] + pref[-1] - pref[i])
	return ans
for _ in range(getInt()):
	print(solve())


import sys
input = sys.stdin.readline

def garland(arr, n, k):
	ps = [int(arr[0])]
	for i in range(1, len(arr) - 1):
		ps.append(int(arr[i]) + ps[-1])
	dp = [[0, 0, None] for i in range(len(arr) - 1)]
	if arr[0] == '1':
		dp[0] = [1, 0, 0]
	else:
		dp[0] = [0, 1, 1]
	for i in range(1, len(arr) - 1):
		if i - k >= 0:
			dp[i][1] = 1 - int(arr[i]) + min(dp[i - k][1], dp[i - k][2]) + ps[i - 1] - ps[i - k]
		else:
			dp[i][1] = 1 - int(arr[i]) + ps[i - 1]
		dp[i][0] = int(arr[i]) + min(dp[i - 1][1], dp[i - 1][0], dp[i - 1][2])
		dp[i][2] = 1 - int(arr[i]) + ps[i - 1]
	return min(dp[-1][0], dp[-1][1], dp[-1][2])

def solution():
	arr = list(map(lambda x: int(x), input().split()))
	n = arr[0]
	k = arr[1]
	arr = input()
	print(garland(arr, n, k))
t = int(input())
for i in range(0, t):
	solution()


def input1(type=int):
	return type(input())

def input2(type=int):
	[a, b] = list(map(type, input().split()))
	return (a, b)

def input3(type=int):
	[a, b, c] = list(map(type, input().split()))
	return (a, b, c)

def input_array(type=int):
	return list(map(type, input().split()))

def input_string():
	s = input()
	return list(s)

def get_val(l, r, cum):
	if l == r:
		return 0
	res = cum[r]
	if l != 0:
		res -= cum[l - 1]
	return res

def main():
	t = input1()
	for ci in range(t):
		(n, m) = input2()
		arr = list(map(int, input_string()))
		tot_on = 0
		last = -1
		res = 2000000.0
		for i in range(0, n):
			if arr[i] == 1:
				tot_on += 1
				last = i
		dp = [0 for _ in range(n + 2)]
		for i in range(last + 1):
			now = 0
			if arr[i] == 1:
				now += 1
			else:
				now -= 1
			dp[i % m] += now
			dp[i % m] = max(dp[i % m], 0)
			res = min(res, tot_on - dp[i % m])
		res = 0 if last == -1 else res
		print(res)
	return
main()


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split(' ')))
	s = input()
	a = [0] * k
	total = 0
	for (i, ch) in enumerate(s):
		if ch == '1':
			a[i % k] += 1
			total += 1
	res = n
	for start in range(k):
		last = -1
		b = [0, n, n]
		c = [0, 0, 0]
		for j in range(start, n, k):
			if s[j] == '1':
				c[0] = b[0] + 1
				c[1] = min(b[0], b[1])
				c[2] = min(b[1], b[2]) + 1
			else:
				c[0] = b[0]
				c[1] = min(b[0], b[1]) + 1
				c[2] = min(b[1], b[2])
			tmp = b
			b = c
			c = tmp
		res = min(res, total - a[start] + min(b[0], b[1], b[2]))
	print(res)


t = int(input())
for tt in range(t):
	global positions
	global total_ones
	global n
	global k
	global s
	(n, k) = [int(x) for x in input().split(' ')]
	s = input()
	total_ones = 0
	for x in s:
		total_ones += int(x)
	positions = []

	def changes_req(positions):
		summ = []
		sum_upto = [0]
		for position in positions:
			if s[int(position)] == '1':
				summ.append(-1)
			elif s[int(position)] == '0':
				summ.append(1)
			else:
				print('TNP')
		for i in range(len(summ)):
			sum_upto.append(summ[i] + sum_upto[-1])
		max_upto = [sum_upto[0]]
		for i in range(1, len(sum_upto)):
			max_upto.append(max(max_upto[-1], sum_upto[i]))
		sum_upto.reverse()
		min_after = [sum_upto[0]]
		for i in range(1, len(sum_upto)):
			min_after.append(min(min_after[-1], sum_upto[i]))
		sum_upto.reverse()
		min_after.reverse()
		ans = n
		for i in range(len(sum_upto)):
			ans = min(ans, round(min_after[i] - max_upto[i]))
		return ans + total_ones

	def update_1(positions):
		for i in range(len(positions)):
			positions[i] += 1
		if positions[-1] >= n:
			positions.pop()
	positions = []
	position = 0
	while position < n:
		positions.append(position)
		position += k
	ans = n
	for i in range(k):
		ans = min(ans, changes_req(positions))
		update_1(positions)
	print(ans)


t = int(input())
while t > 0:
	t -= 1
	(n, k) = map(int, input().split())
	s = input()
	(cnt, v) = ([0] * k, [list() for i in range(k)])
	ans = 0
	for i in range(n):
		if s[i] == '1':
			cnt[i % k] += 1
			ans += 1
		v[i % k].append(int(s[i]))
	tot = ans
	for i in range(k):
		curAns = tot - cnt[i]
		(tot0, tot1) = (0, 0)
		mnsum = 0
		for j in range(len(v[i])):
			if v[i][j] == 0:
				tot0 += 1
			else:
				tot1 += 1
			ans = min(ans, curAns + mnsum + tot0 + (cnt[i] - tot1))
			mnsum = min(mnsum, tot1 - tot0)
	print(ans)


import sys

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())
t = fi()
while t > 0:
	t -= 1
	(n, k) = mi()
	a = si()
	c = a.count('1')
	mini = 10 ** 18
	dp = [[0, 0] for i in range(n)]
	for i in range(k):
		p = 0
		f = 0
		for j in range(i, n, k):
			dp[f] = [0, 0]
			if a[j] == '1':
				p += 1
			if f == 0:
				dp[f][0] = int(a[j] == '1')
				dp[f][1] = int(a[j] == '0')
			else:
				dp[f][0] = dp[f - 1][0] + int(a[j] == '1')
				dp[f][1] = min(dp[f - 1]) + int(a[j] == '0')
			f += 1
		cd = 10 ** 18
		for j in range(f):
			cd = min(cd, dp[j][1] + dp[f - 1][0] - dp[j][0])
		cd = min(dp[f - 1][0], cd)
		mini = min(mini, c - p + cd)
	print(mini)


t = int(input())
while t:
	t -= 1
	(n, k) = list(map(int, input().split()))
	lamps = input()
	ones = 0
	for i in range(n):
		if lamps[i] == '1':
			ones += 1
	ans = ones
	for i in range(k):
		temp = 0
		for j in range(i, n, k):
			if lamps[j] == '1':
				temp += 1
			else:
				temp -= 1
			temp = max(0, temp)
			ans = min(ans, ones - temp)
	print(ans)


import sys
import math
from collections import defaultdict, deque
t = int(sys.stdin.readline())
for _ in range(t):
	(n, k) = map(int, sys.stdin.readline().split())
	s = sys.stdin.readline()[:-1]
	dic = defaultdict(int)
	total = 0
	on = defaultdict(int)
	last = defaultdict(int)
	for i in range(n):
		if s[i] == '1':
			last[i % k] = i
			total += 1
	ans = n
	cnt = 0
	for i in range(n):
		if s[i] == '1':
			cnt += 1
			dic[i % k] += 1
			off = total - dic[i % k] + on[i % k]
			ans = min(ans, off)
			continue
		if dic[i % k] != 0:
			on[i % k] += 1
		if on[i % k] >= dic[i % k]:
			dic[i % k] = 0
			on[i % k] = 0
		off = total - dic[i % k] + on[i % k]
		ans = min(ans, off)
	if cnt == 0:
		print(0)
		continue
	print(ans)


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	s = input()
	if n == 1:
		print(0)
		continue
	c1 = s.count('1')
	ma = c1
	for i in range(k):
		l = 0
		for j in range(i, n, k):
			if s[j] == '1':
				l = l + 1
			else:
				l = l - 1
			l = max(l, 0)
			ma = min(ma, c1 - l)
	print(ma)


import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = pow(10, 9) + 7

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def solve():
	(n, k) = sep()
	s = input()
	cnt1 = s.count('1')
	mm = 10 ** 9
	for i in range(0, k):
		temp = []
		for j in range(i, n, k):
			temp.append(int(s[j]))
		pre = [0]
		for j in range(0, len(temp)):
			pre.append(pre[j] + temp[j])
		minlterm = 10 ** 9
		ans1 = 10 ** 9
		for j in range(0, len(temp)):
			minlterm = min(minlterm, 2 * pre[j] - j)
			ans1 = min(ans1, j + 1 + pre[len(temp)] + minlterm - 2 * pre[j + 1])
		mm = min(mm, ans1 + (cnt1 - pre[len(temp)]))
		mm = min(mm, cnt1)
	print(mm)
testcase(int(inp()))


def max_subarray(s):
	best_sum = 0
	best_start = best_end = 0
	current_sum = 0
	for (current_end, x) in enumerate(s):
		x = 1 if x == '1' else -1
		if current_sum <= 0:
			current_start = current_end
			current_sum = x
		else:
			current_sum += x
		if current_sum > best_sum:
			best_sum = current_sum
			best_start = current_start
			best_end = current_end + 1
	return (best_sum, best_start, best_end)

def min_changes(s):
	(best_sum, best_start, best_end) = max_subarray(s)
	changes = s[best_start:best_end].count('0') + s[:best_start].count('1') + s[best_end:].count('1')
	return changes
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = str(input())
	ones = s.count('1')
	min_moves = n
	for i in range(k):
		substring = s[i::k]
		substring_ones = substring.count('1')
		changes = min_changes(substring)
		cost = changes + ones - substring_ones
		if cost < min_moves:
			min_moves = cost
	print(min_moves)


from collections import defaultdict
from itertools import accumulate
import sys
input = sys.stdin.readline
inf = 100000000000000000
mod = 998244353
for CASES in range(int(input())):
	(n, k) = map(int, input().split())
	S = list(input().strip())
	F = [[0] * 2 for _ in range(n + n + 10)]
	SUM0 = [0] * (n + 1)
	SUM1 = [0] * (n + 1)
	for i in range(n):
		SUM0[i] = SUM0[i - 1]
		SUM1[i] = SUM1[i - 1]
		if S[i] == '0':
			SUM0[i] += 1
		else:
			SUM1[i] += 1
	for i in range(n):
		F[i][0] = SUM1[i - 1] - SUM1[-1] + SUM0[i] - SUM0[i - 1]
	for i in range(k):
		F[i][1] = inf
	for i in range(k, n):
		F[i][1] = min(F[i - k][0], F[i - k][1]) + SUM1[i - 1] - SUM1[i - k] + SUM0[i] - SUM0[i - 1]
	ans = SUM1[n - 1]
	for i in range(n):
		ans = min(ans, F[i][0] + SUM1[n - 1] - SUM1[i])
	for i in range(k, n):
		ans = min(ans, F[i][1] + SUM1[n - 1] - SUM1[i])
	print(ans)


for ii in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	t = [int(i) for i in s]
	if n == 1:
		print(0)
	else:
		dic = {}
		for i in range(k):
			dic[i] = 0
		for i in range(len(t)):
			if t[i] == 1:
				dic[i % k] += 1
		G = []
		for i in range(k):
			a = []
			index = i
			while index < n:
				a.append(index)
				index += k
			prefix2 = []
			l1 = 0
			for j in a:
				if t[j] == 1:
					l1 += 1
				prefix2.append(l1)
			b = [0 for i in range(len(a))]
			b[0] = 0 if t[a[0]] == 1 else 1
			g = prefix2[-1] - prefix2[0] + b[0]
			for j in range(1, len(a)):
				b[j] = min(prefix2[j - 1], b[j - 1]) + (t[a[j]] != 1)
				g = min(prefix2[-1] - prefix2[j] + b[j], g)
			G.append(g)
		ans = sum(dic.values())
		h = ans
		for i in range(k):
			ans = min(ans, G[i] + h - dic[i])
		print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	pre = [0 for i in range(n)]
	steps = [0 for i in range(n)]
	su = 0
	for i in range(1, n):
		su += int(s[i - 1])
		pre[i] = su
	sol = steps[n - 1] + pre[n - 1]
	for i in range(n - 2, -1, -1):
		if i >= n - k:
			steps[i] = pre[n - 1] + int(s[n - 1]) - pre[i + 1]
		else:
			x = pre[i + k] - pre[i + 1] + 1 - int(s[i]) + steps[i + k]
			y = pre[n - 1] - pre[i + 1] + int(s[i] + s[n - 1])
			steps[i] = min(x, y)
		sol = min(sol, steps[i] + pre[i])
	print(sol)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split(' '))
	s = input()
	y = []
	for i in s:
		y.append(i)
	totalones = y.count('1')
	i = 0
	m = 0
	countone = 0
	while i < k:
		m = 0
		for j in range(i, n, k):
			if y[j] == '1':
				m += 1
			else:
				m -= 1
				if m < 0:
					m = 0
			countone = max(m, countone)
		i += 1
	print(totalones - countone)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
from collections import deque
for _ in range(int(input()) if True else 1):
	(n, k) = map(int, input().split())
	s = input()
	total1 = s.count('1')
	ans = total1
	for __ in range(k):
		a = [s[p] for p in range(__, n, k)]
		last_one = [0]
		first_one = [0]
		one = 0
		for i in range(len(a) - 1, -1, -1):
			one += int(a[i])
			last_one += [one]
		one = 0
		for i in a:
			one += int(i)
			first_one += [one]
		dp = [0] * len(a)
		for i in range(len(a)):
			if i == 0:
				dp[i] = 1 - int(a[0])
				ans = min(ans, dp[i] + last_one[len(a) - i - 1] + (total1 - one))
				continue
			dp[i] = min(dp[i - 1], first_one[i]) + (1 - int(a[i]))
			ans = min(ans, dp[i] + last_one[len(a) - i - 1] + (total1 - one))
	print(ans)


def rs():
	return input().strip()

def ri():
	return int(input())

def ria():
	return list(map(int, input().split()))

def ia_to_s(a):
	return ' '.join([str(s) for s in a])

def solve(s, n, k):
	all_ones = 0
	for i in range(n):
		if s[i] == '1':
			all_ones += 1
	res = all_ones
	for i in range(k):
		d = 0
		for j in range(i, n, k):
			if s[j] == '1':
				d += 1
			if s[j] == '0':
				d -= 1
			if d < 0:
				d = 0
			res = min(res, all_ones - d)
	return res

def main():
	for _ in range(ri()):
		(n, k) = ria()
		s = rs()
		print(solve(s, n, k))
main()


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	s = input().strip()
	arr = []
	for i in range(k + 1):
		arr.append([])
	tot = 0
	for i in range(len(s)):
		if s[i] == '1':
			tot += 1
	for i in range(n):
		if s[i] == '1':
			arr[i % k].append(1)
		else:
			arr[i % k].append(-1)
	ans = 0
	for i in range(k):
		cur = 0
		for j in arr[i]:
			cur += j
			if cur < 0:
				cur = 0
			ans = max(ans, cur)
	print(tot - ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
mod = int(1000000000.0) + 7

def power(k, n):
	if n == 0:
		return 1
	if n % 2:
		return power(k, n - 1) * k % mod
	t = power(k, n // 2)
	return t * t % mod

def totalPrimeFactors(n):
	count = 0
	if n % 2 == 0:
		count += 1
		while n % 2 == 0:
			n //= 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			count += 1
			while n % i == 0:
				n //= i
		i += 2
	if n > 2:
		count += 1
	return count

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		S = input()
		s = []
		pre = []
		for i in S:
			if i == '0' or i == '1':
				s.append(int(i))
				pre.append(int(i))
		for i in range(1, len(pre)):
			pre[i] += pre[i - 1]
		ans = pre[-1]
		if n == 1:
			ans = 0
		for i in range(k):
			t = []
			for j in range(i, n, k):
				t.append(s[j])
			curr = 0
			for j in range(len(t)):
				if t[j] == 0:
					curr -= 1
				if t[j] == 1:
					curr += 1
				if curr < 0:
					curr = 0
				ans = min(ans, pre[-1] - curr)
		print(ans)
	return
main()