#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
vector<int>g[N];
int n,v[N],idx[N],vis[N],id,low,SRC;
vector<int>res,temp;

void DFS(int v){
    if(v<low){
        low=v;
        res=temp;
    }
    vis[v]=id;
    for(size_t a=0;a<g[v].size();++a){
        int u=g[v][a];
        if(vis[u]==id||u<SRC)
            continue;
        temp.push_back(u);
        DFS(u);
        temp.pop_back();
    }
}

int main(){
//  freopen("read.txt","r",stdin);
    scanf("%d",&n);
    for(int a=0;a<n;++a){
        scanf("%d",v+a);
        --v[a];
        idx[v[a]]=a;
    }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b){
            char ch;
            scanf(" %c",&ch);
            if(ch=='1')
                g[a].push_back(b);
        }
    for(int a=0;a<n;++a){
        ++id;
        SRC=a,low=idx[a];
        res.clear();
        temp=vector<int>(1,idx[a]);
        DFS(idx[a]);
        for(size_t a=1;a<res.size();++a)
            swap(v[res[a]],v[res[a-1]]);
    }
    for(int a=0;a<n;++a)
        printf("%d ",v[a]+1);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
int n,arr[N],idx[N],g[N][N],id,vis[N],par[N];
vector<int>adj[N];

bool BFS(int str,int tar){
    queue<int>qu;
    vis[str]=++id;
    par[str]=-1;
    qu.push(str);
    while(qu.size()){
        int v=qu.front();
        qu.pop();
        for(size_t a=0;a<adj[v].size();++a){
            int u=adj[v][a];
            if(vis[u]==id||arr[u]<arr[str])
                continue;
            vis[u]=id;
            par[u]=v;
            qu.push(u);
            if(u==tar){
                vector<int>path;
                for(int u=tar;u!=-1;u=par[u])
                    path.push_back(u);
                reverse(path.begin(),path.end());
                for(size_t a=1;a<path.size();++a)
                    swap(arr[path[a-1]],arr[path[a]]);
                for(int a=0;a<n;++a)
                    idx[arr[a]]=a;
                return true;
            }
        }
    }
    return false;
}

int main(int argc, char **argv){
//  freopen("a","r",stdin);
    scanf("%d",&n);
    for(int a=0;a<n;++a){
        scanf("%d",arr+a);
        --arr[a];
        idx[arr[a]]=a;
    }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b){
            char ch;
            scanf(" %c",&ch);
            if(ch=='1')
                g[a][b]=1,adj[a].push_back(b);
        }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b)
            for(int c=0;c<n;++c)
                g[b][c]|=g[b][a]&g[a][c];
    for(int a=0;a<n;++a)
        for(int b=0;b<idx[a];++b)
            if(g[idx[a]][b]&&BFS(idx[a],b))
                break;
    string s="";
    for(int a=0;a<n;++a,s=" ")
        printf("%s%d",s.c_str(),arr[a]+1);
    puts("");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
int n,arr[N],idx[N],g[N][N],id,vis[N],par[N];
vector<int>adj[N];

bool BFS(int str,int tar){
    queue<int>qu;
    vis[str]=++id;
    par[str]=-1;
    qu.push(str);
    while(qu.size()){
        int v=qu.front();
        qu.pop();
        for(size_t a=0;a<adj[v].size();++a){
            int u=adj[v][a];
            if(vis[u]==id||arr[u]<arr[str])
                continue;
            vis[u]=id;
            par[u]=v;
            qu.push(u);
            if(u==tar){
                vector<int>path;
                for(int u=tar;u!=-1;u=par[u])
                    path.push_back(u);
                reverse(path.begin(),path.end());
                for(size_t a=1;a<path.size();++a)
                    swap(arr[path[a-1]],arr[path[a]]);
                for(int a=0;a<n;++a)
                    idx[arr[a]]=a;
                return true;
            }
        }
    }
    return false;
}

int main(int argc, char **argv){
//  freopen("a","r",stdin);
    scanf("%d",&n);
    for(int a=0;a<n;++a){
        scanf("%d",arr+a);
        --arr[a];
        idx[arr[a]]=a;
    }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b){
            char ch;
            scanf(" %c",&ch);
            if(ch=='1')
                g[a][b]=g[b][a]=1,adj[a].push_back(b),adj[b].push_back(a);
        }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b)
            for(int c=0;c<n;++c)
                g[b][c]|=g[b][a]&g[a][c];
    for(int a=0;a<n;++a)
        for(int b=0;b<idx[a];++b)
            if(g[idx[a]][b]&&BFS(idx[a],b))
                break;
    string s="";
    for(int a=0;a<n;++a,s=" ")
        printf("%s%d",s.c_str(),arr[a]+1);
    puts("");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
int n,arr[N],vis[N],idx[N],id;
vector<int>g[N],mv;
pair<int,vector<int> >res;

void DFS(int v,int w){
	vis[v]=id;
	mv.push_back(v);
	res=min(res,make_pair(v,mv));
	for(size_t a=0;a<g[v].size();++a){
		int u=g[v][a];
		if(vis[u]==id||arr[u]<w)
			continue;
		DFS(u,w);
	}
	mv.pop_back();
}

