Official

C - Squared Error Editorial by en_translator


If we calculate the given expression directly, the time complexity will be \(\Theta(N^2)\), which will lead to TLE.

Solution \(1\)

We use the constraint \(|A_i| \le 200\).
Although \(N\) is large, the number of distinct values is small, so we process the elements with the same value at the samme time.
First, we calculate the array
\(\mathrm{cnt}_i: \) the number of appearances of \(i\) in \(A\).
Since the index may be negative, it is recommended to add \(200\) to add to all the indices in the actual implementation.
Then, for each \(i\) and \(j (-200 \le i \lt j \le 200)\), we can find \(\mathrm{cnt}_i \times \mathrm{cnt}_j \times |i - j|^2\) and sum them up, and that is the answer.
The square of the difference of the same value is \(0\), which it does not affect the answer, so we can ignore them.
Note that the answer may not fit in a 32-bit integer type. One can use 64-bit integer type instead.
The time complexity is \(O(N + (\max |A_i|)^2)\).

Solution \(2\)

We can find the answer fast enough without the constraint \(|A_i| \le 200\).
\(\sum_{i = 2}^n \sum_{j = 1}^{i - 1} (A_i - A_j)^2\)
\( = \frac{1}{2}(\sum_{i = 1}^n \sum_{j = 1}^{n} (A_i - A_j)^2)\) (Because \((A_i - A_i)^2 = 0\))
\( = \frac{1}{2}(\sum_{i = 1}^n \sum_{j = 1}^{n} (A_i^2 + A_j^2 - 2A_iA_j))\)
\( = \frac{1}{2}(2N \sum_{i = 1}^n A_i^2 -2 \sum_{i = 1}^n (A_i \sum_{j = 1}^n A_j))\)
\( = N\sum_{i = 1}^n A_i^2 - (\sum_{i = 1}^n A_i)^2\),

and the last expression can be calculated in a total of \(O(N)\) time.
Similarly, be careful of overflows of 32-bit integer type.

posted:
last update: