#include #include #include #include #include #include using namespace std; using lint = long long; using pint = pair; #define FOR(i, begin, end) for (int i = (begin), i##_end_ = (end); i < i##_end_; i++) #define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--) #define REP(i, n) FOR(i,0,n) #define IREP(i, n) IFOR(i,0,n) #include #include int op1(int l, int r) { return min(l, r); } int e1() { return 1 << 30; } int main() { cin.tie(nullptr), ios::sync_with_stdio(false); int N, Q; string S; cin >> N >> Q >> S; auto sa = atcoder::suffix_array(S); auto lcp = atcoder::lcp_array(S, sa); lcp.push_back(0); vector rcs(N); vector nexts(N, N); vector st; st.emplace_back(N - 1, 0); IREP(i, N - 1) { while (st.back().second > lcp.at(i)) st.pop_back(); nexts.at(i) = st.back().first; rcs.at(i) = rcs.at(st.back().first) + lint(st.back().first - i) * lcp.at(i); st.emplace_back(i, lcp.at(i)); } vector sainv(N, -1); REP(i, N) sainv.at(sa.at(i)) = i; vector cs(N + 1); REP(i, N) cs.at(i + 1) = cs.at(i) + (N - sa.at(i)); atcoder::segtree lcptree(lcp); while (Q--) { int l, r; cin >> l >> r; --l; int len = r - l; int x = sainv.at(l); int b = lcptree.min_left(x, [&](int v) { return v >= len; }); lint ret = cs.at(b) + (len - 1) * (nexts.at(b) - b); if (nexts.at(b) < N) ret += rcs.at(nexts.at(b)); int h = len - 1; // if (b < N and h) { // int bnxt = lcptree.max_right(b, [&](int v) { return v >= h; }); // ret += lint(h) * (bnxt - b); // if (bnxt < N) ret += rcs.at(bnxt); // } cout << ret << '\n'; } }