C. K-Complete Word
time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
Word s of length n is called k-complete if
s is a palindrome, i.e. si=sn+1−i for all 1≤i≤n;
s has a period of k, i.e. si=sk+i for all 1≤i≤n−k.
For example, “abaaba” is a 3-complete word, while “abccba” is not.
Bob is given a word s of length n consisting of only lowercase Latin letters and an integer k, such that n is divisible by k. He wants to convert s to any k-complete word.
To do this Bob can choose some i (1≤i≤n) and replace the letter at position i with some other lowercase Latin letter.
So now Bob wants to know the minimum number of letters he has to replace to convert s to any k-complete word.
Note that Bob can do zero changes if the word s is already k-complete.
You are required to answer t test cases independently.
Input
The first line contains a single integer t (1≤t≤105) — the number of test cases.
The first line of each test case contains two integers n and k (1≤k<n≤2⋅105, n is divisible by k).
The second line of each test case contains a word s of length n.
It is guaranteed that word s only contains lowercase Latin letters. And it is guaranteed that the sum of n over all test cases will not exceed 2⋅105.
Output
For each test case, output one integer, representing the minimum number of characters he has to replace to convert s to any k-complete word.
Example
inputCopy
4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
outputCopy
2
0
23
16
Note
In the first test case, one optimal solution is aaaaaa.
In the second test case, the given word itself is k-complete.
回文串s的周期为T,那么每一个周期一定是回文串。
若干个相同的回文串叠加起来,结果仍然是回文串
s字符串由k个相等的回文组成的回文串
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
#define inf 0x3f3f3f
typedef long long ll;
int t;
char s[200001];
int mp[200001][30];
int main()
{
cin>>t;
int n,k;
while(t--)
{
cin>>n>>k;
cin>>s+1;
for(int i=1;i<=n;i++)
for(int j=0;j<26;j++)
mp[i][j]=0;
int ans=0;
for(int i=1;i<=(k+1)/2;i++)
{
int maxn=0;//s[j+i-1]与s[j+k-i]应相等,求出有最大相等字母个数;
for(int j=1;j<=n;j+=k)//j+=k;第j组字符串,共n/k组;
{
mp[i][s[j+i-1]-'a']++;
if(k!=2*i-1)//k为奇数时,中间值无相对应的回文
{
mp[i][s[j+k-i]-'a']++;
}
maxn=max( mp[i][s[j+i-1]-'a'],max( mp[i][s[j+k-i]-'a'],maxn));
}
if(k==2*i-1)
{ ans+=(n/k)-maxn;}
else
ans+=2*(n/k)-maxn;//n/k组,每组两个;再减去最大相等的字母个数
}
cout<<ans<<endl;
}
return 0;
}