/* -*- coding: utf-8 -*- * * 3078.cc: No.3078 Difference Sum Query - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 100000; const int MAX_QN = 100000; /* typedef */ using ll = long long; using vi = vector; template struct BIT { int n; vector bits; BIT() {} BIT(int _n) { init(_n); } void init(int _n) { n = _n; bits.assign(n + 1, 0); } T sum(int x) { x = min(x, n); T s = 0; while (x > 0) { s += bits[x]; x -= (x & -x); } return s; } void add(int x, T v) { if (x <= 0) return; while (x <= n) { bits[x] += v; x += (x & -x); } } }; /* global variables */ ll as[MAX_N], bs[MAX_N], xs[MAX_QN], res[MAX_QN]; int ls[MAX_QN], rs[MAX_QN], xis[MAX_QN]; vi lvs[MAX_QN], rvs[MAX_QN]; BIT bit0; BIT bit1; /* subroutines */ /* main */ int main() { int n, qn; scanf("%d%d", &n, &qn); for (int i = 0; i < n; i++) scanf("%lld", as + i); for (int i = 0; i < qn; i++) scanf("%d%d%lld", ls + i, rs + i, xs + i), ls[i]--, rs[i]--; copy(as, as + n, bs); sort(bs, bs + n); for (int i = 0; i < qn; i++) { xis[i] = lower_bound(bs, bs + n, xs[i]) - bs; lvs[ls[i]].push_back(i); rvs[rs[i]].push_back(i); } bit0.init(n); bit1.init(n); for (int i = 0; i < n; i++) { for (auto j: lvs[i]) { int lc = bit0.sum(xis[j]), rc = bit0.sum(n) - lc; ll lsum = bit1.sum(xis[j]), rsum = bit1.sum(n) - lsum; res[j] = (xs[j] * lc - lsum) + (rsum - xs[j] * rc); } int ai = lower_bound(bs, bs + n, as[i]) - bs; bit0.add(ai + 1, 1); bit1.add(ai + 1, as[i]); for (auto j: rvs[i]) { int lc = bit0.sum(xis[j]), rc = bit0.sum(n) - lc; ll lsum = bit1.sum(xis[j]), rsum = bit1.sum(n) - lsum; res[j] = (xs[j] * lc - lsum) + (rsum - xs[j] * rc) - res[j]; } } for (int i = 0; i < qn; i++) printf("%lld\n", res[i]); return 0; }