#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; int op(int x, int y) { return min(x, y); } int e() { return 1001001001; } template> pair>, int> cartesian_tree(const vector& a) { const int n = a.size(); vector> g(n, {-1, -1}); vector st; constexpr Compare cmp; for (int i = 0; i < n; i++) { int last_popped = -1; while (!st.empty() && cmp(a[i], a[st.back()])) { last_popped = st.back(); st.pop_back(); } g[i][0] = last_popped; if (!st.empty()) g[st.back()][1] = i; st.emplace_back(i); } return pair(move(g), st.empty() ? -1 : st[0]); } template> vector prefix_min_sums(const vector& a) { int n = a.size(); auto [to, root] = cartesian_tree(a); vector d(n + 1); auto dfs = [&](auto&& self, int u, int l, int r) -> void { if (u == -1) return; T v = T(a[u]) * (r - u); d[l] += v; d[u + 1] -= v; self(self, to[u][0], l, u); self(self, to[u][1], u + 1, r); }; dfs(dfs, root, 0, n); for (int i = 0; i < n; i++) d[i + 1] += d[i]; d.resize(n); return d; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q; cin >> n >> q; string s; cin >> s; VI sa = suffix_array(s); VI lcp = lcp_array(s, sa); segtree seg(lcp); VI sa_inv(n); rep(i, n) sa_inv[sa[i]] = i; VL acc(n + 1); rep(i, n) acc[i + 1] = acc[i] + n - sa[i]; VL d = prefix_min_sums(lcp); rep(_, q) { int l, r; cin >> l >> r; l--; int len = r - l; int i = sa_inv[l]; int li = seg.min_left(i, [&](int x) { return x >= len; }); int ri = seg.max_right(i, [&](int x) { return x >= len; }); ll ans = ll(ri - li + 1) * (len - 1); ans += acc[li]; ans += d[ri]; cout << ans << '\n'; } }