#include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< pii; typedef vector vi; typedef vector vll; struct BIT{ int n; vector t; BIT(){} BIT(int _n):n(_n+1), t(_n+1){} void add(int k, long long val){ k++; while(k < n){ t[k] += val; k += (k&-k); } } long long sum(int k){ ll r = 0; while(k > 0){ r += t[k]; k -= (k&-k); } return r; } long long sum(int l, int r){ return sum(r) - sum(l); } }; template vector compress(vector &v){ vector a = v; sort(all(a)); a.erase(unique(all(a)), a.end()); each(b, v)b = (int)(lower_bound(all(a), b) - a.begin()); return a; } int N, Q; vi a; int main(){ cin >> N; a.resize(N); rep(i, N)scanf("%d", &a[i]); auto b = compress(a); const int M = sz(b); vll cnl(M), cnr(M); BIT bitl(M), bitr(M), ans(M); for(int i = 1; i <= N - 1; ++i){ cnr[a[i]]++; bitr.add(a[i], 1); } ll bad = 0; for(int i = 1; i <= N - 2; ++i){ bad -= cnl[a[i - 1]] * cnr[a[i - 1]]; if(a[i - 1] != a[i])bad -= cnl[a[i]] * cnr[a[i]]; cnl[a[i - 1]]++; cnr[a[i]]--; bitl.add(a[i - 1], 1); bitr.add(a[i], -1); bad += cnl[a[i - 1]] * cnr[a[i - 1]]; if(a[i - 1] != a[i])bad += cnl[a[i]] * cnr[a[i]]; ll sum = bitl.sum(0, a[i])*bitr.sum(0, a[i]) + bitl.sum(a[i] + 1, M)*bitr.sum(a[i] + 1, M); sum = sum - bad + cnl[a[i]] * cnr[a[i]]; ans.add(a[i], sum); } auto f = [&](int x){ return (int)(lower_bound(all(b), x) - b.begin()); }; cin >> Q; while(Q--){ int L, R; scanf("%d%d", &L, &R); R++; L = f(L); R = f(R); ll res = ans.sum(L, R); printf("%lld\n", res); } }