int main(int argc, char **argv){
//	freopen("a","r",stdin);
	scanf("%d",&n);
	for(int a=0;a<n;++a){
		scanf("%d",arr+a);
		--arr[a];
		idx[arr[a]]=a;
	}
	for(int a=0;a<n;++a)
		for(int b=0;b<n;++b){
			char ch;
			scanf(" %c",&ch);
			if(ch=='1')
				g[a].push_back(b);
		}
	for(int a=0;a<n;++a){
		++id;
		res=make_pair(idx[a],vector<int>());
		DFS(idx[a],a);
		for(size_t a=1;a<res.second.size();++a)
			swap(arr[res.second[a]],arr[res.second[a-1]]);
		for(int a=0;a<n;++a)
			idx[arr[a]]=a;
	}
	for(int a=0;a<n;++a)
		printf("%d ",arr[a]+1);
	puts("");
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
int n,v[N],p[N],r[N],res[N];
vector<int>comp[N];

int find(int x){
    if(x==p[x])
        return x;
    return p[x]=find(p[x]);
}

void link(int x,int y){
    x=find(x);
    y=find(y);
    if(x!=y){
        if(r[x]>r[y])
            swap(x,y);
        p[x]=y;
        if(r[x]==r[y])
            ++r[y];
    }
}

void calc(){
    map<int,int>hs;
    int id=0;
    for(int a=0;a<n;++a){
        int x=find(a);
        if(hs.find(x)==hs.end())
            hs[x]=id++;
        comp[hs[x]].push_back(a);
    }
    for(int a=0;a<id;++a){
        vector<int>with;
        for(size_t b=0;b<comp[a].size();++b)
            with.push_back(v[comp[a][b]]);
        sort(with.begin(),with.end());
        for(size_t b=0;b<comp[a].size();++b)
            res[comp[a][b]]=with[b];
    }
}

int main(int argc, char **argv){
//  freopen("a","r",stdin);
    scanf("%d",&n);
    for(int a=0;a<n;++a){
        scanf("%d",v+a);
        p[a]=a,r[a]=1;
    }
    for(int a=0;a<n;++a){
        getchar();
        for(int b=0;b<n;++b){
            char ch=getchar();
            if(ch=='1')
                link(a,b);
        }
    }
    calc();
    string s="";
    for(int a=0;a<n;++a,s=" ")
        printf("%s%d",s.c_str(),res[a]);
    puts("");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

/*
 * You got a dream, you gotta protect it.
 */

const int N=300;
int n,arr[N],vis[N],idx[N],id;
vector<int>mv,res;
int B;
char g[N+9][N+9];

void DFS(int v,int w){
    vis[v]=id;
    mv.push_back(v);
    if(v<B)
        B=v,res=mv;
    for(int a=0;a<n;++a)
        if(g[v][a]=='1'&&vis[a]!=id&&arr[a]>w)
            DFS(a,w);
    mv.pop_back();
}

int main(int argc, char **argv){
//  freopen("a","r",stdin);
    scanf("%d",&n);
    for(int a=0;a<n;++a){
        scanf("%d",arr+a);
        --arr[a];
        idx[arr[a]]=a;
    }
    for(int a=0;a<n;++a)
        scanf("%s",g[a]);
    for(int a=0;a<n;++a){
        ++id;
        B=idx[a];
        res.clear();
        DFS(idx[a],a);
        for(size_t a=1;a<res.size();++a)
            swap(arr[res[a]],arr[res[a-1]]);
        for(int a=0;a<n;++a)
            idx[arr[a]]=a;
    }
    for(int a=0;a<n;++a)
        printf("%d ",arr[a]+1);
    puts("");
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
//        memset(a, 0, sizeof(a));
//        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i]);
            for(int j = 0; j < n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;

                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = i + 1; j <= n; ++j) {
                if(num[i] > num[j]) {
                    if(a[i][j - 1] == '1') {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
//        for(int i = 1; i <= n; ++i) {
//            for(int j = 0; j <= n; ++j) {
//                if(a[i][j] == '1') {
//                    if(i < j + 1 && num[i] > num[j + 1]) {
//                        int t = num[i];
//                        num[i] = num[j + 1];
//                        num[j + 1] = t;
//                    }
//                }
//            }
//        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
//        memset(a, 0, sizeof(a));
//        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i]);
            for(int j = 0; j < n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;

                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = 0; j <= n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;
                    }
                }
            }
        }

        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
int num[305];
char a[305][305];

int main()
{
//freopen("in", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }
        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
        }
        for(int i = 1; i <= n; ++i) {
            for(int k = 1; k <= n; ++k) {
                for(int j = 1; j <= n; ++j) {
                    if(a[k][i] == '1' && a[i][j] == '1')
                    a[k][j] = '1';
                }
            }
        }
        int ok = 1;
        while(ok) {
            ok = 0;
            for(int i = 1; i <= n; ++i) {
                for(int j = i + 1; j <= n; ++j) {
                    if(a[i][j] == '1' && num[i] > num[j]) {
                        ok = 1;
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        memset(a, 0, sizeof(a));
        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
            for(int j = 1; j <= n; ++j) {
                if(a[i][j] == '1' || a[j][i] == '1') {
                    if(i < j  && num[i] > num[j]) {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = i + 1; j <= n; ++j) {
                if(num[i] > num[j]) {
                    if(a[i][j] == '1' || a[j][i] == '1') {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        memset(a, 0, sizeof(a));
        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i]);
            for(int j = 0; j < n; ++j) {
                if(a[i][j] == '1' || a[j][i] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;
                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = i + 1; j <= n; ++j) {
                if(num[i] > num[j]) {
                    if(a[i][j - 1] == '1' || a[j-1][i] == '1') {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
//        for(int i = 1; i <= n; ++i) {
//            for(int j = 0; j <= n; ++j) {
//                if(a[i][j] == '1') {
//                    if(i < j + 1 && num[i] > num[j + 1]) {
//                        int t = num[i];
//                        num[i] = num[j + 1];
//                        num[j + 1] = t;
//                    }
//                }
//            }
//        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        memset(a, 0, sizeof(a));
        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
            for(int j = 1; j <= n; ++j) {
                if(a[i][j] == '1' || a[j][i] == '1') {
                    if(i < j  && num[i] > num[j]) {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = i + 1; j <= n; ++j) {
                if(num[i] > num[j]) {
                    if(a[i][j] == '1' || a[j][i] == '1') {
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
struct node {int x, d; }numb[305];
int num[305], fn[305];
char a[305][305];

bool cmp(node aa, node bb)
{
    return aa.x < bb.x;
}

int main()
{
//freopen("in", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
            fn[i] = num[i];
            numb[i].x = num[i];
            numb[i].d = i;
        }
        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
        }
        sort(numb + 1, numb + n + 1, cmp);
//        for(int i = 1; i <= n; ++i) {
//            printf("%d ", numb[i].x);
//        }
//        printf("\n");
        int ok = 1;
        while(ok) {
            ok = 0;
//            for(int i = 1; i <= n; ++i) {
//                printf("%d ", numb[i].d);
//            }
//            printf("\n");
            for(int i = 1; i <= n; ++i) {
                if( (num[i] < numb[i].x && i > numb[i].d) ||
                    (num[i] > numb[i].x && i < numb[i].d)) {
                    if( (a[i][numb[i].d] == '1') || (a[numb[i].d][i] == '1') ) {
                        ok = 1;
                        int t = num[i];
                        num[i] = num[numb[i].d];
                        num[numb[i].d] = t;

                        for(int j = 1; j <= n; ++j) {
                            if(numb[j].x == num[numb[i].d]) numb[j].d = numb[i].d;
                        }
                        numb[i].d = i;
                    }
                }
//                for(int i = 1; i <= n; ++i) {
//                    printf("%d ", numb[i].d);
//                }
//                printf("\n");
            }
        }

        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
//        memset(a, 0, sizeof(a));
//        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i]);
            for(int j = 0; j < n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;

                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = 0; j <= n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;
                    }
                }
            }
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = 0; j <= n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
int num[305];
char a[305][305];

int main()
{
//freopen("in", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }
        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
        }
        for(int i = 1; i <= n; ++i) {
            for(int k = 1; k <= n; ++k) {
                for(int j = 1; j <= n; ++j) {
                    if(a[k][i] == '1' && a[i][j] == '1')
                    a[k][j] = '1';
                }
            }
        }
        int ok = 1;
        for(int i = 1; i <= n; ++i) {
            for(int j = i + 1; j <= n; ++j) {
                if(a[i][j] == '1' && num[i] > num[j]) {
                    ok = 1;
                    swap(num[i], num[j]);
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
struct node {int x, d; }numb[305];
int num[305];
char a[305][305];

bool cmp(node aa, node bb)
{
    return aa.x < bb.x;
}

int main()
{
//freopen("in", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
            numb[i].x = num[i];
            numb[i].d = i;
        }
        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
        }
        //sort(numb + 1, numb + n + 1, cmp);
//        for(int i = 1; i <= n; ++i) {
//            printf("%d ", numb[i].x);
//        }
//        printf("\n");
        int ok = 1;
        while(ok) {
            ok = 0;
            for(int i = 1; i <= n; ++i) {
                for(int j = i + 1; j <= n; ++j) {
                    if( (a[i][j] == '1'|| a[j][i] == '1') && num[i] > num[j]) {
                        ok = 1;
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char a[305][305];
int num[305];

int main()
{
//freopen("inB", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
//        memset(a, 0, sizeof(a));
//        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }

        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i]);
            for(int j = 0; j < n; ++j) {
                if(a[i][j] == '1') {
                    if(i < j + 1 && num[i] > num[j + 1]) {
                        int t = num[i];
                        num[i] = num[j + 1];
                        num[j + 1] = t;

                    }
                }
            }
        }
        int cnt = 50;
        while(cnt--) {
            for(int i = 1; i <= n; ++i) {
                for(int j = 0; j <= n; ++j) {
                    if(a[i][j] == '1') {
                        if(i < j + 1 && num[i] > num[j + 1]) {
                            int t = num[i];
                            num[i] = num[j + 1];
                            num[j + 1] = t;
                        }
                    }
                }
            }
        }

//        for(int i = 1; i <= n; ++i) {
//            for(int j = 0; j <= n; ++j) {
//                if(a[i][j] == '1') {
//                    if(i < j + 1 && num[i] > num[j + 1]) {
//                        int t = num[i];
//                        num[i] = num[j + 1];
//                        num[j + 1] = t;
//                    }
//                }
//            }
//        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
int num[305];
char a[305][305];

int main()
{
//freopen("in", "r", stdin);
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &num[i]);
        }
        for(int i = 1; i <= n; ++i) {
            scanf("%s", a[i] + 1);
        }
        for(int i = 1; i <= n; ++i) {
            for(int k = 1; k <= n; ++k) {
                for(int j = 1; j <= n; ++j) {
                    if(a[i][k] == '1' && a[k][j] == '1')
                    a[i][j] = '1';
                }
            }
        }
        int ok = 1;
        while(ok) {
            ok = 0;
            for(int i = 1; i <= n; ++i) {
                for(int j = i; j <= n; ++j) {
                    if(a[i][j] == '1' && num[i] > num[j]) {
                        ok = 1;
                        int t = num[i];
                        num[i] = num[j];
                        num[j] = t;
                    }
                }
            }
        }
        printf("%d", num[1]);
        for(int i = 2; i <= n; ++i) {
            printf(" %d", num[i]);
        }
        printf("\n");
    }
    return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] || b[k][j])?true:b[i][j];

	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && b[i][j])
				{
					if (id==-1)
						id = j;
					else if (num2<v[id])
						id=j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] && b[k][j])?true:b[i][j];

	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && b[i][j])
				{
					if (id==-1)
						id = j;
					else if (num2<v[id])
						id=j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] && b[k][j])?true:b[i][j];

	for (int i=0;i<n-1;i++)
	{
		int num=v[i];
		int j = n-1;
		int id = -1;
		for (;j>i;j--)
		{
			int num2=v[j];
			if (num2<num && b[i][j])
			{
				v[i]=v[j];
				v[j]=num;
			}
		}
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i]<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] && b[k][j])?true:b[i][j];

	for (int i=0;i<n-1;i++)
	{
		int num=v[i];
		for (int j=i+1;j<n;j++)
		{
			if (v[j]<num && b[i][j])
			{
				v[i]=v[j];
				v[j]=num;
			}
		}
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i]<<" ";
	}
	cout<<endl;
	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}

	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && (b[i][j]||b[j][i]))
				{
					if (id==-1)
						id = j;
					else if (num2<v[id])
						id=j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] && b[k][j])?true:b[i][j];

	for (int i=0;i<n;i++)
	{
		int num=v[i];
		for (int j=i+1;j<n;j++)
		{
			if (v[j]<num && b[i][j])
			{
				v[i]=v[j];
				v[j]=num;
			}
		}
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i]<<" ";
	}
	cout<<endl;
	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}

	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && (b[i][j]||b[j][i]))
				{
					id = j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}

	}
	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && b[i][j])
				{
					id = j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	//sort(v.begin(),v.end());
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}

	bool alldone = false;
	while (!alldone)
	{
		bool entered=false;
		for (int i=0;i<n-1;i++)
		{
			int num=v[i];
			int j = n-1;
			int id = -1;
			for (;j>i;j--)
			{
				int num2=v[j];
				if (num2<num && b[i][j])
				{
					if (id==-1)
						id = j;
					else if (num2<v[id])
						id=j;
				}
			}
			if (id != -1)
			{
				entered =true;
				v[i]=v[id];
				v[id]=num;
			}
		}
		if (!entered) alldone=true;
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i];
		if (i < n-1) cout<<" ";
	}
	cout<<endl;
	return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <climits>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <utility>
using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef signed long l;
#ifndef ONLINE_JUDGE
FILE* pf = freopen("input.txt","r",stdin);
FILE* qf = freopen("output.txt","w",stdout);
#endif

int main()
{
	std::ios_base::sync_with_stdio(0);
	int n,t;
	cin>>n;
	vector<int> v(n);
	for (int i=0;i<n;i++) cin>>v[i];
	vector<vector<bool> > b(n, vector<bool>(n));
	for (int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;j<s.size();j++)
		{
			if(s[j]=='1') b[i][j]=true;
			else b[i][j]=false;
		}
	}
	for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i != j)
                    b[i][j] = (b[i][k] && b[k][j])?true:b[i][j];

	for (int i=0;i<n;i++)
	{
		for (int j=i+1;j<n;j++)
		{
			if (v[j]<v[i] && b[i][j])
			{
				swap(v[i],v[j]);
			}
		}
	}
	for (int i=0;i<n;i++)
	{
		cout<<v[i]<<" ";
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
    // your code goes here
    int n,t,x;
    scanf("%d", &n);
    int p[n+1];
    for(int i=1;i<=n;i++) scanf("%d", &p[i]);
    int a[n+1][n+1];
    for(int i=1;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            scanf("%d", &a[i][j]);
        }
    }
    /*for(int i=1;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            printf("%d", a[i][j]);
        }
        printf("\n");
    }*/

    for(int i=1;i<n;i++) {
        for(int j=i+1;j<=n;j++) {
            if(a[i][j]==1) {
                if(p[j]<p[i]) {t=p[i];p[i]=p[j];p[j]=t;}
            }
        }
    }

    for(int i=1;i<=n;i++) printf("%d ", p[i]);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
    // your code goes here
    int n,t,x;
    scanf("%d", &n);
    int p[n+1];
    for(int i=1;i<=n;i++) scanf("%d", &p[i]);
    int a[n+1][n+1];
    for(int i=1;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            scanf("%d", &a[i][j]);
        }
    }
    for(int i=1;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            printf("%d", a[i][j]);
        }
        printf("\n");
    }

    for(int i=1;i<n;i++) {
        for(int j=i+1;j<=n;j++) {
            if(a[i][j]==1) {
                if(p[j]<p[i]) {t=p[i];p[i]=p[j];p[j]=t;}
            }
        }
    }

    for(int i=1;i<=n;i++) printf("%d ", p[i]);
    return 0;
}


