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;
}