[Python] Cumulative sum ABC186D

ABC186D

Sort the inputA_1\leq\ldots\leq A_NIt is good as. At this timei<jAgainst|A_i-A_j| = A_j-A_iAnd you can simplify the calculation.

eachiabout\sum_{j=i+1}^{N}|A_i-A_j|=(\sum_{j=i+1}^{N}A_j)-(N-i)A_iAnd this is in advanceABy calculating the cumulative sum ofO(1)You can find it at. ThereforeO(N\log N)So I solved this problem.

If you're not sure, AtCoder ABC 186 D --Sum of difference (brown, 400 points)

Sample code


n = int(input())
a = list(map(int,input().split()))
a.sort()
suma= sum(a)
ans = 0
for i in range(n-1):
    # print()
    suma -= a[i]
    ans += suma - a[i]*(n-i-1) 
 
print(ans)

Recommended Posts

[Python] Cumulative sum ABC186D
[Python] Cumulative sum ABC179D
Learn cumulative sum in Python
[Python] ABC175D
[Python] DP ABC184D
[Python] UnionFind ABC177D
[Python] Interval scheduling ABC103D
[Python] Binary search ABC155D
Solve ABC159-D in Python
Implement sum in Python
[Python] Dynamic programming ABC015D
[Python] BFS (breadth-first search) ABC168D
Cumulative sum and potato method
ABC161D Lunlun Number with python3
[Python] DFS (Depth-first Search) ABC157D
Solve with Ruby and Python AtCoder ABC133 D Cumulative sum
Python
[Python] How to derive nCk (ABC156-D)
Solve with Ruby, Python and Java AtCoder ARC104 B Cumulative sum
(Python) ABC162-D Consideration log and solution
AtCoder ABC130 D Cumulative Sum Binary Search Solved by Ruby and Python
Solving with Ruby, Perl, Java, and Python AtCoder ARC 098 C Cumulative sum
Solving with Ruby and Python AtCoder Tenka1 Programmer Contest C Cumulative sum
AtCoder ABC172 C Cumulative Sum Binary Search Solved by Ruby and Python
PRML Chapter 8 Product Sum Algorithm Python Implementation
[Scientific / technical calculation by Python] Sum calculation, numerical calculation
Project Euler # 16 "Sum of Powers" in Python
Solve with Ruby and Python AtCoder ABC084 D Cumulative sum of prime numbers