题目
题意:给定长度为n的字符串,字符串只包含a,b,c三种字符。m次查询,每次查询区间[l,r]中最少需要修改多少个字符(只能改成a,b,c三种字符),把该字符串变成beautiful。一个字符串是beautiful的定义:它的任何长度大于1的字符子串都是非回文。
题解:考虑一个字符串怎么样才能是beautiful的。
1、因为长度为2的子串不能是回文串,所以相邻的字符不能相同;
2、因为长度为3的子串不能是回文串,所以间隔为1的字符不能相同。
此外,如果一个字符串不存在长度为2和为3的回文串,那么显然它不存在长度大于3的回文串了,因此,我们只要满足1和2就可以保证字符串是beautiful的。
而为了保证1和2,我们发现字符串的每3个字符都一定要互不相同。因此,一个beautiful的字符串一定循环的,且循环节有6种情况:
a
b
c
,
a
c
b
,
b
a
c
,
b
c
a
,
c
a
b
,
c
b
a
abc, {acb},bac,bca,cab,cba
abc,acb,bac,bca,cab,cba。
现在,因为有多次查询,我们可以用前缀和,预处理计算每个下标,每个字符的累计出现次数。详见代码。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 200010;
int n, m;
char s[maxn];
// pre[i][pos][idx]表示前i个字符中下标位置模3为pos,字符为idx + 'a'的总数
int pre[maxn][3][3];
void init() {
memset(pre, 0, sizeof(pre));
for (int i = 1; i <= n; ++i) {
int cur_pos = (i - 1) % 3;
int cur_idx = s[i] - 'a';
pre[i][cur_pos][cur_idx] = pre[i-1][cur_pos][cur_idx] + 1;
for (int pos = 0; pos < 3; ++pos) {
for (int idx = 0; idx < 3; ++idx) {
if (!(pos == cur_pos && idx == cur_idx)) {
pre[i][pos][idx] = pre[i-1][pos][idx];
}
}
}
}
}
char s2[6][4] = {"abc", "acb", "bac", "bca", "cab", "cba"};
int cal(int l, int r) {
int res = r - l + 1;
int len = r - l + 1;
for (int k = 0; k < 6; ++k) {
int num = 0;
for (int i = 0; i < 3; ++i) {
if (i >= len) continue;
int idx = s2[k][i] - 'a';
int pos = (i + l - 1) % 3;
num += 1 + (len - i - 1) / 3 - (pre[r][pos][idx] - pre[l-1][pos][idx]);
}
// printf("%s : %d\n", s2[k], num);
res = min(res, num);
}
return res;
}
void print() {
for (int pos = 0; pos < 3; ++pos) {
for (int idx = 0; idx < 3; ++idx) {
printf("index: %d + 3 * i letter: %c\n", pos, idx + 'a');
for (int i = 1; i <= n; ++i) {
printf("%d ", pre[i][pos][idx]);
}
printf("\n");
}
}
}
void test() {
while (~scanf("%s", s + 1)) {
n = strlen(s + 1);
init();
print();
}
}
int main() {
// test();
scanf("%d%d", &n, &m);
scanf("%s", s+1);
init();
// print();
while (m--) {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", cal(l, r));
}
}
/*
abacbabacabacacc
babcbcabbcabcabcbabca
cacbcbabcbabcabcba
*/