C - Squared Error
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 300300 points
Problem Statement
Given is a number sequence AA of length NN.
Find the sum of squared differences of every pair of elements: N∑i=2i−1∑j=1(Ai−Aj)2∑i=2N∑j=1i−1(Ai−Aj)2.
Constraints
- 2≤N≤3×1052≤N≤3×105
- |Ai|≤200|Ai|≤200
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
NN
A1A1 A2A2 A3A3 ⋯⋯ ANAN
Output
Print the answer.
Sample Input 1 Copy
Copy
3
2 8 4
Sample Output 1 Copy
Copy
56
We have ∑Ni=2∑i−1j=1(Ai−Aj)2=(8−2)2+(4−2)2+(4−8)2=56∑i=2N∑j=1i−1(Ai−Aj)2=(8−2)2+(4−2)2+(4−8)2=56.
Sample Input 2 Copy
Copy
5
-5 8 9 -4 -3
Sample Output 2 Copy
Copy
950
不会。。。。。官方解答:
SOLUTION1:
We use the constraint |Ai|≤200
Although NN 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
cnti:cnti: the number of appearances of ii in AA.
Since the index may be negative, it is recommended to add 200200 to add to all the indices in the actual implementation.
Then, for each ii and j(−200≤i<j≤200), we can find cnti×cntj×|i−j|2 and sum them up, and that is the answer.
The square of the difference of the same value is 00, 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|Ai|)2).
我们使用约束|Ai|≤200 尽管 NN 很大,但不同值的数量很少,因此我们同时处理具有相同值的元素。 首先,我们计算数组 cnti:cnti:ii 在 AA 中的出现次数。 由于索引可能为负,建议在实际实现中添加200200添加到所有索引中。 然后,对于每个 i 和 j(−200≤i<j≤200),我们可以找到cnti×cntj×|i−j|2 并将它们相加,这就是答案。 相同值的差的平方是00,不影响答案,所以我们可以忽略它们。 请注意,答案可能不适合 32 位整数类型。 可以改用 64 位整数类型。 时间复杂度为 O(N+(max|Ai|)2)。
code1:
code2: