题目
思路:
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
#define lson p << 1
#define rson p << 1 | 1
const int maxn = 1e6 + 5, inf = 1e9, maxm = 4e4 + 5;
const int N = 1e6;
// const int mod = 1e9 + 7;
// const int mod = 998244353;
const __int128 mod = 212370440130137957LL;
// int a[505][5005];
// bool vis[505][505];
// char s[505][505];
int a[maxn], b[maxn];
int vis[maxn];
string s;
int n, m;
struct Node{
int val, id;
bool operator<(const Node &u)const{
return val < u.val;
}
};
// Node c[maxn];
int ans[maxn];
int pre[maxn], suf[maxn];
int pw[maxn];
int base = 337;
//long long ? maxn ?
// string s[maxn];
int t[maxn][26];//t[i][j]表示长度为i,字符全为char('a' + j)的字符串的哈希值
int Hash(int l, int r){
if(l > r){
return 0;
}
return (pre[r] - (__int128)pre[l - 1] * pw[r - l + 1] % mod + mod) % mod;
}
int Hash2(int l, int r){
if(l > r){
return 0;
}
return (suf[l] - (__int128)suf[r + 1] * pw[r - l + 1] % mod + mod) % mod;
}
bool same(int l, int r){//判断字符串所有字符都相同
for(int j = 0; j < 26; j++){
if(Hash(l, r) == t[r - l + 1][j] && Hash2(l, r) == t[r - l + 1][j]){
return 1;
}
}
return 0;
}
bool ispal(int l, int r){//判断回文
return Hash(l, r) == Hash2(l, r);
}
bool isalt(int l, int r){//字符串字符交替或字符全相同 转化为 前缀后缀分别去掉2个字符后相等
return Hash(l, r - 2) == Hash(l + 2, r) && Hash2(l, r - 2) == Hash2(l + 2, r);
}
void solve(){
int res = 0;
int q, k;
int sum = 0;
int mx = 0;
cin >> n >> q;
cin >> s;
s = " " + s;
for(int i = 1; i <= n; i++){
pre[i] = ((__int128)pre[i - 1] * base % mod + s[i] - 'a') % mod;
}
suf[n + 1] = 0;
for(int i = n; i >= 1; i--){
suf[i] = ((__int128)suf[i + 1] * base % mod + s[i] - 'a') % mod;
}
while(q--){
int l, r;
cin >> l >> r;
if(same(l, r)){
cout << 0 << '\n';
continue;
}
int len = r - l + 1;
int sum = (len - 2) * (len + 1) / 2;//2 + 3 +...+ len - 1
if(isalt(l, r) && len - 1 >= 3){//考虑字符交替的情况
int cnt = (len - 1 - 3) / 2 + 1;
sum -= cnt * (3 + 3 + 2 * (cnt - 1)) / 2;
}
if(!ispal(l, r)){//考虑k = len的情况
sum += len;
}
cout << sum << '\n';
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
pw[0] = 1;
for(int i = 1; i <= N; i++){
pw[i] = (__int128)pw[i - 1] * base % mod;
}
for(int j = 0; j < 26; j++){
t[1][j] = j;
}
for(int i = 2; i <= N; i++){
for(int j = 0; j < 26; j++){
t[i][j] = ((__int128)t[i - 1][j] * base % mod + j) % mod;
}
}
int T = 1;
cin >> T;
while (T--)
{
solve();
}
return 0;
}