AtCoder Beginner Contest 194 ----- C(思维)

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:


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值