This is a hard version of this problem.The only difference is $$$2 \leq k \leq 50$$$ in this version.
You are given a binary array $$$a$$$ of size $$$n$$$ consisting of $$$0$$$ or $$$1$$$.
You can do the following operation any number of times:
Your goal is to make $$$a$$$ satisfy the following condition:
Find the minimum number of operations you need. It can be proven that your goal is always able to be realized.
The first line of the input contains a single integer $$$t$$$($$$1\le t\le 10^5$$$) — the number of test cases. The description of test cases follows.
The first line of each test case contains two integers $$$n,k$$$($$$4\le n\le 5\cdot 10^5$$$,$$$2\leq k \leq 50$$$).
Then one line follows, containing $$$n$$$ integers $$$a_1,a_2,\cdots,a_n$$$($$$0\le a_i\le 1$$$).
It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
For each test case, output a single line — the minimum number of operations.
54 501 1 1 17 41 1 0 1 1 1 18 31 1 0 1 1 1 1 110 21 1 1 1 1 1 0 0 0 114 51 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 3 15 6
Test Case $$$1$$$:
You don't need to do any operation.
Test Case $$$2$$$:
You only need to choose $$$i=5$$$. After your operation,$$$a=[1,1,0,0,1,0,1]$$$.
Test Case $$$3$$$: