#include #include #define rep(i, n) for(int i = 0; i < (n); ++i) using namespace std; typedef long long ll; int n; int a[200000]; int q; int l[200000]; int h[200000]; ll bf[200001]; ll bb[200001]; ll bs[200001]; ll bq[200001]; void badd(ll* b, int i, ll x){ while(i <= 200000){ b[i] += x; i += i & -i; } } ll bsum(ll* b, int i){ ll s = 0; while(i > 0){ s += b[i]; i -= i & -i; } return s; } void compress(){ vector v(a, a + n); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); rep(i, n){ a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin(); } rep(i, q){ l[i] = lower_bound(v.begin(), v.end(), l[i]) - v.begin(); h[i] = upper_bound(v.begin(), v.end(), h[i]) - v.begin(); } } void add_count(){ rep(i, n){ badd(bb, a[i] + 1, 1); } rep(i, n){ badd(bf, a[i] + 1, 1); badd(bb, a[i] + 1, -1); ll c = (bsum(bf, a[i] + 1) - bsum(bf, a[i])) * (bsum(bb, a[i] + 1) - bsum(bb, a[i])) - (bsum(bs, a[i] + 1) - bsum(bs, a[i])); badd(bs, a[i] + 1, c); ll p = bsum(bf, a[i]) * bsum(bb, a[i]); ll q = (bsum(bf, n) - bsum(bf, a[i] + 1)) * (bsum(bb, n) - bsum(bb, a[i] + 1)); ll r = (bsum(bs, n) - bsum(bs, a[i] + 1)) + bsum(bs, a[i]); badd(bq, a[i] + 1, p + q - r); } } void remove_count(){ } int main(){ cin >> n; rep(i, n){ cin >> a[i]; } cin >> q; rep(i, q){ cin >> l[i] >> h[i]; } compress(); add_count(); remove_count(); rep(i, q){ cout << bsum(bq, h[i]) - bsum(bq, l[i]) << endl; } return 0; }