We need to compute for each query [l, r] the sum over distinct values s of (Ks * Ks * s) = s * (Ks^2). Ks is the frequency of s in the subarray. So answer = sum_{s} s * (cnt_s)^2.
We have up to n=200k, t=200k, values up to 1e6.
We need to answer many queries offline, presumably using Mo's algorithm because the query asks for sum over frequencies squared times value. This is a typical problem: given subarray queries, compute sum of cnt[x]^2 * x. Mo's algorithm can maintain current answer when adding/removing an element.
We need to support add(pos) and remove(pos). Maintain an array freq[value] for current window. When we add a value v, we update answer: old contribution = v * freq[v]^2. After increment freq[v] by 1, new contribution = v * (freq[v])^2. So delta = v * ((freq[v])^2 - (freq[v]-1)^2) = v * (freq[v]^2 - (freq[v]^2 - 2freq[v] + 1)) = v * (2freq[v] - 1). Actually careful: when adding, the new freq = old+1; so delta = v * ( (old+1)^2 - old^2 ) = v*(2old+1). Since after increment freq[v] becomes old+1, the delta uses the old freq? If we compute after updating: new_freq = old+1, we can compute delta = v(new_freq^2 - old^2) = v*((old+1)^2 - old^2) = v*(2*old+1). But in implementation we can first compute with old freq, then update.
When removing, we decrement freq[v] by 1. So old freq = freq[v] before removal, new freq = old-1. Delta = v * ((old-1)^2 - old^2) = v * ( (old^2 - 2old + 1) - old^2) = v * (-2old + 1) = - v * (2old - 1). Alternatively, delta = -v(2*(old) - 1). Since we remove, answer decreases by v*(2*old-1).
Thus Mo's algorithm O((n+t)sqrt(n)) ~ 200k * sqrt(200k) ~ 200k447 ~ 90 million, borderline but maybe okay in C++ with optimizations. However, t can be 200k, sqrt(n) ~447, product ~89e6, plus overhead; fine.
Alternatively, we could use BIT or segment tree with offline processing? But formula involves square of frequencies, not linear. So Mo's is suitable.
We also need to handle values up to 1e6, so freq array of size 1e6+1 is okay (memory ~ 8 MB if using int). Use int for freq and long long for answer.
Implementation steps:
-
read n, t.
-
read array a (1-indexed).
-
read queries: each with l, r, index.
-
block size = sqrt(n) maybe around n/sqrt(t) but usual sqrt(n) works. We'll set block = int(sqrt(n)) + 1.
-
sort queries by Mo order: (l/block, r) with alternating order for even blocks to improve (Hilbert order maybe but not needed). Use typical.
-
initialize currL=1, currR=0, ans=0, freq array zero.
-
process each query in sorted order:
while currL > L: add(--currL)
while currR < R: add(++currR)
while currL < L: remove(currL++)
while currR > R: remove(currR--)
store answer in res[query.idx]
-
add(pos): v = a[pos]; old = freq[v]; delta = v * (2*old + 1); ans += delta; freq[v]++.
-
remove(pos): v = a[pos]; old = freq[v]; delta = v * (2*old - 1); ans -= delta; freq[v]--.
-
after processing all, output res in original order.
Check with samples.
Let's test manually:
Sample1: n=3, a=[1,2,1]
Query1: [1,2] -> frequencies: 1:1, 2:1 -> sum = 11^2 + 21^2 = 3. OK.
Query2: [1,3] -> 1:2, 2:1 -> sum = 14 + 21 = 6. OK.
Sample2: n=8, a:1,1,2,2,1,3,1,1. Query [2,7] -> subarray indices 2..7: 1,2,2,1,3,1 => freq1=3, freq2=2, freq3=1 -> sum=19 + 24 + 3*1 = 9+8+3=20. All outputs 20. Works.
Complexities: O((n+t)*sqrt(n)) time, O(maxA) space for freq.
But careful: maxA is up to 1e6, freq array size 1e6+1 is okay (~8 MB for long? Use int). For ans use long long.
Now, is there any faster method? Possibly using offline sqrt decomposition with updates? But Mo's is typical.
Alternative: Use BIT with value compression? But square of frequencies is not additive, so Mo's is appropriate.
Edge cases: t=0? But constraints t>=1.
Now ensure we use fast I/O.
Potential optimization: Use block size = n / sqrt(t) maybe but typical sqrt(n) works. Could use Hilbert order to reduce constant.
We'll implement standard Mo.
But wait: n and t up to 200k, sqrt(n)~447, total operations ~ (n+t)sqrt(n) ~ 400k447 ~ 178.8 million add/remove operations. Each operation is O(1). 178 million operations maybe borderline but still okay in C++ if optimized. Use register, use int for freq, avoid modulo. Might pass.
We can try to reduce moves by using Hilbert order sort which reduces total moves to O(n sqrt(t))? Actually Hilbert order sorts queries by a space-filling curve, reducing total movement. But not necessary.
However, consider that both n and t are 200k, which is quite large. I recall Codeforces problem "Powerful array" is exactly this: sum cnt^2 * s. And Mo's algorithm is the standard solution. In that problem constraints: n, t up to 200k, a_i up to 1e6. Many solutions use Mo with block size and pass. So we'll implement that.
We'll set block = 500 approximately.
But careful: 200k * 500 = 100M moves; each move does a few arithmetic ops. Should be fine.
Now we just need to produce code.
Implementation details:
-
Use scanf/printf for fast I/O, but note the output may require long long; we can use printf with %I64d? The problem says "do not use %lld ... It is preferred to use cout". Actually says: "Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d)." So they recommend using cout. But we can use printf with %I64d if we want, but maybe they check? Usually both are fine. We'll use printf with %I64d or cout. For simplicity, since we need speed, we can use printf with %I64d, but sometimes on GNU G++ %lld works. I'll use fast I/O with ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); and then use cout for output. But cout printing 200k lines might be slower? It's okay.
-
However, reading using cin after sync is okay for 200k numbers. But I'd still use scanf to be safe. But mixing scanf and cout may be fine. We'll use scanf for input, printf for output.
We'll be careful with indices: using 0-indexed or 1-indexed? Typically Mo's algorithm uses 0-indexed for easier block calculation? But we can use 1-indexed array.
Define:
int a[200001]; // 1-indexed.
Read:
scanf("%d %d", &n, &t);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
Define struct Query {int l, r, id;};
Compute block = (int)sqrt(n) + 1; (or use n / sqrt(t)? We'll stick with sqrt(n))
Sorting:
sort(queries.begin(), queries.end(), [block](const Query& a, const Query& b) {
if (a.l/block != b.l/block) return a.l/block < b.l/block;
// Even-odd optimization: for even block, sort r ascending; for odd, descending.
return ((a.l/block) & 1) ? (a.r > b.r) : (a.r < b.r);
});
But I'll include the optimization to reduce movements.
Now implement add and remove as inline functions.
Pseudo:
long long ans = 0;
int freq[1000001] = {0};
inline void add(int pos) {
int v = a[pos];
ans += (long long)v * ( (freq[v] << 1) + 1 ); // 2*freq+1
freq[v]++;
}
inline void remove(int pos) {
int v = a[pos];
freq[v]--;
ans -= (long long)v * ( (freq[v] << 1) + 1 ); // after decrement, freq is new, so compute 2freq+1? Wait careful.
Actually we need to subtract contribution before removal: old contribution = v * old^2, new = v * (old-1)^2, so ans should decrease by v(old^2 - (old-1)^2) = v*(2old -1). So before decrement, old = freq[v]. Then we do ans -= v(2old -1). Then freq[v]--.
So implement as:
ans -= (long long)v * ( (freq[v] << 1) - 1 ); // 2old -1
freq[v]--;
}
Yes.
Alternatively, after decrement compute, but it's simpler to use old.
Now loop:
int curL = 1, curR = 0;
for (auto &q: queries) {
int L = q.l, R = q.r;
while (curL > L) add(--curL);
while (curR < R) add(++curR);
while (curL < L) remove(curL++);
while (curR > R) remove(curR--);
res[q.id] = ans;
}
Print res in order.
Now test with sample.
But careful: In remove, we compute ans -= v * (2*old - 1). Since old = freq[v] before decrement. That's correct.
Also ensure using long long for multiplication to avoid overflow. (v up to 1e6, freq up to n up to 200k, 2freq-1 up to 400k, product up to 1e6400k = 4e11 fits in 64-bit.)
Now overall time: O((n + t) * sqrt(n)) but more precisely O((n + t) * number of moves). Each move constant.
We'll implement.
Potential pitfalls:
-
Sorting: using block size = sqrt(n) may cause many queries in same block, but r order toggles, which is good.
-
Input constraints: t up to 200k, so we need to allocate queries array of size t.
-
freq array size: since a_i up to 1e6, need at least 1000000+1, say 1000005.
-
Use global arrays for speed.
Now final code.
But I recall there is known Codeforces problem "D. Powerful array" (problem 86D) with exactly same statement. In editorial, Mo's algorithm is used.
So it's fine.
Now edge: If n=1, t=1. Works.
Now I will write final answer.
But the user expects "The sum contains only finite number of nonzero summands..." etc. So output t lines.
Now produce final solution.
I will include comments and explanation.
But the problem statement says: "Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d)." So I can use printf with %I64d. But to be safe, we can use cout with '\n' and ios::sync_with_stdio.
But in competitive programming, using printf with %I64d is typical. I'll use printf for output.
Now final code.
Potential improvement: Use faster input via getchar_unlocked but not needed.
Implementation:
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 200005;
const int MAXV = 1000005;
int n, t, block;
int a[MAXN];
int freq[MAXV];
long long res[MAXN];
struct Query {
int l, r, id;
bool operator<(const Query& other) const {
if (l / block != other.l / block) return l / block < other.l / block;
// if same block, sort by r depending on parity for optimization
return ( (l / block) & 1 ) ? (r > other.r) : (r < other.r);
}
} q[MAXN];
int main() {
scanf("%d %d", &n, &t);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
block = (int)sqrt(n) + 1;
for (int i = 0; i < t; i++) {
scanf("%d %d", &q[i].l, &q[i].r);
q[i].id = i;
}
sort(q, q + t);
long long curAns = 0;
int curL = 1, curR = 0; // current window is empty
for (int i = 0; i < t; i++) {
int L = q[i].l, R = q[i].r;
// expand
while (curL > L) {
curL--;
int v = a[curL];
curAns += (long long)v * ( (freq[v] << 1) + 1 );
freq[v]++;
}
while (curR < R) {
curR++;
int v = a[curR];
curAns += (long long)v * ( (freq[v] << 1) + 1 );
freq[v]++;
}
// shrink
while (curL < L) {
int v = a[curL];
curAns -= (long long)v * ( (freq[v] << 1) - 1 );
freq[v]--;
curL++;
}
while (curR > R) {
int v = a[curR];
curAns -= (long long)v * ( (freq[v] << 1) - 1 );
freq[v]--;
curR--;
}
res[q[i].id] = curAns;
}
for (int i = 0; i < t; i++) {
printf("%I64d\n", res[i]);
}
return 0;
}
Double-check remove: In the shrink loops, before removal, we have current freq[v] = old. Then compute curAns -= v*(2*old-1), then decrement freq[v]. This matches formula.
We must ensure that for add, we compute curAns before incrementing? In add loops, we compute delta using old freq: old = freq[v], then curAns += v*(2*old+1), then increment freq. That's correct.
Now test with sample:
Sample1:
n=3, a[1]=1,a[2]=2,a[3]=1, t=2.
queries sorted:
Assume block = sqrt(3)+1 ~ 2.
Queries: (1,2) and (1,3). They both have l/block = 0? Since block=2, l=1 => 1/2=0. So both in block 0. Then sort by r ascending (since block 0 even) so order: (1,2) then (1,3).
Processing:
Initialize curL=1,curR=0,ans=0.
First query L=1,R=2:
curL>L? curL=1, L=1 => no.
curR<R: curR=0 <2 -> add pos1: v=1, old=0, ans+=1*(0+1)=1, freq[1]=1. curR=1.
curR=1 <2 -> add pos2: v=2, old=0, ans+=21=2, freq[2]=1, ans=3. curR=2.
Now curR==R. no shrink. res[0]=3.
Second query L=1,R=3:
curL=1, L=1 => no.
curR=2 <3 -> add pos3: v=1, old freq[1]=1, ans+=1(21+1)=13=3, ans=6, freq[1]=2. curR=3.
No shrink. res[1]=6. Output order: line1 3, line2 6. OK.
Sample2:
n=8, a: [1,1,2,2,1,3,1,1], t=3 queries: (2,7), (1,6), (2,7). We'll test sorting.
Block size sqrt(8)+1 ~ 3 (since sqrt(8)=2.828, +1 =3.8 floor? Actually (int) sqrt(n) + 1: sqrt(8)=2 (int sqrt =2) +1 =3). So block=3.
Compute block index for each query:
(2,7): l=2/3=0
(1,6): l=1/3=0
(2,7): l=2/3=0
All block0. Sort by r: for even block? block 0 even, sort r ascending. So order: (1,6) r=6, then (2,7) r=7, then (2,7) r=7. But if two have same r, maybe by id? Our sorting doesn't differentiate same r, but stable sort might keep original order? But order among equal r doesn't matter, but we need correct results. We'll simulate quickly:
Processing:
Initialize curL=1,curR=0,ans=0.
First query (1,6):
Expand curL down from 1 to 1? curL=1, L=1, fine.
curR up to 6: add positions 1..6.
We'll compute contributions:
Positions: 1:1, 2:1, 3:2, 4:2, 5:1, 6:3.
After adding all, frequencies: 1:3, 2:2, 3:1. ans=19+24+31=9+8+3=20. Good.
Second query (2,7):
Now window is [1,6]. Need to move to [2,7]:
Shrink left: remove pos1 (value 1). old freq[1]=3 => ans -= 1(23-1)=15=5 -> ans=15, freq[1]=2.
curL becomes 2.
Expand right: add pos7 (value 1). old freq[1]=2 => ans+=1*(22+1)=15=5 -> ans=20, freq[1]=3.
Now curL=2, curR=7. ans=20.
Third query (2,7) again (same interval): no moves; ans=20.
Output in original order: queries order: first (2,7) -> res[0]=? Actually we need to preserve id. Our ids: we assign in input order: i=0 -> (2,7), i=1 -> (1,6), i=2 -> (2,7). After sorting, the order of processing: (1,6) id=1, (2,7) id=0, (2,7) id=2 (since both have r=7, the order of equal r among ids? In our sorting comparator, we only compare by (l/block) and then r. If r equal, they are considered equal; sorting algorithm may reorder equal elements arbitrarily. Typically std::sort uses a strict weak ordering; if two elements compare equal, their order is unspecified. For our results to be correct, we must ensure that we still assign answer to correct id, and order of processing doesn't matter as long as we correctly compute each answer. But if two queries have same l/block and same r, the comparator returns false for both a<b and b<a, thus they are considered equivalent. This can lead to unpredictable ordering, but it's okay because we process each query and store result at its id. However, it's important that the ordering is deterministic? Not needed. However, we must ensure that the comparator is strict weak: if (!(a<b) && !(b<a)) they are considered equal. That's fine.
But there is potential issue: some compilers' std::sort may require a strict weak ordering; if comparator returns false for both (a<b) and (b<a) when they are not truly equal, it may cause undefined behavior? Actually if a and b are distinct but comparator says neither is less than the other, that means they are equivalent. That's allowed. However, if comparator is not transitive, could cause issues. Ours is fine.
But many Mo implementations add tie-breaking on r or on id to ensure deterministic order. Could also add id to sort to ensure strict ordering, to avoid any issues. I'll add id as final tiebreaker:
if (l/block != other.l/block) return l/block < other.l/block;
if ((l/block) & 1) {
return r > other.r;
} else {
if (r != other.r) return r < other.r;
return id < other.id;
}
But it's optional. However, to be safe, I'll include id tiebreaker.
Thus final comparator:
bool operator<(const Query& other) const {
int block_a = l / block;
int block_b = other.l / block;
if (block_a != block_b) return block_a < block_b;
if (block_a & 1) return r > other.r; // descending
else {
if (r != other.r) return r < other.r;
return id < other.id;
}
}
But careful: block variable is global; we can use block from enclosing scope if we define comparator as lambda. In struct operator< we need block as global or static? We can define static block variable, but easier to use lambda for sorting. However, struct with operator< requires block to be accessible. Could store block index inside query? Not needed. Could use lambda.
I'll use lambda for sorting to capture block.
Implementation:
sort(q, q+t, [block](const Query& a, const Query& b) {
int block_a = a.l / block;
int block_b = b.l / block;
if (block_a != block_b) return block_a < block_b;
if (block_a & 1) return a.r > b.r;
else {
if (a.r != b.r) return a.r < b.r;
return a.id < b.id;
}
});
Yes.
Now adjust code accordingly.
Now about reading/writing: using scanf and printf; we must ensure to use %I64d for long long. But on some judges, %lld also works. I'll use %I64d.
Now final code.
Potential memory: freq array size 1e6+5 = 1000005, int.
Now final answer.
But the problem is from Codeforces 86D; there may be additional constraints: time limit 7 seconds? Actually original problem time limit 5 sec, Mo's passes.
I'll provide final solution.
I will also add comments to explain.
Now produce final answer. ```cpp
#include
#include
#include
using namespace std;
const int MAXN = 200005;
const int MAXV = 1000005;
int n, t, block;
int a[MAXN];
int freq[MAXV]; // frequency of each value in the current window
long long ans[MAXN]; // answers for each query
struct Query {
int l, r, id;
} q[MAXN];
int main() {
scanf("%d %d", &n, &t);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
block = (int)sqrt(n) + 1;
for (int i = 0; i < t; ++i) {
scanf("%d %d", &q[i].l, &q[i].r);
q[i].id = i;
}
// sort queries using Mo's order with even-odd optimization
sort(q, q + t, [block](const Query& x, const Query& y) {
int bx = x.l / block, by = y.l / block;
if (bx != by) return bx < by;
if (bx & 1) return x.r > y.r; // odd blocks: r descending
else {
if (x.r != y.r) return x.r < y.r;
return x.id < y.id; // tie breaker
}
});
long long curAns = 0;
int curL = 1, curR = 0; // current window [curL, curR] is empty
for (int i = 0; i < t; ++i) {
int L = q[i].l, R = q[i].r;
// expand to the left
while (curL > L) {
--curL;
int v = a[curL];
curAns += (long long)v * ((freq[v] << 1) + 1);
++freq[v];
}
// expand to the right
while (curR < R) {
++curR;
int v = a[curR];
curAns += (long long)v * ((freq[v] << 1) + 1);
++freq[v];
}
// shrink from the left
while (curL < L) {
int v = a[curL];
curAns -= (long long)v * ((freq[v] << 1) - 1);
--freq[v];
++curL;
}
// shrink from the right
while (curR > R) {
int v = a[curR];
curAns -= (long long)v * ((freq[v] << 1) - 1);
--freq[v];
--curR;
}
ans[q[i].id] = curAns;
}
for (int i = 0; i < t; ++i)
printf("%I64d\n", ans[i]);
return 0;
}