Codeforces #630 div2 C
题目描述
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
input
4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
output
2
0
23
16
Note
In the first test case, one optimal solution is a aaa aa.
In the second test case, the given word itself is k-complete.
大概:给一个长度为n的字符串,要求你进行尽可能少的次数,使他变成K-完全的字符串。
K-完全的条件:1)回文; 2)以k为周期
通过定义,我们可以得到两组等式:
a[i] = a[n-i+1] (i = 1,2,…,n)
a[i] = a[i+k] (i=1,2,…,n-k)
联立它们发现,条件转化成了每个周期的子字符串也必须是回文的,所以只需考虑这n/k个子字符串即可。
#include <bits/stdc++.h>
using namespace std;
int n,k,t;
string s;
int main()
{
cin >> t;
while(t--)
{
int ans=0;
cin >> n >> k >> s;
int vis[27] = {0};
for(int i=0;i<k/2;i++)
{
for(int j=i;j<n;j+=k)
vis[s[j]-'a'+1]++;
for(int j=k-i-1;j<n;j+=k)
vis[s[j]-'a'+1]++;
sort(vis,vis+27);
ans += 2*n/k - vis[26];
memset(vis,0,sizeof(vis));
}
if(k&1)
{
for(int i=k/2;i<n;i+=k)
vis[s[i]-'a'+1]++;
sort(vis,vis+27);
ans += n/k-vis[26];
}
cout << ans << endl;
}
return 0;
}