Codeforces 1332 C. K-Complete Word

给定一个长度为n且由小写字母组成的单词s和一个整数k,n能被k整除。若s是回文且有k的周期,即为k-完全词。题目要求找到将s转换为任何k-完全词所需的最小替换次数。对于每个测试用例,输出这个次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

int t,n,m,ans=0,sum[26];
string s;
int vis[100010][30];
 
int solve(){
    int n,k;
    cin>>n>>k;
    string ss;
    cin>>ss;
    int sz=ss.size();
    for(int i=0;i<=k;i++) {
        for(int j=0;j<=25;j++) vis[i][j]=0;
    }
    for(int i=0;i<sz;i++) vis[(i+k)%k][ss[i]-'a']++;
    int cnt=0;
    int ret=n/k;
    for(int i=0;i<k/2;i++){
        int sum=sz;
        for(int j=0;j<=25;j++)
            sum=min(sum,2*ret-vis[i][j]-vis[k-i-1][j]);
        cnt+=sum;
    }
    int now=k/2;
    if(k&1){
        int sum=sz;
        for(int i=0;i<=25;i++)
            sum=min(sum,ret-vis[now][i]);
        cnt+=sum;
    }
    cout<<cnt<<endl;
    return 0;
}
 
 
int main() {
    cin>>t;
    while(t--) {
        solve();
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值