PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#TP0000043. Buôn bán rượu ở Gergovia (Wine trading in Gergovia)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Buôn bán rượu ở Gergovia (Wine trading in Gergovia)

Wine trading in Gergovia

Source: UVa

Version: Phuoc Hung OJ Extended

Problem Statement

A street has nn consecutive houses. House ii has wine balance aia_i: a positive value means it sells that many bottles; a negative value means it needs to buy the opposite amount. The total balance is zero. Moving one bottle across one edge between adjacent houses costs one unit of work. Find the minimum total work needed to satisfy all houses.

Input

  • The first line contains nn, the number of houses.
  • The second line contains nn integers a1,…,ana_1,\ldots,a_n in street order.

Output

Print one integer: the minimum total transport work.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le8; −106≤ai≤106-10^6\le a_i\le10^6 for all 1≤i≤n1\le i\le n; ∑i=1nai=0\sum_{i=1}^{n}a_i=0.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; −106≤ai≤106-10^6\le a_i\le10^6 for all 1≤i≤n1\le i\le n; ∑i=1nai=0\sum_{i=1}^{n}a_i=0.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le100000; −106≤ai≤106-10^6\le a_i\le10^6 for all 1≤i≤n1\le i\le n; ∑i=1nai=0\sum_{i=1}^{n}a_i=0.

Examples

Input

5
5 -4 1 -3 1

Output

9

Explanation

The running balances after successive houses are 5,1,2,−1,05,1,2,-1,0. Across the four boundaries, the necessary absolute flows are 5,1,2,15,1,2,1 bottles. The total work is 5+1+2+1=95+1+2+1=9.