#include using namespace std; const int SQRT = 535; const int INF = 1000000000; template struct binary_indexed_tree{ int N; vector BIT; binary_indexed_tree(int n){ N = 1; while (N < n){ N *= 2; } BIT = vector(N + 1, 0); } void add(int i, T x){ i++; while (i <= N){ BIT[i] += x; i += i & -i; } } T sum(int i){ T ans = 0; while (i > 0){ ans += BIT[i]; i -= i & -i; } return ans; } T sum(int L, int R){ return sum(R) - sum(L); } T all(){ return BIT[N]; } }; template struct lazy_segment_tree{ int N; vector ST; vector lazy; lazy_segment_tree(vector A){ int n = A.size(); N = 1; while (N < n){ N *= 2; } ST = vector(N * 2 - 1, INF); lazy = vector(N * 2 - 1, 0); for (int i = 0; i < n; i++){ ST[N - 1 + i] = A[i]; } for (int i = N - 2; i >= 0; i--){ ST[i] = min(ST[i * 2 + 1], ST[i * 2 + 2]); } } void eval(int i){ if (i < N - 1){ lazy[i * 2 + 1] += lazy[i]; lazy[i * 2 + 2] += lazy[i]; } ST[i] += lazy[i]; lazy[i] = 0; } void range_add(int L, int R, T x, int i, int l, int r){ eval(i); if (R <= l || r <= L){ return; } else if (L <= l && r <= R){ lazy[i] += x; eval(i); } else { int m = (l + r) / 2; range_add(L, R, x, i * 2 + 1, l, m); range_add(L, R, x, i * 2 + 2, m, r); ST[i] = min(ST[i * 2 + 1], ST[i * 2 + 2]); } } void range_add(int L, int R, T x){ range_add(L, R, x, 0, 0, N); } T all(){ eval(0); return ST[0]; } }; int main(){ int N, Q; cin >> N >> Q; vector a(N); for (int i = 0; i < N; i++){ cin >> a[i]; a[i]--; } vector l(Q), r(Q); for (int i = 0; i < Q; i++){ cin >> l[i] >> r[i]; l[i]--; } vector> query(Q); for (int i = 0; i < Q; i++){ query[i] = make_tuple(l[i] / SQRT, r[i], l[i], i); } sort(query.begin(), query.end()); binary_indexed_tree BIT1(N); binary_indexed_tree BIT2(N); lazy_segment_tree ST(vector(N, 0)); vector ans(Q); int L = 0, R = N; int invs = 0; for (int i = 0; i < Q; i++){ int l = get<2>(query[i]); int r = get<1>(query[i]); int id = get<3>(query[i]); while (l < L){ L--; ST.range_add(0, a[L], -1); invs -= BIT1.sum(a[L] + 1, N); invs -= BIT2.sum(a[L]); BIT1.add(a[L], -1); } while (R < r){ ST.range_add(a[R] + 1, N, -1); invs -= BIT1.sum(a[R] + 1, N); invs -= BIT2.sum(a[R]); BIT2.add(a[R], -1); R++; } while (L < l){ ST.range_add(0, a[L], 1); invs += BIT1.sum(a[L] + 1, N); invs += BIT2.sum(a[L]); BIT1.add(a[L], 1); L++; } while (r < R){ R--; ST.range_add(a[R] + 1, N, 1); invs += BIT1.sum(a[R] + 1, N); invs += BIT2.sum(a[R]); BIT2.add(a[R], 1); } ans[id] = ST.all() * (r - l) + invs; } for (int i = 0; i < Q; i++){ cout << ans[i] << endl; } }