D. Say No to Palindromes(前缀和)

D. Say No to Palindromes

题目描述
Let’s call the string beautiful if it does not contain a substring of length at least 2, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.

Let’s define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first 3 letters of the Latin alphabet (in lowercase).

You are given a string s of length n, each character of the string is one of the first 3 letters of the Latin alphabet (in lowercase).

You have to answer m queries — calculate the cost of the substring of the string s from li-th to ri-th position, inclusive.

input
The first line contains two integers n and m (1≤n,m≤2⋅105) — the length of the string s and the number of queries.

The second line contains the string s, it consists of n characters, each character one of the first 3 Latin letters.

The following m lines contain two integers li and ri (1≤li≤ri≤n) — parameters of the i-th query.

output
For each query, print a single integer — the cost of the substring of the string s from li-th to ri-th position, inclusive.

example
5 4
baacb
1 3
1 5
4 5
2 3
output
1
2
0
1

思路
我们发现长度大于等于4的回文串都包含长度为2或3的回文串,例如abba包含bb,abcba中包含bcb,于是要使最后的字符串不含回文串,即保证它不含aa,bb,cc,aba,aca,bab,bcb,cac,cbc九种,于是我们又发现若前三个字符确定,最终字符串也确定,所以只需要枚举前三种字符串的排列后,将生成的字符串与原字符串进行比较,结果取最小即可

代码

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
const int inf=0x3f3f3f3f;
char s[N];
int n,m;
int num[10][N];
//num[x][y]表示abc第x种排列形成的字符串与原字符串在前y个字母中有多少个不同
//例如abc bba ,假设abc为第一种排列,则num[1][1]=1,num[1][2]=1,num[1][3]=2;
char str[10];
bool vis[10];
int cnt=0;
void dfs(int pos)//递归处理排列
{
    if(pos==4)
    {
        cnt++;
        for(int i=1;i<=n;i++)
        {
            if(s[i]!=str[(i-1)%3+1]) num[cnt][i]=num[cnt][i-1]+1;
            else num[cnt][i]=num[cnt][i-1];
        }
        return ;
    }
    for(int i=1;i<=3;i++)
    {
        if(vis[i]) continue;
        str[pos]='a'+i-1;
        vis[i]=true;
        dfs(pos+1);
        vis[i]=false;
    }
}
void init()
{
    dfs(1);
}
int main()
{
    cin>>n>>m>>s+1;
    init();
    while(m--)
    {
        int l,r;
        cin>>l>>r;
        int res=inf;
        for(int i=1;i<=cnt;i++)  res=min(res,num[i][r]-num[i][l-1]);
        cout<<res<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值