#include using namespace std; typedef long long int64; struct BinaryIndexedTree { vector< int64 > data; BinaryIndexedTree(int sz) { data.assign(++sz, 0); } int64 sum(int k) { int64 ret = 0; for(++k; k > 0; k -= k & -k) ret += data[k]; return(ret); } void add(int k, int64 x) { for(++k; k < data.size(); k += k & -k) data[k] += x; } }; int N, A[200005], Q; int L[200005], R[200005]; int ans[200005]; int LL[200005], RR[200005]; int main() { scanf("%d", &N); for(int i = 0; i < N; i++) scanf("%d", &A[i]); scanf("%d", &Q); for(int i = 0; i < Q; i++) scanf("%d %d", &L[i], &R[i]); vector< int > nums; nums.push_back(-1); nums.push_back(1 << 30); for(int i = 0; i < N; i++) nums.push_back(A[i]); sort(begin(nums), end(nums)); for(int i = 0; i < N; i++) { A[i] = lower_bound(begin(nums), end(nums), A[i]) - begin(nums); } BinaryIndexedTree rest(nums.size()), left(nums.size()), right(nums.size()), result(nums.size()); for(int i = 0; i < N; i++) ++RR[A[i]], right.add(A[i], 1); for(int i = 0; i < N; i++) { --RR[A[i]]; rest.add(A[i], -LL[A[i]]); right.add(A[i], -1); result.add(A[i], 1LL * (right.sum(nums.size() - 1) - right.sum(A[i])) * (left.sum(nums.size() - 1) - left.sum(A[i])) - (rest.sum(nums.size() - 1) - rest.sum(A[i]))); result.add(A[i], 1LL * right.sum(A[i] - 1) * left.sum(A[i] - 1) - rest.sum(A[i] - 1)); ++LL[A[i]]; left.add(A[i], 1); rest.add(A[i], RR[A[i]]); } for(int i = 0; i < Q; i++) { L[i] = lower_bound(begin(nums), end(nums), L[i]) - begin(nums); R[i] = upper_bound(begin(nums), end(nums), R[i]) - begin(nums); printf("%lld\n", result.sum(R[i] - 1) - result.sum(L[i] - 1)); } }