Balancing Bacteria

시간 제한2초메모리 제한1024 MB

요약
수열 a[1..N]이 주어질 때, 오른쪽 끝에서 (L, L-1, ..., 1) 형태로 더하거나 빼는 분무를 최소 횟수로 사용해 모든 값을 0으로 만드는 횟수를 구한다.
난이도

어려움10점 중 8점

유형
그리디, 배열, 수학, 누적 합
정답자
아직 제출이 없습니다

문제

Farmer John has NN (1≤N≤2⋅1051\le N\le 2\cdot 10^5) patches of grass in a line, where patch ii has a level of bacteria that differs by a_ia\_i from that of healthy grass (−1015≤a_i≤1015-10^{15}\le a\_i \le 10^{15}). For example, if a_i=−3a\_i = -3, then patch ii has a level of bacteria 3 lower than normal, and would need exactly 3 additional units of bacteria added to raise it to the point where it is considered healthy.

Farmer John wants to ensure every patch of grass is corrected to have a healthy level of bacteria. Conveniently, he owns two brands of pesticide that he can spray on his field, one that adds bacteria and one that removes bacteria. When Farmer John sprays either type of pesticide, he stands in patch NN (the rightmost patch) and selects a power level LL for his sprayer (1≤L≤N1 \leq L \leq N).

The sprayer has the most impact on patches near Farmer John, with diminishing effect farther away. If Farmer John chooses the pesticide that adds bacteria, then LL units of bacteria will be added to patch NN, L−1L-1 units to patch N−1N-1, L−2L-2 units to patch N−2N-2, and so on. Patches 1…N−L1 \ldots N-L will receive no bacteria, since the sprayer isn't set to a level powerful enough to reach them. Similarly, if Farmer John chooses the pesticide that removes bacteria, then LL units of bacteria will be removed from patch NN, L−1L-1 units will be removed from patch N−1N-1, and so on. Again, patches 1…N−L1 \ldots N-L will be unaffected.

Find the minimum number of times Farmer John has to apply his sprayer such that every patch of grass has the recommended value of bacteria for healthy grass. It is guaranteed that the answer is at most 10910^9.

Note that the large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a "long long" in C/C++).

입력

The first line contains NN.

The second line contains NN integers a_1…a_Na\_1\dots a\_N, the initial bacteria levels of each patch of grass.

출력

The minimum number of applications necessary to make every patch of grass have the recommended value of bacteria for healthy grass.

예제2

  1. 예제 1

    입력
    2
    -1 3
    
    예상 출력
    6
    
  2. 예제 2

    입력
    5
    1 3 -2 -7 5
    
    예상 출력
    26