题目链接:https://codeforces.ml/problemset/problem/1332/C
转自:https://blog.csdn.net/mrcrack/article/details/105245298
题意:给一个字符串,要求变成周期是k并且是个回文串。求改变字符的最小个数。
思路:先把字符串划分成长度为k的子串,根据题意,每个子串一定是相同的回文串。问题变成了如何把这些子串变成相同的回文串。求最小个数,那么应该让对应位置出现个数最多的字符尽可能的不改变,因此统计每个子串中对应位置出现的字符数,每次都取最大值求和sum,然后用n-sum就是需要改变的字符数。
#include <bits/stdc++.h>
using namespace std;
int main()
{
// ios::sync_with_stdio(false);
string s;
int T,cnt[30];
cin>>T;
while(T--)
{
int n,k;
cin>>n>>k;
cin>>s;
int ans=0;
for(int i=0; i<(k+1)/2; i++)
{
memset(cnt,0,sizeof(cnt));
int maxx=0;
for(int j=0; j<n; j+=k)
{
int l=i+j,r=j+k-1-i;
if(l!=r)
{
cnt[s[l]-'a']++;
cnt[s[r]-'a']++;
}
else
{
cnt[s[l]-'a']++;
}
}
for(int j=0; j<26; j++)
{
maxx=max(maxx,cnt[j]);
}
ans=ans+maxx;
}
cout<<n-ans<<endl;
}
return 0;
}