#include #include #include #include #include #include #include #include #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) #define whole(f,x,...) ([&](decltype((x)) y) { return (f)(begin(y), end(y), ## __VA_ARGS__); })(x) typedef long long ll; using namespace std; template struct segment_tree { // on monoid int n; vector a; function append; // associative T unit; template segment_tree(int a_n, T a_unit, F a_append) { n = pow(2,ceil(log2(a_n))); a.resize(2*n-1, a_unit); unit = a_unit; append = a_append; } void point_update(int i, T z) { a[i+n-1] = z; for (i = (i+n)/2; i > 0; i /= 2) { a[i-1] = append(a[2*i-1], a[2*i]); } } T range_concat(int l, int r) { return range_concat(0, 0, n, l, r); } T range_concat(int i, int il, int ir, int l, int r) { if (l <= il and ir <= r) { return a[i]; } else if (ir <= l or r <= il) { return unit; } else { return append( range_concat(2*i+1, il, (il+ir)/2, l, r), range_concat(2*i+2, (il+ir)/2, ir, l, r)); } } }; map count_kadomatsu(vector const & as, int first, int last) { int n = as.size(); int direction = first < last ? 1 : -1; map acc; acc[first] = 0; map > que; repeat (i,n) que[direction * as[i]].push_back(i); segment_tree cnt(n, 0, plus()); for (auto & it : que) { int a; vector is; tie(a, is) = it; a *= direction; acc[a] = acc[first]; first = a; for (int i : is) { int l = cnt.range_concat(0, i); int r = cnt.range_concat(i+1, n); acc[a] += l *(ll) r; } for (int i : is) { cnt.point_update(i, 1); } } return acc; } map count_same(vector const & as) { int n = as.size(); map dp; map total; repeat (i,n) total[as[i]] += 1; map used; ll cur = 0; for (int a : as) { dp[a] += cur - used[a] *(ll) (total[a] - used[a]); cur -= used[a]; used[a] += 1; cur += total[a] - used[a]; } map acc; int first = -1; acc[first] = 0; for (auto it : dp) { acc[it.first] = acc[first] + it.second; first = it.first; } acc[1e9+7] = acc[first]; return acc; } int main() { // input int n; scanf("%d", &n); vector a(n); repeat (i,n) scanf("%d", &a[i]); // compute map acch = count_kadomatsu(a, -1, 1e9+7); // a1 < a2, a2 > a3 map accl = count_kadomatsu(a, 1e9+7, -1); // a1 > a2, a2 < a3 map accs = count_same(a); // output int q; scanf("%d", &q); while (q --) { int l, h; scanf("%d%d", &l, &h); ll ahr = (-- acch.upper_bound(h ))->second; ll ahl = (-- acch.upper_bound(l-1))->second; ll alr = ( accl.lower_bound(h+1))->second; ll all = ( accl.lower_bound(l ))->second; ll asr = (-- accs.upper_bound(h ))->second; ll asl = (-- accs.upper_bound(l-1))->second; printf("%lld\n", (ahr - ahl) + (all - alr) - (asr - asl)); } return 0; }