from sys import stdin

t = int(stdin.readline())
for _ in range(t):
	n, k = map(int, stdin.readline().split())
	s = stdin.readline()
	cnt = [[0 for i in range(26)] for j in range((k + 1) // 2)]
	for i in range(n):
		cnt[min(i % k, k - i % k - 1)][ord(s[i]) - ord('a')] += 1
	ans = 0
	for i in range(k // 2):
		ans += 2 * n // k - max(cnt[i])
	if k % 2 == 1:
		ans += n // k - max(cnt[k // 2])
	print(ans)


t=int(input())

def most_f(List):
    return max(set(List), key = List.count)

for test in range(t):

    n,k=[int(x) for x in input().split()]
    arr = list(input())
    #print(arr)
    allsame=True
    count=0
    end=k
    ev=0
    if n%2 == 0:
        ev=1
    for i in range(0,k//2+ev):
        valk = []
        end-=1
        #for j in range(i,n,k):
            #valk.append(arr[j])
        valk=[arr[x] for x in range(i,n,k)]
        valm= [arr[x] for x in range(end,n,k)]
        val=valk[:]+valm[:]

        #print(valk,valm)
        most=most_f(val)
        #print(most)
        endwr=end

        for j in range(i,n,k):
            #print(endwr)
            if arr[j] != most:
                arr[j]=most
                count+=1
            if arr[endwr] != most:
                arr[endwr]=most
                count+=1
            endwr+=k
        #print(arr)
    if n%2 == 1:
        val = [arr[x] for x in range(k//2,n,k)]

        most=most_f(val)
        #print(val,most)
        for i in range(k//2,n,k):
            if arr[i] != most:
                arr[i]=most
                count+=1

    #print(arr,count)
    #print(arr[:len(arr)//2:-1])
    #print(arr[len(arr)//2:])
    #print(arr)
    print(count)


t=int(input())
for i in range(0,t,1):
    n,k=[int(x) for x in input().split(" ")]
    s=input()
    total=0
    for i in range(0,k//2,1):
        count=[0]*123
        maxi=0
        for j in range(0,n,k):
            s1=j+i
            s2=j+(k-1-i)
            count[ord(s[s1])]+=1
            count[ord(s[s2])]+=1
        maxi=max(count)
        req=2*(n//k)
        total=total+(req-maxi)
    if k%2!=0:
        count=[0]*123
        for i in range(k//2,n,k):
            count[ord(s[i])]+=1
        maxi=max(count)
        total=total+(n//k-maxi)

    print(total)


from collections import defaultdict
t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    s = input()
    ans = 0
    st = []
    for i in range(n//k):
        st.append(s[i*k:i*k+k])

    for i in range(k//2):
        al = defaultdict(int)
        for g in st:
            al[g[i]] += 1
            al[g[-1-i]] += 1
        ans += 2*(n//k)-max(al.values())

    if k % 2 == 1:
        al = defaultdict(int)
        for g in st:
            al[g[k//2]] += 1
        ans += n//k - max(al.values())

    print(ans)


t = int(input())
cases = []
for i in range(t):
    length, k = map(int, input().strip().split())
    word = input()
    cases.append([word, k])

def solve(case):

    word = case[0]
    k = case[1]
    reps = len(word)//k

    ans = 0

    for i in range(k//2 if k%2==0 else k//2+1):
        print()
        count = {}
        for j in range(reps+1):
            left, right =  (j+1)*k-1-i, j*k+i
            if 0 <= left < len(word):
                #print(word[left], left, right)
                if word[left] in count:
                    count[word[left]] += 1
                else:
                    count[word[left]] = 1
            if 0 <= right < len(word) and left!=right:
                #print(word[right], left, right)
                if word[right] in count:
                    count[word[right]] += 1
                else:
                    count[word[right]] = 1
        replace = sum(count.values())-max(count.values())
        ans += replace

    print(ans)

for case in cases: solve(case)


t = int(input())
cases = []
for i in range(t):
    length, k = map(int, input().strip().split())
    word = input()
    cases.append([word, k])

def solve(case):

    word = case[0]
    k = case[1]
    reps = len(word)//k

    ans = 0

    for i in range(k//2):
        count = {}
        for j in range(reps+1):
            left, right =  j*k-1-i, j*k+i
            if 0 <= left < len(word):
                if word[left] in count:
                    count[word[left]] += 1
                else:
                    count[word[left]] = 1
            if 0 <= right < len(word) and left!=right:
                if word[right] in count:
                    count[word[right]] += 1
                else:
                    count[word[right]] = 1
        replace = sum(count.values())-max(count.values())
        ans += replace

    print(ans)

for case in cases: solve(case)


q = int(input())

alph = "abcdefghijklmnopqrstuvwxyz"

def to_arr(s):
    a = [0]*len(s)
    for i in range(len(s)):
        a[i] = alph.index(s[i])
    return a

for _ in range(q):
    n, k = map(int, input().split())
    s = to_arr(input())
    ans = 0
    for i in range(k//2):
        r = [0]*26
        ml = 1
        r[s[i]] += 1
        r[s[k-i-1]] += 1
        if r[s[k-i-1]] > ml:
            ml = r[s[k-i-1]]
        for m in range(1, n//k):
            r[s[i+m*k]] += 1
            if r[s[i+m*k]] > ml:
                ml = r[s[i+m*k]]
            r[s[k-i-1+m*k]] += 1
            if r[s[k-i-1+m*k]] > ml:
                ml = r[s[k-i-1+m*k]]
        ans += (n//k)*2 - ml
    if k%2:
        r = [0]*26
        ml = 1
        r[s[k//2]] += 1
        for m in range(1, n//k):
            r[s[k//2+m*k]] += 1
            if r[s[k//2+m*k]] > ml:
                ml = r[s[k//2+m*k]]
        ans += n//k - ml
    print(ans)


import collections

def mostRepeatedLetter(st):
	d = collections.defaultdict(int)
	for c in st:
		d[c] +=1
	return d[sorted(d, key=d.get, reverse=True)[0]]

def run(n, k, string):
	numChanges = 0

	for u in range(int(k/2)): #posicoes
		letters = ""
		for j in range(int(n/k)): #sub palindromes
			curPalindrome = string[j*k : j*k + k]
			letters = letters + curPalindrome[u]
			letters = letters + curPalindrome[-(u+1)]
		numChanges += len(letters) - mostRepeatedLetter(letters)

	if k % 2 == 1:
		u = int(k/2)
		letters = ""
		for j in range(int(n/k)): #sub palindromes
			curPalindrome = string[j*k : j*k + k]
			letters = letters + curPalindrome[u]
		numChanges += len(letters) - mostRepeatedLetter(letters)

	print(numChanges)

times = int(input())

for i in range(times):
	n, k = map(int, input().split())
	string = input()
	run(n, k, string)


for i in range(int(input())):
       n, k = map(int, input().split())
       s = input()
       ans = 0
       for j in range(k):
              d = {}
              for l in range(j, n, k):
                     if s[l] in d:
                            d[s[l]] += 1
                     else:
                            d[s[l]] = 1
              for l in range(k-j-1, n, k):
                     if s[l] in d:
                            d[s[l]] += 1
                     else:
                            d[s[l]] = 1
              ans += n//k*2-max(d.values())
       print(ans//2)


for _ in range(int(input())):
    n,k=map(int,input().split())
    s = input()
    ans = []

    if k%2==1:
        ran = k//2+1

    else:
        ran = k//2

    for i in range(ran):
        temp = []
        start = i
        end = k-i-1
        # print(start,end)
        for j in range(n//k):
            #why 3 1 2?
            # print(s[start+(j-1)*k],s[end+(j-1)*k])
            temp.append(s[start+(j-1)*k])
            temp.append(s[end+(j-1)*k])
        ans.append(temp)

    res = 0

    for i in range(len(ans)):
        res+=len(set(ans[i]))-1

    print(res)


for _ in range(int(input())):
    n,k=map(int,input().split())
    s = input()
    ans = []

    for i in range(k//2+1):
        temp = []
        start = i
        end = k-i-1
        # print(start,end)
        for j in range(n//k):
            #why 3 1 2?
            # print(s[start+(j-1)*k],s[end+(j-1)*k])
            temp.append(s[start+(j-1)*k])
            temp.append(s[end+(j-1)*k])
        ans.append(temp)

    res = 0

    for i in range(len(ans)):
        res+=len(set(ans[i]))-1

    print(res)


for _ in range(int(input())):
    n,k=map(int,input().split())
    s = input()
    ans = []

    if k%2==1:
        ran = k//2+1

    else:
        ran = k//2

    for i in range(ran):
        temp = []
        start = i
        end = k-i-1
        # print(start,end)
        for j in range(n//k):
            #why 3 1 2?
            # print(s[start+(j-1)*k],s[end+(j-1)*k])

            if i!=k//2:
                temp.append(s[start+(j-1)*k])
            temp.append(s[end+(j-1)*k])
        ans.append(temp)

    # print(ans)
    res = 0

    for i in range(len(ans)):

        some = {}
        for j in range(len(ans[i])):
            # print(ans[i][j])
            if some.get(ans[i][j])==None:
                some[ans[i][j]] = 1
            else:
                some[ans[i][j]] += 1
        # print(res)
        res+=len(ans[i])-max(some.values())
        # print(res)

    print(res)


oa = ord('a')
st = lambda x:ord(x) - oa
t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    s = list(map(st, list(input())))
    l = [s[i:i + k] for i in range(0, n, k)]
    c = n//k
    ans = n
    for i in range(k//2):
        d = [0]*30
        for x in l:
            d[x[i]] += 1
            d[x[k-i-1]] += 1
        ans -= max(d)
    if k%2:
        d = [0]*30
        for x in l:
            d[x[k//2]] += 1
        ans -= max(d)
    print(ans)


from collections import Counter

def solve(s: str, n: int, k: int) -> int:
    counters = [Counter(s[i::k] + s[k - i - 1::k])
                for i in range((k + 1) // 2)]
    chars = [max((c for c in cnt), key=lambda c: cnt[c]) for cnt in counters]

    target = ''.join(chars + chars[:k // 2][::-1]) * (n // k)

    res = 0
    for c1, c2 in zip(s, target):
        if c1 != c2:
            res += 1

    return res

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        n, k = map(int, input().split())
        s = input()
        print(solve(s, n, k))


from collections import defaultdict

def solve(s: str, n: int, k: int) -> int:
    counters = [defaultdict(int) for _ in range((k + 1) // 2)]
    for i in range(n):
        counters[min(i % k, k - i % k - 1)][s[i]] += 1

    chars = [max((c for c in cnt), key=lambda c: cnt[c]) for cnt in counters]

    target = ''.join(chars + chars[:k // 2][::-1]) * (n // k)

    res = 0
    for c1, c2 in zip(s, target):
        if c1 != c2:
            res += 1

    return res

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        n, k = map(int, input().split())
        s = input()
        print(solve(s, n, k))


from collections import Counter

for _ in range(int(input())):
    n, k = map(int,input().split())
    s = list(input())

    ans = 0

    for i in range(k):
        ans += len(s[i::k]) + len(s[n-i-1::-k]) - max(Counter(s[i::k] + s[n-i-1::-k]).values())

    print(ans // 2)


def max_counter(a):
    d = {}

    for i in a:
        d[i] = d.get(i, 0) + 1

    return max(d.values())

for _ in range(int(input())):
    n, k = map(int, input().split())
    s = list(input())

    ans = 0

    for i in range(k):
        ans += len(s[i::k]) + len(s[n - i - 1::-k]) - max_counter(s[i::k] + s[n-i-1::-k])

    print(ans // 2)


"""
Author: guiferviz
Time: 2020-03-31 15:35:03
"""

def solve():
    n, k = map(int, input().split())
    s = list(input())

    c = 0
    for i, s_i in enumerate(s[:k//2+1]):
        idxs = [*range(i, n, k), *range(k - i - 1, n, k)]
        # Get more frequent char.
        cd = {}
        max_count = 0
        max_char = None
        for j in idxs:
            s_j = s[j]
            count = cd.get(s_j, 0) + 1
            if count > max_count:
                max_count = count
                max_char = s_j
            cd[s_j] = count
        # Set char.
        for j in idxs:
            if s[j] != max_char:
                s[j] = max_char
                c += 1

    print(c)
    #print("".join(s))

def main():
    t = int(input())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


for _ in range(int(input())):
    n,k = map(int,input().split())
    s = input()
    a,p,m,o = [[]],0,n//k,ord('a')
    for i in range(n):
        a[p].append(s[i])
        if (i+1)%k==0:
            a.append([])
            p+=1
    l, r, res = 0, k-1, 0
    while(l<=r):
        cnt = [0]*36
        for i in range(m):
            cnt[ord(a[i][l])-o] += 1
            if l!=r: cnt[ord(a[i][r])-o] += 1
        t = max(cnt)
        res+=2*m-t if l!=r else m-t
        l+=1
        r-=1
    print(res)


from collections import*
I=input
for _ in[0]*int(I()):n,k=map(int,I().split());s=I();s+=s[::-1];print(n-sum(max(Counter(s[i::k]).values())for
i in range(k))//2)


ttt=int(input())
for tttt in range(ttt):
	nk=input().split(' ')
	n=int(nk[0])
	k=int(nk[1])
	s=input()

	m=round(n/k)
	a=[]
	for i in range(m):
		row=[]
		for j in range(k):
			row.append(s[(i*k)+j])
		a.append(row)
	q=0
	if(k%2==0):
		for i in range(round(k/2)):
			listt=[]
			for j in range(m):
				listt.append(a[j][i])
			for j in range(m):
				listt.append(a[j][k-i-1])
			sett=set(listt)
			count=[]
			for x in sett:
				count.append(listt.count(x))
			q+=len(listt)-max(count)
		print(q)
	else:
		for i in range(round((k-1)/2)):
			listt=[]
			for j in range(m):
				listt.append(a[j][i])
			for j in range(m):
				listt.append(a[j][k-i-1])
			sett=set(listt)
			count=[]
			for x in sett:
				count.append(listt.count(x))
			q+=len(listt)-max(count)
		listt=[]
		for j in range(m):
			listt.append(a[j][round(k/2)])
		sett=set(listt)
		count=[]
		for x in sett:
			count.append(listt.count(x))
		q+=len(listt)-max(count)
		print(q)


ttt=int(input())
for tttt in range(ttt):
	nk=input().split(' ')
	n=int(nk[0])
	k=int(nk[1])
	s=input()

	m=round(n/k)
	a=[]
	for i in range(m):
		row=[]
		for j in range(k):
			row.append(s[(i*k)+j])
		a.append(row)
	q=0
	if(k%2==0):
		for i in range(round(k/2)):
			listt=[]
			for j in range(m):
				listt.append(a[j][i])
			for j in range(m):
				listt.append(a[j][k-i-1])
			sett=set(listt)
			count=[]
			for x in sett:
				count.append(listt.count(x))
			q+=len(listt)-max(count)
		print(q)
	else:
		for i in range(round((k-1)/2)):
			listt=[]
			for j in range(m):
				listt.append(a[j][i])
			for j in range(m):
				listt.append(a[j][k-i-1])
			sett=set(listt)
			count=[]
			for x in sett:
				count.append(listt.count(x))
			q+=len(listt)-max(count)
		listt=[]
		for j in range(m):
			listt.append(a[j][int(k/2)])
		sett=set(listt)
		count=[]
		for x in sett:
			count.append(listt.count(x))
		q+=len(listt)-max(count)
		print(q)


import operator
t = int(input())
estado = "complete"
igual = "idle"
decir = []
for i in range(0, t):
    b = input()
    n = int(b.split((" "))[0])
    k = int(b.split(" ")[1])
    word = list(input())
    resultado = 0
    if k % 2 == 0:
        for i in range(0, int(k/2)):
            l = {}
            dif = []
            estado = "SI"
            for j in range(0, n, k):
                for g in word[i+j]:
                    if g not in dif:
                        dif.append(g)
                        l[g] = 0
                for g in word[n-1-i-j]:
                    if g not in dif:
                        dif.append(g)
                        l[g] = 0
                if word[i+j] in dif:
                    l[word[i+j]] += 1
                if (i+j) == n-1-i:
                    estado = "NO"
                if estado != "NO":
                    if (i+j) != n-1-i-k:
                        if word[n-1-i-j] in dif:
                            l[word[n-1-i-j]] += 1
            sortL = sorted(l.items(), key=lambda t: t[1])
            for i in range(0, len(sortL) - 1):
                resultado += int(sortL[i][1])
    else:
        for i in range(0, int((k+1)/2)):
            l = {}
            dif = []
            estado = "SI"
            for j in range(n-k, -k, -k):
                for g in word[i+j]:
                    if g not in dif:
                        dif.append(g)
                        l[g] = 0
                for g in word[n-1-i-j]:
                    if g not in dif:
                        dif.append(g)
                        l[g] = 0
                if word[i+j] in dif:
                    l[word[i+j]] += 1
                if (i+j) == n-1-i:
                    estado = "NO"
                if estado != "NO":
                    if (i+j) != n-1-i-k:
                        if word[n-1-i-j] in dif:
                            l[word[n-1-i-j]] += 1

            sortL = sorted(l.items(), key= lambda t : t[1])
            for i in range(0, len(sortL)-1):
                resultado += int(sortL[i][1])

    decir.append(resultado)
for i in range(0, t):
    print(decir[i])


import sys

sys.setrecursionlimit(10**7)

def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()

def dfs(node, color):

    if not visited[node]:
        visited[node] = True
        dp[node] = color

        if node+k < n and not visited[node+k]:
            dfs(node+k, color)
        if not visited[n-node-1]:
            dfs(n-node-1, color)

T = int(input())
while T:
    n,k = get_ints()
    string = input()
    # if k==1:
    #     mydict = dict()
    #     for i in string:
    #         mydict[i] = mydict.get(i, 0)+1
    #     maxi = 0
    #     for i in mydict:
    #         maxi = max(maxi, mydict[i])
    #     print(n-maxi)
    #     T-=1
    #     continue
    visited = [False]*n
    dp = [0]*n

    color = 1
    for i in range(n):
        if not visited[i]:
            dfs(i, color)
            color += 1

    lst = [{} for i in range(color-1)]
    for i in range(n):
        lst[dp[i]-1][string[i]] = lst[dp[i]-1].get(string[i], 0)+1
    # print(lst)
    ans = 0
    for mydict in lst:
        count = 0
        maxi = 0
        for i in mydict:
            count += mydict[i]
            maxi = max(maxi, mydict[i])
        ans += (count-maxi)
    print(ans)
    T-=1


import sys

sys.setrecursionlimit(10**9)

def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()

def dfs(node, color):

    if not visited[node]:
        visited[node] = True
        dp[node] = color

        if node+k < n and not visited[node+k]:
            dfs(node+k, color)
        if not visited[n-node-1]:
            dfs(n-node-1, color)

T = int(input())
while T:
    n,k = get_ints()
    string = input()
    # if k==1:
    #     mydict = dict()
    #     for i in string:
    #         mydict[i] = mydict.get(i, 0)+1
    #     maxi = 0
    #     for i in mydict:
    #         maxi = max(maxi, mydict[i])
    #     print(n-maxi)
    #     T-=1
    #     continue
    visited = [False]*n
    dp = [0]*n

    color = 1
    for i in range(n):
        if not visited[i]:
            dfs(i, color)
            color += 1

    lst = [{} for i in range(color-1)]
    for i in range(n):
        lst[dp[i]-1][string[i]] = lst[dp[i]-1].get(string[i], 0)+1
    # print(lst)
    ans = 0
    for mydict in lst:
        count = 0
        maxi = 0
        for i in mydict:
            count += mydict[i]
            maxi = max(maxi, mydict[i])
        ans += (count-maxi)
    print(ans)
    T-=1


ans=[]
for s in range(int(input())):
    n,k=[int(x) for x in input().split()]
    s1=input()
    final=0
    for i in range(0,k):
        arr=[0]*26
        j=i
        while j<n:
            arr[ord(s1[j])-97]+=1
            arr[ord(s1[k-1-j])-97]+=1
            j+=k

        final+=sum(arr)-max(arr)

    ans.append(final//2)
for it in ans:
    print(it)


ans=[]
for s in range(int(input())):
    n,k=[int(x) for x in input().split()]
    s1=input()
    final=0
    for i in range(0,k):
        arr=[0]*26
        j=i
        while j<n:
            arr[ord(s1[j])-97]+=1
            arr[ord(s1[k-1-j])-97]+=1
            j+=k
        print(arr)
        final+=sum(arr)-max(arr)
        print(final)
    ans.append(final//2)
for it in ans:
    print(it)


from collections import Counter

for _ in range(int(input())):
    n , k = map(int, input().split())
    s = input()

    r = 0
    observed = set()
    for i in range(k):
        ss = set(range(i, n, k)).union(set(range(n-i-1, -1, -k)))
        if ss.issubset(observed):
            continue
        c = Counter(s[i] for i in ss)
        r += len(ss) - c.most_common(1)[0][1]
        observed = observed.union(ss)
    print(r)


from sys import stdin
input=stdin.readline

from collections import Counter

for _ in range(int(input())):
    n , k = map(int, input().split())
    s = input()

    r = 0
    #sobserved = set()
    for i in range(k//2+1):
        #print(i)
        if (n-1 - i) % k < i:
            continue
        #print(*range(i, n, k))
        #print(*range(n-i-1, -1, -k))

        l = (n - i - 1) // k + 1
        #print("l:", l)
        c = Counter(s[j] for j in range(i, n, k))
        if i != k - i - 1:
            l *= 2
            for j in range(n-i-1, -1, -k):
                c[s[j]] += 1

        r += l - c.most_common(1)[0][1]

    print(r)
    #print("----")


t=int(input())
for i in range(t):
    inp1=list(map(int,input().split()))
    n=inp1[0]
    k=inp1[1]
    s=input()
    anss=0
    for p in range(int(k/2)):
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[j*k+p]+s[(j+1)*k-1-p]
        dicti=[0]*26
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=(2*(int(n/k))-maxfre)
    if(k &1):
        p=int(k/2+1)
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[(j*k)+p-1]
        dicti=[0]*26
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=((int(n/k))-maxfre)
    print(int(anss))


t=int(input())
for i in range(t):
    inp1=list(map(int,input().split()))
    n=inp1[0]
    k=inp1[1]
    s=input()
    anss=0
    for p in range(int(k/2)):
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[j*k+p]+s[(j+1)*k-1-p]
        dicti=[0]*26
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=(2*(int(n/k))-maxfre)
    if(k &1):
        p==int(k/2+1)
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[(j*k)+p-1]
        dicti=[0]*26
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=((int(n/k))-maxfre)
    print(int(anss))


t=int(input())
for i in range(t):
    inp1=list(map(int,input().split()))
    n=inp1[0]
    k=inp1[1]
    s=input()
    anss=0
    for p in range(int(k/2)):
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[j*k+p]+s[(j+1)*k-1-p]
        dicti=[0]*28
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=(2*(int(n/k))-maxfre)
    if(k &1):
        p=int(k/2+1)
        aplha=""
        for j in range(int(n/k)):
            aplha=aplha+s[(j*k)+p-1]
        dicti=[0]*28
        for j in aplha:
            dicti[ord(j)-96]+=1
        maxfre=max(dicti)
        anss+=((int(n/k))-maxfre)
    print(int(anss))


for i in range(int(input())):
    [n, k] = list(map(int, input().split()))
    p = int(n / k)
    s = list(input())
    total = 0
    for j in range(1, int((k + 1) / 2) + 1):
        dom = {}
        for l in range(p):
            dom[s[l * k + j - 1]] = dom.get(s[l * k + j - 1], 0) + 1
            dom[s[(l + 1) * k - j]] = dom.get(s[(l + 1) * k - j], 0) + 1
        largest = max(dom.values())
        if j == k + 1 - j:
            total += p - largest / 2
        else:
            total += 2 * p - largest
    print(int(total))


from sys import stdin

t = int(stdin.readline())
for _ in range(t):
	n, k = map(int, stdin.readline().split())
	s = stdin.readline()
	cnt = [[0 for i in range(26)] for j in range((k + 1) // 2)]
	for i in range(n):
		cnt[min(i % k, k - i % k - 1)][ord(s[i]) - ord('a')] += 1
	ans = 0
	for i in range(k // 2):
		ans += 2 * n // k - max(cnt[i])
	if k % 2 == 1:
		ans += n // k - max(cnt[k // 2])
	print(ans)


from sys import stdin
t = int(stdin.readline())
x = [0] * t
for _ in range(t):
	n, k = map(int, stdin.readline().split())
	s = stdin.readline()
	cnt = [[0 for i in range(26)] for j in range((k + 1) // 2)]
	for i in range(n):
		cnt[min(i % k, k - i % k - 1)][ord(s[i]) - 97] += 1
	ans = 0
	for i in range(k // 2):
		ans += 2 * n // k - max(cnt[i])
	if k % 2 == 1:
		ans += n // k - max(cnt[k // 2])
	x[_]=ans
print(*x, sep='\n')


import math

t = int(input())
for j in range(t):
    n, k = list(map(int, input().split()))
    txt = str(input())
    counts = [[0] * 28 for _ in range(math.ceil(k / 2))]
    BASE = 97
    for i, s in enumerate(txt):
        r = min(i % k, k - 1 - i % k)
        counts[r][ord(s) - BASE] += 1
    changes = 0
    for c in counts:
        changes += (sum(c) - max(c))
    print(changes)


from collections import defaultdict
from math import ceil
def solve(st,l,d):
	arr = []
	for i in range(0,l,d) :
		arr.append(st[i:(i+d)])
	# print(arr)
	nd = ceil(d / 2)
	# ano = []
	ans = 0
	for i in range(nd):
		# ano.append(defaultdict(int))
		m = defaultdict(int)
		for j in range(l//d):
			m[arr[j][i]] += 1
			if (i != (d-(i+1))):
				m[arr[j][d-(i+1)]] += 1
		ans += sum(m.values()) - max(m.values())
		# print(m)

	return ans

t = int(input())
lans = ""
for l in range(t):
	l,d = map(int,input().split())
	st = input()
	lans += str(solve(st,l,d))
	lans += "\n"
print(lans)


from collections import defaultdict
from math import ceil
from sys import stdin
def solve(st,l,d):
	arr = []
	for i in range(0,l,d) :
		arr.append(st[i:(i+d)])
	# print(arr)
	nd = ceil(d / 2)
	# ano = []
	ans = 0
	for i in range(nd):
		# ano.append(defaultdict(int))
		m = defaultdict(int)
		for j in range(l//d):
			m[arr[j][i]] += 1
			if (i != (d-(i+1))):
				m[arr[j][d-(i+1)]] += 1
		ans += sum(m.values()) - max(m.values())
		# print(m)

	return ans

t = int(stdin.readline())
lans = ""
for l in range(t):
	l,d = map(int,stdin.readline().split())
	st = input()
	lans += str(solve(st,l,d))
	lans += "\n"
print(lans)


from collections import defaultdict
from math import ceil
def solve(st,l,d):
	arr = []
	for i in range(0,l,d) :
		arr.append(st[i:(i+d)])
	# print(arr)
	nd = ceil(d / 2)
	# ano = []
	ans = 0
	for i in range(nd):
		# ano.append(defaultdict(int))
		m = defaultdict(int)
		for j in range(l//d):
			m[arr[j][i]] += 1
			if (i != (d-(i+1))):
				m[arr[j][d-(i+1)]] += 1
		ans += sum(m.values()) - max(m.values())
		# print(m)

	print(ans)

t = int(input())
for l in range(t):
	l,d = map(int,input().split())
	st = input()
	solve(st,l,d)


for _ in range(int(input())):
    n,k=map(int,input().split())
    s=input()
    ans=0
    for i in range(k//2):
        l=[0]*26
        c=0
        for j in range(i,n,k):
            c+=1
            val=ord(s[j])-ord('a')
            l[val]+=1
        for j in range(k-i-1,n,k):
            c+=1
            val=ord(s[j])-ord('a')
            l[val]+=1
        ans+=c-max(l)
    if k%2!=0:
        c=0
        l=[0]*26
        for j in range(k//2,n,k):
            c+=1
            val=ord(s[j])-ord('a')
            l[val]+=1
        ans+=c-max(l)
    print(ans)


for _ in range(int(input())):
    n,k=map(int,input().split())
    s=input()
    ans=0
    for i in range(k):
        l=[0]*26
        c=0
        for j in range(i,n,k):
            c+=1
            val=ord(s[j])-ord('a')
            l[val]+=1
        ans+=c-max(l)
    print(ans)


debug = 0
if debug:
    print("DEBUG MODE ON")
    f = None
    def new_input():
        global f
        if f==None:
            f = open('input.txt')
        return f.readline()
    input = new_input
def readrange(): return range(int(input()))
def readint(): return int(input())
def readarr(): return [int(x) for x in input().split()]
def readmat(rows): return [readarr() for _ in range(rows)]

from collections import Counter as counter

for _ in readrange():
    n, size = readarr() #k = size of word
    words = n//size #number of words
    s = input()
    mods = 0
    for offset in range((size+1)//2):
        letters = [s[x*size+offset] for x in range(words)] + [s[(x+1)*size-offset-1] for x in range(words)]
        c = counter(letters)
        inc = len(letters) - c.most_common(1)[0][1]
        mods += inc if offset < size//2 else inc//2
    print(mods)


debug = 0
if debug:
    print("DEBUG MODE ON")
    f = None
    def new_input():
        global f
        if f==None:
            f = open('input.txt')
        return f.readline().strip()
    input = new_input
def readrange(): return range(int(input()))
def readint(): return int(input())
def readarr(): return [int(x) for x in input().split()]
def readmat(rows): return [readarr() for _ in range(rows)]

from collections import Counter as counter

letters = {chr(x):0 for x in range(97, 123)}
for _ in readrange():
    n, size = readarr() #k = size of word
    words = n//size #number of words
    s = input()
    mods = 0
    for offset in range((size+1)//2):
        for l in letters:
            letters[l] = 0
        letter = 'a'
        for w in range(words):
            c1 = w*size+offset
            c2 = (w+1)*size-offset-1
            letters[s[c1]] += 1
            letters[s[c2]] += 1
            if letters[s[c1]] > letters[letter]:
                letter = s[c1]
            if letters[s[c2]] > letters[letter]:
                letter = s[c2]
        inc = words*2 - letters[letter]
        mods += inc if offset < size//2 else inc//2
    print(mods)


debug = 0
if debug:
    print("DEBUG MODE ON")
    f = None
    def new_input():
        global f
        if f==None:
            f = open('input.txt')
        return f.readline()
    input = new_input
def readrange(): return range(int(input()))
def readint(): return int(input())
def readarr(): return [int(x) for x in input().split()]
def readmat(rows): return [readarr() for _ in range(rows)]

for _ in readrange():
    n, k = readarr()
    p = n//k
    s = input()
    l = tuple(map(len, list(set([s[x*k+offset] for x in range(p)] + [s[x*k+k-offset-1] for x in range(p)] ) for offset in range((k+1)//2))))
    print(sum(l)-len(l))


units=[s[j*k:(j+1)*k] for j in range(rep)];

arr2=[units[j][k-i-1] for j in range(rep)];


t=int(input());
run=0;
while run<t:
    n, k= map(int, input().split());
    s= input();
    rep=int(n/k);
    units=[s[j*k:(j+1)*k] for j in range(rep)];
    changes=0;
    if k%2==0:
        for i in range(k//2):
            arr1=[units[j][i] for j in range(rep)];
            arr2=[units[j][k-i-1] for j in range(rep)];
            arr=arr1+arr2;
            letters=[];
            counts=[];
            for letter in arr:
                if letter not in letters:
                    letters.append(letter);
                    counts.append(arr.count(letter));
            changes=changes+len(arr)-max(counts);
        print(changes);
    else:
        for i in range(k//2+1):
            arr1=[units[j][i] for j in range(rep)];
            arr2=[units[j][k-i-1] for j in range(rep)];
            arr=arr1+arr2;
            letters=[];
            counts=[];
            for letter in arr:
                if letter not in letters:
                    letters.append(letter);
                    counts.append(arr.count(letter));
            if i==k//2:
                changes=changes+(len(arr)-max(counts))/2;
            else:
                changes=changes+len(arr)-max(counts);
        print(int(changes));
    run+=1;


#!/usr/bin/python3

from collections import Counter

def algo(n, k, s):
    x = n // k
    is_odd = True if k % 2 != 0 else False
    count = 0
    for i in range((k-1)//2):
        ss = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)
        for j in range(x):
            ss[s[j*k+i]] += 1
            ss[s[j*k+k-1-i]] += 1
        count += 2*x - max(ss.values())
    else:
        if is_odd:
            count += x - max(Counter([s[i] for i in range(k//2, n, k)]).values())
        else:
            ss = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)
            i = k//2 - 1
            for j in range(x):
                ss[s[j*k+i]] += 1
                ss[s[j*k+k-1-i]] += 1
            count += 2*x - max(ss.values())
    return count

for _ in range(int(input())):
    n, k = list(map(int, input().split()))
    s = input()
    print(algo(n, k, s))


"""
a9qnrp
Problem 1332C
04/04/2020
"""

def hamming_dist(a, b):
    n = len(a)
    d = [1 if a[i] != b[i] else 0 for i in range(n)]
    return sum(d)

def letter_frequencies(word, k):
    """
    Find frequency of characters in the substrings word[i::k] of word.
    returns k dictionaries
    """

    dict_list = []
    for i in range(k):
        sub_wrd = word[i::k]
        my_dict = {}
        for c in sub_wrd:
            if c not in my_dict:
                my_dict[c] = 0

            my_dict[c] += 1

        dict_list.append(my_dict)

    return dict_list

def dict_max(dic):
    best_key = None

    for k in dic:
        if not best_key:
            best_key = k

        if dic[k] > dic[best_key]:
            best_key = k

    return (best_key, dic[best_key])

t = int(input())

for _ in range(t):
    n, k = list(map(int, input().split()))

    word = list(input())

    dict_list = letter_frequencies(word, k)

    letters = [dict_max(dic) for dic in dict_list]

    unit = list(range(k))
    for i in range(k // 2):
        if letters[i][1] >= letters[-(i + 1)][1]:
            unit[i] = letters[i][0]
            unit[-(i + 1)] = letters[i][0]
        else:
            unit[i] = letters[-(i + 1)][0]
            unit[-(i + 1)] = letters[-(i + 1)][0]

    if k % 2:
        unit[k // 2] = letters[k // 2][0]

    best_word = ''.join(unit * (n//k))

    print(best_word)
    print(hamming_dist(best_word, word))


"""
a9qnrp
Problem 1332C
04/04/2020
"""

def hamming_dist(a, b):
    n = len(a)
    d = [1 if a[i] != b[i] else 0 for i in range(n)]
    return sum(d)

def letter_frequencies(word, k):
    """
    Find frequency of characters in the substrings word[i::k] of word.
    returns k dictionaries
    """

    dict_list = []
    for i in range(k // 2):
        sub_wrd1 = word[i::k]
        sub_wrd2 = word[k-i-1::k]

        sub_wrd = sub_wrd1 + sub_wrd2
        my_dict = {}
        for c in sub_wrd:
            if c not in my_dict:
                my_dict[c] = 0

            my_dict[c] += 1

        dict_list.append(my_dict)

    if k % 2:
        my_dict = {}
        sub_wrd = word[k//2::k]
        for c in sub_wrd:
            if c not in my_dict:
                my_dict[c] = 0

            my_dict[c] += 1

        dict_list.append(my_dict)

    return dict_list

def dict_max(dic):
    best_key = None

    for k in dic:
        if not best_key:
            best_key = k

        if dic[k] > dic[best_key]:
            best_key = k

    return (best_key, dic[best_key])

t = int(input())

for _ in range(t):
    n, k = list(map(int, input().split()))

    word = list(input())

    dict_list = letter_frequencies(word, k)

    letters = [dict_max(dic) for dic in dict_list]

    unit = list(range(k))
    for i in range(k // 2):
        unit[i] = letters[i][0]
        unit[-i-1] = letters[i][0]

    if k % 2:
        unit[k // 2] = letters[k // 2][0]

    best_word = ''.join(unit * (n//k))

    print(hamming_dist(best_word, word))


from collections import defaultdict
for _ in range(int(input())):
	n,k=map(int,input().split())
	z=n//k
	s=input()
	d=defaultdict(lambda:[0]*26)
	for i in range(0,n,k):
		s1=s[i:i+k]
		for j in range(0,k//2):
			d[j][ord(s1[j])-ord('a')]+=1
			d[j][ord(s1[-j-1])-ord('a')]+=1
		if k&1:
			j=k//2
			d[j][ord(s1[-j-1])-ord('a')]+=1
	ans=0
	for key in d.keys():
		ans+=sum(d[key])-max(d[key])
	print(ans)


for h in range(int(input())):
    n, k = map(int, input().split())
    s = input()
    matrix = [s[i:i + k] for i in range(0, n, k)]
    ans = 0
    if k % 2 == 1:
        cnt = [0] * 26
        for i in range(n // k):
            cnt[ord(matrix[i][k // 2]) - 97] += 1
        ans += n // k - max(cnt)
    else:
        for i in range(n // k):
            matrix[i] = matrix[i][:k // 2] + '#' + matrix[i][k // 2:]
        k += 1
    for j in range(k // 2):
        cnt = [0] * 26
        for i in range(len(matrix)):
            cnt[ord(matrix[i][j]) - 97] += 1
            cnt[ord(matrix[i][k - j - 1]) - 97] += 1
        ans += 2 * len(matrix) - max(cnt)
    print(ans)


z=int(input())
while z:
    z-=1
    n,k=map(int,input().strip().split(' '))
    s=input()
    d={}
    t=0
    for i in range(k//2):
        m=0
        d.clear()
        for j in range(i,n,k):
            if s[j] in d.keys():
                d[s[j]]+= 1
            else:
                d[s[j]]=1
            if s[j+(k-i)-1] in d.keys():
                d[s[j+(k-i)-1]]+=1
            else:
                d[s[j+(k-i)-1]]=1
            m=max(m,d[s[j]],d[s[j+(k-i)-1]])
        t+=(n//k)*2 -m
    m=0
    d.clear()
    if k%2!=0:
        for j in range(k//2,n,k):
            if s[j] in d.keys():
                d[s[j]]+= 1
            else:
                d[s[j]]=1
            m=max(m,d[s[j]])
        t+=(n//k)-m
    print(t)


def slv(s,n, k):
    ans = 0
    for i in range((k+1)//2):
        c = {}
        sm=0
        for j in range(n//k):
            a = s[j*k + i]
            if a not in c:
                c[a]=0
            c[a]+=1
            sm+=1
            if i != k-i-1:
                a = s[j*k + k-i-1]
                if a not in c:
                    c[a]=0
                c[a]+=1
                sm+=1
        m = max([c[i] for i in c])
        ans += sm - m
    return ans

t = int(input())
for _ in range(t):
    n,k=map(int, input().split())
    s = input()
    print(slv(s,n,k))


import sys
import threading
threading.stack_size(2**27)
sys.setrecursionlimit(10**7)

def main():
    def get_ints(): return map(int, sys.stdin.readline().strip().split())
    def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
    def input(): return sys.stdin.readline().strip()

    def dfs(node, color):

        if not visited[node]:
            visited[node] = True
            dp[node] = color

            if node+k < n and not visited[node+k]:
                dfs(node+k, color)
            if not visited[n-node-1]:
                dfs(n-node-1, color)

    T = int(input())
    while T:
        n,k = get_ints()
        string = input()
        # if k==1:
        #     mydict = dict()
        #     for i in string:
        #         mydict[i] = mydict.get(i, 0)+1
        #     maxi = 0
        #     for i in mydict:
        #         maxi = max(maxi, mydict[i])
        #     print(n-maxi)
        #     T-=1
        #     continue
        visited = [False]*n
        dp = [0]*n

        color = 1
        for i in range(n):
            if not visited[i]:
                dfs(i, color)
                color += 1

        lst = [{} for i in range(color-1)]
        for i in range(n):
            lst[dp[i]-1][string[i]] = lst[dp[i]-1].get(string[i], 0)+1
        # print(lst)
        ans = 0
        for mydict in lst:
            count = 0
            maxi = 0
            for i in mydict:
                count += mydict[i]
                maxi = max(maxi, mydict[i])
            ans += (count-maxi)
        print(ans)
        T-=1
threading.Thread(target=main).start()


import sys
import threading
threading.stack_size(2**26)
sys.setrecursionlimit(10**7)

def main():
    def get_ints(): return map(int, sys.stdin.readline().strip().split())
    def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
    def input(): return sys.stdin.readline().strip()

    def dfs(node, color):

        if not visited[node]:
            visited[node] = True
            dp[node] = color

            if node+k < n and not visited[node+k]:
                dfs(node+k, color)
            if not visited[n-node-1]:
                dfs(n-node-1, color)

    T = int(input())
    while T:
        n,k = get_ints()
        string = input()
        # if k==1:
        #     mydict = dict()
        #     for i in string:
        #         mydict[i] = mydict.get(i, 0)+1
        #     maxi = 0
        #     for i in mydict:
        #         maxi = max(maxi, mydict[i])
        #     print(n-maxi)
        #     T-=1
        #     continue
        visited = [False]*n
        dp = [0]*n

        color = 1
        for i in range(n):
            if not visited[i]:
                dfs(i, color)
                color += 1

        lst = [{} for i in range(color-1)]
        for i in range(n):
            lst[dp[i]-1][string[i]] = lst[dp[i]-1].get(string[i], 0)+1
        # print(lst)
        ans = 0
        for mydict in lst:
            count = 0
            maxi = 0
            for i in mydict:
                count += mydict[i]
                maxi = max(maxi, mydict[i])
            ans += (count-maxi)
        print(ans)
        T-=1
threading.Thread(target=main).start()


def to_list(s):
    return list(map(lambda x: int(x), s.split(' ')))

def get_replace_count(item):
    moda_count = get_moda_count(item)
    return len(item) - moda_count

def get_moda_count(item):
    sorted_item = sorted(item)
    len_ = 1
    max_len = 1
    curr_letter = sorted_item[0]
    prev_letter = sorted_item[0]
    for i in range(1,len(item)):
        curr_letter = sorted_item[i]
        if curr_letter != prev_letter:
            if len_ > max_len:
                max_len = len_
                len_ = 1
        else:
            len_ += 1
        prev_letter = curr_letter
    if len_ > max_len:
        return len_
    return max_len

def solve(s,k):
    if k == 1:
        replace_count = 0
        for i in range(int(len(s)/2)):
            if s[i] != s[-i-1]:
                replace_count += 1
        return str(replace_count)
    arr = []
    for i in range(0,len(s),k):
        arr.append(s[i:i+k])
    dict_ = {}
    for j in range(int(k/2)):
        dict_[j] = ''
    if k % 2 != 0:
        dict_[int(k/2)] = ''
    for item in arr:
        for i in range(int(k/2)):
            dict_[i] += item[i]
            dict_[i] += item[-i-1]

        if k % 2 != 0:
            dict_[int(k/2)] += item[int(k/2)]

    replace_count = 0
    for item in list(dict_.values()):
        replace_count += get_replace_count(item)

    return str(replace_count)

answers = []
t = int(input())
for i in range(t):
    n, k = to_list(input())
    s = input()
    answers.append(solve(s, k))
print('\n'.join(answers))


def to_list(s):
    return list(map(lambda x: int(x), s.split(' ')))

def get_replace_count(item):
    moda_count = get_moda_count(item)
    return len(item) - moda_count

def get_moda_count(item):
    sorted_item = sorted(item)
    len_ = 1
    max_len = 1
    curr_letter = sorted_item[0]
    prev_letter = sorted_item[0]
    for i in range(1,len(item)):
        curr_letter = sorted_item[i]
        if curr_letter != prev_letter:
            if len_ > max_len:
                max_len = len_
            len_ = 1
        else:
            len_ += 1
        prev_letter = curr_letter
    if len_ > max_len:
        return len_
    return max_len

def solve(s,k):
    if k == 1:
        return str(len(s) - get_moda_count(s))
    arr = []
    for i in range(0,len(s),k):
        arr.append(s[i:i+k])
    dict_ = {}
    for j in range(int(k/2)):
        dict_[j] = ''
    if k % 2 != 0:
        dict_[int(k/2)] = ''
    for item in arr:
        for i in range(int(k/2)):
            dict_[i] += item[i]
            dict_[i] += item[-i-1]

        if k % 2 != 0:
            dict_[int(k/2)] += item[int(k/2)]

    replace_count = 0
    for item in list(dict_.values()):
        replace_count += get_replace_count(item)

    return str(replace_count)

answers = []
t = int(input())
for i in range(t):
    n, k = to_list(input())
    s = input()
    answers.append(solve(s, k))
print('\n'.join(answers))


def to_list(s):
    return list(map(lambda x: int(x), s.split(' ')))

def get_replace_count(item):
    moda_count = get_moda_count(item)
    return len(item) - moda_count

def get_moda_count(item):
    sorted_item = sorted(item)
    len_ = 1
    max_len = 1
    curr_letter = sorted_item[0]
    prev_letter = sorted_item[0]
    for i in range(1,len(item)):
        curr_letter = sorted_item[i]
        if curr_letter != prev_letter:
            if len_ > max_len:
                max_len = len_
                len_ = 1
        else:
            len_ += 1
        prev_letter = curr_letter
    if len_ > max_len:
        return len_
    return max_len

def solve(s,k):
    arr = []
    for i in range(0,len(s),k):
        arr.append(s[i:i+k])
    dict_ = {}
    for j in range(int(k/2)):
        dict_[j] = ''
    if k % 2 != 0:
        dict_[int(k/2)] = ''
    for item in arr:
        for i in range(int(k/2)):
            dict_[i] += item[i]
            dict_[i] += item[-i-1]

        if k % 2 != 0:
            dict_[int(k/2)] += item[int(k/2)]

    replace_count = 0
    for item in list(dict_.values()):
        replace_count += get_replace_count(item)

    return str(replace_count)

answers = []
t = int(input())
for i in range(t):
    n, k = to_list(input())
    s = input()
    answers.append(solve(s, k))
print('\n'.join(answers))


a=int(input())
for _ in range(a):
    b,c=map(int,input().split())
    d=input()
    ans=0
    for i in range(c//2):
        now=i
        data={}
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        now=c-i-1
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        ans+=max(data.values())
    if c%2==1:
        now=c//2+1
        data={}
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        ans+=max(data.values())
    print(b-ans)


a=int(input())
for _ in range(a):
    b,c=map(int,input().split())
    d=input()
    ans=0
    for i in range(c//2):
        now=i
        data={}
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        now=c-i-1
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        ans+=max(data.values())
    if c%2==1:
        now=c//2
        data={}
        while now<b:
            if d[now] not in data:
                data[d[now]]=0
            data[d[now]]+=1
            now+=c
        ans+=max(data.values())
    print(b-ans)


from sys import stderr

def count_min_to_equalize(cs):
    c_counts = [0 for _ in range(ord('z') - ord('a') + 1)]

    for c in cs:
        c_counts[ord(c) - ord('a')] += 1

    # c_max = max(range(len(c_counts)), key=lambda i: c_counts[i])
    # c_max = chr(ord('a') + c_max)

    # print('->', ''.join(cs), len(cs), max(c_counts), len(cs) - max(c_counts), file=stderr)

    return len(cs) - max(c_counts)

for _ in range(int(input())):
    n, k = map(int, input().split(' '))

    s = input()

    n_min = 0

    # print(len(s), s, file=stderr)
    # print(*(s[i * k:(i + 1) * k] for i in range(n // k)), file=stderr)
    # print(*(s[i] + s[-(i + 1)] for i in range(len(s) // 2)), file=stderr)
    # print(*(s[i::k] for i in range(k)), file=stderr)

    s_new = [None for c in s]

    for i in range(k // 2):
        cs = [s[i + j * k] for j in range(0, n // k)]
        cs += [s[(j + 1) * k - (i + 1)] for j in range(0, n // k)]

        # print(''.join(cs), file=stderr)

        n_min += count_min_to_equalize(cs)

    if k % 2 == 1:
        n_min += count_min_to_equalize([s[k // 2 + i * k] for i in range(n // k)])

    # print(file=stderr)

    print(n_min)


def solve(ans):
    n,k=[int(x) for x in input().split()]
    s=input()
    occur=[[0]*26 for i in range((k+1)//2)] # IT NOTES THE OCCURENCE
    for i in range(0,n,k):
        for j in range((k+1)//2):
            occur[j][ord(s[i+j])-ord('a')]+=1
        for j in range(k//2):
            occur[j][ord(s[i+k-j-1])-ord('a')]+=1
    change=0
    for j in range(k//2):
        max_at_pos=max(occur[j])
        change+=2*(n//k)-max_at_pos
    if k%2!=0:
        change+=n//k-max(occur[-1])

    ans.append(change)
    return

n=int(input())
ans=[]
for i in range(n):
    solve(ans)
for ele in ans:
    print(ele)


from sys import stdin, gettrace

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

# def input():
#    return stdin.buffer.readline()

def main():
    def solve():
        n,k = map(int, input().split())
        ss = input()
        counts = [[0]*26 for _ in range((k+1)//2)]
        for i in range(0,n,k):
            for j in range((k+1)//2):
                counts[j][ord(ss[i+j]) - ord('a')] += 1
            for j in range(k//2):
                counts[j][ord(ss[i+k-j-1]) - ord('a')] += 1
        res = 0
        for i in range(k//2):
            res += 2* n//k - max(counts[i])
        if k%2 == 1:
            res += n//k - max(counts[-1])
        print(res)

    q = int(input())
    for _ in range(q):
        solve()

if __name__ == "__main__":
    main()


import operator

T = int(input())
n = [0]*T
k = [0]*T
ss = [0]*T

for t in range(T):
  n[t],k[t]  = [int(i) for i in input().split(' ')]
  ss[t] = input()

for t in range(T):
  ans = n[t]
  g = n[t]//k[t]
  for i in range(int((k[t]+1)*0.5)):
    uns = {}
    for j in range(g):
      if (j*k[t]+i!=(j+1)*k[t]-i-1):
        m = 2
        for ind in (j*k[t]+i,(j+1)*k[t]-i-1):
          if ss[t][ind] in uns:
            uns[ss[t][ind]] += 1
          else:
            uns[ss[t][ind]] = 1
      else:
        ind = j*k[t]+i
        m = 1
        if ss[t][ind] in uns:
          uns[ss[t][ind]] += 1
        else:
          uns[ss[t][ind]] = 1
    ans -= max(uns.items(), key=operator.itemgetter(1))[1]

  print(ans)


def Bfs(id, n, k, visited: list):
    queue1, queue2 = [], []
    visited[id] = True
    queue1.append(id)
    while queue1:
        i = queue1.pop()
        queue2.append(i)
        if i + k < n and not visited[i + k]:
            visited[i + k] = True
            queue1.append(i + k)
        if i - k >= 0 and not visited[i - k]:
            visited[i - k] = True
            queue1.append(i - k)
        if not visited[n - 1 - i]:
            visited[n - 1 - i] = True
            queue1.append(n - 1 - i)
    return queue2

def countReplacement(string: str, queue: list):
    total, count, chrcount = len(queue), 0, {}
    while queue:
        i = queue.pop()
        chrcount[string[i]] = chrcount.get(string[i], 0) + 1
        count = max(count, chrcount[string[i]])
    return total - count

t = int(input())
while t > 0:
    n, k = [int(x) for x in input().split()]
    string, count = input(), 0
    visited = [False] * len(string)
    for id in range(len(string)):
        if not visited[id]:
            queue = Bfs(id, n, k, visited)
            count += countReplacement(string, queue)
    print(count)
    t -= 1


from collections import defaultdict

def solve(s, n, k):
    div = n // k
    i = 0
    j = k - 1
    ans = 0
    while i <= j:
        map_d = defaultdict(int)
        for d in range(div):
            l = d * k + i
            r = d * k + j
            if l != r:
                map_d[s[l]] += 1
                map_d[s[r]] += 1
            else:
                map_d[s[l]] += 1
        max_so_far = -1
        for key in map_d.keys():
            if map_d[key] > max_so_far:
                max_so_far = map_d[key]
        if i == j:
            ans += div - max_so_far
        else:
            ans += 2 * div - max_so_far
        i += 1
        j -= 1
    return ans

def read():
    t = int(input())
    for i in range(t):
        n, k = list(map(int, input().strip().split()))
        s = input()
        ans = solve(s, n, k)
        print(ans)
read()


import collections
def min_k_complete(s, n, k):
    roots = [*range(n)]

    def find(i):
        if i != roots[i]: roots[i] = find(roots[i])
        return roots[i]

    def unite(i, j):
        roots[find(i)] = find(j)

    for i in range(n // 2):
        unite(i, n-1-i)

    for i in range(k):
        target = k + i
        while target < n:
            unite(i, target)
            target += k

    d = collections.defaultdict(list)
    for i, c in enumerate(s):
        d[find(i)] += c,

    res = 0
    for k, arr in d.items():
        res += len(arr) - max(collections.Counter(arr).values())
    return res

t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    s = input()
    print(min_k_complete(s, n, k))


import collections
def min_k_complete(s, n, k):

    def find(i):
        return min(i % k, (n - 1 - i) % k)

    d = collections.defaultdict(list)
    for i, c in enumerate(s):
        d[find(i)] += c,

    res = 0
    for k, arr in d.items():
        res += len(arr) - max(collections.Counter(arr).values())
    return res

t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    s = input()
    print(min_k_complete(s, n, k))


from statistics import mode
t=int(input())
#t=1
for i in range(t):
    ctr=0
    n,k=map(int,input().split())
    #n,k=21,7
    s=input()
    #s='wudixiaoxingxingheclp'
    s1=[]
    ls1=[]
    for j in range(n):
        s1.append(0)

    k1=k//2
    for l in range(k1):
        ls=[]
        for j in range(n//k):
            ls.append(s[k*j+l])
            ls.append(s[-(k*j+l+1)])
        #print(ls)
        try:
            md=mode(ls)
        except:
            md=ls[0]

        if l<=k1:
            for j in range(n//k):
                if s[k*j+l]!=md:
                    ctr+=1
                if s[-(k*j+l+1)]!=md:
                    ctr+=1
            #print(md,ctr)
    ls=[]
    if k%2!=0:
        for j in range(n//k):
            ls.append(s[k*j+(n//k)])
        try:
            md=mode(ls)
        except:
            md=ls[0]
        for j in range(n//k):
            if ls[j]!=md:
                ctr+=1

    print(ctr)
#print(s1)
'''
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
'''


from statistics import mode
t=int(input())
#t=1
for i in range(t):
    ctr=0
    n,k=map(int,input().split())
    #n,k=21,7
    s=input()
    #s='wudixiaoxingxingheclp'
    s1=[]
    ls1=[]
    for j in range(n):
        s1.append(0)
    for l in range(k):
        ls=[]
        for j in range(int(n/k)):
            ls.append(s[k*j+l])
        #print(ls)
        ls1.append(ls)
    k1=k//2
    for l in range(k1):
        try:
            md=mode(ls1[l]+ls1[k-l-1])
        except:
            md=ls1[l][0]
        for j in range(int(n/k)):
            if ls1[l][j]!=md:
                ctr+=1
            if ls1[k-l-1][j]!=md:
                ctr+=1
    #print(ctr)
    if k%2!=0:
        k1=k//2
        try:
            md=mode(ls1[k1])
        except:
            md=ls1[k1][0]
        for j in range(n//k):
            if ls1[k1][j]!=md:
                ctr+=1
    print(ctr)
#print(s1)
'''
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
'''


from statistics import mode
t=int(input())
#t=1
for i in range(t):
    ctr=0
    n,k=map(int,input().split())
    #n,k=18,1
    s=input()
    #s='cbieggbagecajecdbf'
    k1=k//2
    for l in range(k1):
        ls=[]
        for j in range(n//k):
            ls.append(s[k*j+l])
            ls.append(s[-(k*j+l+1)])
        #print(ls)
        try:
            md=mode(ls)
        except:
            md=ls[0]

        if l<=k1:
            for j in range(n//k):
                if s[k*j+l]!=md:
                    ctr+=1
                if s[-(k*j+l+1)]!=md:
                    ctr+=1
            #print(md,ctr)
    if k%2!=0:
        ls=[]
        for j in range(n//k):
            try:
                ls.append(s[k*j+(n//k)])
            except:
                pass
        if k==1:
            for a in s:
                ls.append(a)
        try:
            md=mode(ls)
        except:
            md=ls[0]
        for j in range(n//k):
            if ls[j]!=md:
                ctr+=1
    print(ctr)
#print(s1)
'''
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
18 1

cbieggbagecajecdbf

'''


from statistics import mode
t=int(input())
#t=1
import string
string.ascii_lowercase
import random

for i in range(t):
    ctr=0
    n,k=map(int,input().split())
    #n,k=370,5
    s=input()
    #s='cbieggbagecajecdbf'
    '''s=''
    for j in range(370):
        s+=random.choice(string.ascii_lowercase)
    '''
    k1=k//2
    for l in range(k1):
        ls=[]
        for j in range(n//k):
            ls.append(s[k*j+l])
            ls.append(s[-(k*j+l+1)])
        #print(ls)
        try:
            md=mode(ls)
        except:
            md=ls[0]

        if l<=k1:
            for j in range(n//k):
                if s[k*j+l]!=md:
                    ctr+=1
                if s[-(k*j+l+1)]!=md:
                    ctr+=1
            #print(md,ctr)
    if k%2!=0:
        ls=[]
        for j in range(n//k):
                ls.append(s[k*j+(k//2)])
        try:
            md=mode(ls)
        except:
            md=ls[0]
        for j in range(n//k):
            if ls[j]!=md:
                ctr+=1
    print(ctr)
#print(s1)
'''
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
18 1

cbieggbagecajecdbf

'''


from math import sqrt,ceil
def mi():return map(int,input().split())
def li():return list(mi())
def ii():return int(input())
def si():return input()

rank=[]
#dsu(disjoint set unit) -> :)
def find(x,parent):
    if(x==parent[x]):
        return x
    parent[x]=find(parent[x],parent)
    return parent[x]

def union(x,y,parent):
    x1=find(x,parent)
    y1=find(y,parent)
    if(x1==y1):
        return
    if(rank[x1]>=rank[y1]):
        parent[y]=x1
        rank[x1]+=1
    else:
        parent[x]=y1
        rank[y1]+=1

def main():
    for _ in range(ii()):

        n,k=mi()
        s=si()
        parent=[i for i in range(n)]
        global rank
        for i in range(n):
            rank.append(0)
        for i in range(k):
            rank[i]+=1
            for j in range(i+k,n,k):
                union(i,j,parent)
        for i in range(n//2):
            union(i,n-i-1,parent)
        d={}
        for i in range(ceil(k/2)):
            d[i]=[]
        for i in range(n):
            d[parent[i]].append(i)
        ans=0
        for i in d.keys():
            x=[0]*26
            for j in d[i]:
                x[ord(s[j])-ord('a')]+=1
            ans+=(sum(x)-max(x))
        print(ans)

if __name__=="__main__":
    main()