Codeforces Round #630 (Div. 2) C.K-Complete Word
题目链接
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≤1e5) — the number of test cases.
The first line of each test case contains two integers n and k (1≤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
1 2 3 4 5 6 7 8 9 | 4 6 2 abaaba 6 3 abaaba 36 9 hippopotomonstrosesquippedaliophobia 21 7 wudixiaoxingxingheclp |
output
1 2 3 4 | 2 0 23 16 |
不难发现,要满足题目的条件,拆成
n/k 段每一段都应该是回文串~
所以可以记录每个位置每个字母的数量,用一个二维数组
a[i][j] 即可~
下面考虑最优解:
对每个位置
i 和其对称位置
k?i?1,遍历记录出现次数最多的字母下标
t 使得
max=a[i][t]+a[k?i?1][t] ,此时该位置需要变换的最小次数即为
2?n/k?max,遍历一遍累加答案即可(注意
n 为奇数时要特判一下中心位置),AC代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include<bits/stdc++.h> using namespace std; int main(){ int t,n,k; cin>>t; while(t--){ string s; cin>>n>>k>>s; int a[k][30]={0}; for(int i=0;i<n;i++) a[i%k][s[i]-'a']++; int mx,ans=0; for(int i=0;i<k/2;i++){ mx=0; for(int j=0;j<26;j++){ mx=max(mx,a[i][j]+a[k-i-1][j]); } ans+=2*n/k-mx; } if(k%2==1){ int mx=0; for(int i=0;i<26;i++){ mx=max(mx,a[k/2][i]); } ans+=n/k-mx; } cout<<ans<<endl; } } |