Say No to Palindromes

Let's call the string beautiful if it does not contain a substring of length at least 22, 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 33 letters of the Latin alphabet (in lowercase).

You are given a string ss of length nn, each character of the string is one of the first 33 letters of the Latin alphabet (in lowercase).

You have to answer mm queries — calculate the cost of the substring of the string ss from lili-th to riri-th position, inclusive.

Input

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

The second line contains the string ss, it consists of nn characters, each character one of the first 33 Latin letters.

The following mm lines contain two integers lili and riri (1≤li≤ri≤n1≤li≤ri≤n) — parameters of the ii-th query.

Output

For each query, print a single integer — the cost of the substring of the string ss from lili-th to riri-th position, inclusive.

Example

input

5 4
baacb
1 3
1 5
4 5
2 3

output

1
2
0
1

由于字符串只有“a”,“b”,"c",要是不想构成回文,我们先想3个字符组成的字符串:

aba,aab,baa。我们发现像这样字符串(只有两个字符)都会有回文子串。因此三个字符组成的不含回文子串的一定是“abc”全排列的一种。

接着推广到所有状态:abcb、abcc都是不行的,因此需要abca。五个字符:abcac、abcac都不行,只有abcab可以,接下来以此类推。我们的无回文子串字符串只能是由abcabcabc这样构成。其他排列也是如此。

因此枚举这些排列,然后和全字符串作对比,就可以得到每种排列的差异前缀和。

之后挨个输出就行。

完整代码:

#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b; ++i)
#define per(i, a, b) for(int i = a; i >= b; --i)
using namespace std;

const int N = 2e5 + 10;

string key = "abc";

int dif[10][N];
int tot;

int main()
{
	int n,m; cin >> n >> m;
    char c[N]; cin >> c + 1;
    do{
    	rep(i,1,n){
    		dif[tot][i] = dif[tot][i-1] + (c[i] != key[(i-1) % 3]);
		}
		tot++;
	}while(next_permutation(key.begin(),key.end()));

	while(m--){
		int l,r; cin >> l >> r;
		int ans = 1e9;
		rep(i,0,tot-1){
			ans = min(ans,dif[i][r] - dif[i][l-1]);
		}
		cout << ans << endl;
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值