#include using namespace std; #define rep(i,a,b) for(int i=a;i class SegTree { public: static V const def = 0; V comp(V l, V r) { return (l + r); }; vector val; SegTree() { val = vector(NV * 2, def); } V getval(int l, int r) { //[l,r] l += NV; r += NV + 1; V ret = def; while (l < r) { if (l & 1) ret = comp(ret, val[l++]); if (r & 1) ret = comp(ret, val[--r]); l /= 2; r /= 2; } return ret; } void update(int i, V v) { i += NV; val[i] = v; while (i>1) i >>= 1, val[i] = comp(val[i * 2], val[i * 2 + 1]); } }; //----------------------------------------------------------------- int N, Q; map > A; map cnt; SegTree seg; #define INF INT_MAX/2 int main() { cin >> N; rep(i, 0, N) { int a; scanf("%d", &a); A[a].push_back(i); } rep(i, 0, N) seg.update(i, 1); for (auto p : A) { int a = p.first; auto v = p.second; for (int i : v) seg.update(i, 0); for (int i : v) cnt[a] += seg.getval(0, i) * seg.getval(i, N - 1); } rep(i, 0, N) seg.update(i, 1); auto ite = A.rbegin(); while (ite != A.rend()) { int a = ite->first; auto v = ite->second; for (int i : v) seg.update(i, 0); for (int i : v) cnt[a] += seg.getval(0, i) * seg.getval(i, N - 1); ite++; } /*for (auto p : cnt) { printf("[%d : %lld]\n", p.first, p.second); }*/ ll sum = 0; for (auto p : cnt) { cnt[p.first] += sum; sum = cnt[p.first]; } vector idx; vector imos; idx.push_back(0), imos.push_back(0); for (auto p : cnt) idx.push_back(p.first), imos.push_back(p.second); idx.push_back(INF), imos.push_back(sum); int Q; cin >> Q; rep(i, 0, Q) { int L, H; cin >> L >> H; int LI = lower_bound(idx.begin(), idx.end(), L) - idx.begin(); int HI = upper_bound(idx.begin(), idx.end(), H) - idx.begin(); //printf("<%d %d>", LI, HI); printf("%lld\n", imos[HI - 1] - imos[LI - 1]); } }