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
inputCopy
5 4 baacb 1 3 1 5 4 5 2 3
outputCopy
1 2 0 1
Note
Consider the queries of the example test.
in the first query, the substring is baa, which can be changed to bac in one operation;
in the second query, the substring is baacb, which can be changed to cbacb in two operations;
in the third query, the substring is cb, which can be left unchanged;
in the fourth query, the substring is aa, which can be changed to ba in one operation.
在当天晚上清楚有六种情况之后,本来想用前缀和来操作一手,然后隔壁大佬说要用线段树,然后经过一番思考用树状数组写了一发
在他写树状数组之前,用前缀和写了一发惊喜的wa了,然后今天看到这个题竟然有用前缀和ac的
然后打开自己wa2的代码仔细一看,原来如此
题意:
给出一个字符串,长度为n,而且都是又a,b,c三个字符构成的,然后有m个询问
每个询问给出l r
,问要想这个区间内不存在回文子串,至少要改多少个字符
结论:
一共会有六种情况
abcabcabc
acbacbacb
bacbacbac
bcabcabca
cabcabcab
cbacbacba
然后用前缀和记录一下六种修改次数中最小的就好啦
string s; string s1[7]; ll diff[7][maxn]; /// abc acb bac bca cab cba int main() { ll n = read, m = read; cin >> s; s = "#" + s; s1[1] = "#"; while (s1[1].size() <= n) s1[1] += "abc"; s1[2] = "#"; while (s1[2].size() <= n) s1[2] += "acb"; s1[3] = "#"; while (s1[3].size() <= n) s1[3] += "bac"; s1[4] = "#"; while (s1[4].size() <= n) s1[4] += "bca"; s1[5] = "#"; while (s1[5].size() <= n) s1[5] += "cab"; s1[6] = "#"; while (s1[6].size() <= n) s1[6] += "cba"; for (int i = 1; i <= 6; i++) { diff[i][0] = 0; for (int j = 1; j <= n; j++) { if (s1[i][j] == s[j]) diff[i][j] = diff[i][j - 1]; else diff[i][j] = diff[i][j - 1] + 1; } } while (m--) { int l = read, r = read; ll ans = inf; for (int i = 1; i <= 6; i++) { ans = min(ans, diff[i][r] - diff[i][l - 1]); } cout << ans << endl; } return 0; } /** **/