Problem:


Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8



Sample input:
4
1 -3 1 0


Sample output:
4

Submission status: Accepted

Solution code:
n = int(input())
a = [int(x) for x in input().split()]

def odd_positive(List):
    sum_a = 0
    cost = 0
    i = 0
    for a in List:
        i += 1
        sum_a += a
        if i & 1 and sum_a <= 0:
            cost += - sum_a + 1
            sum_a = 1
        elif (not i & 1) and sum_a >= 0:
            cost += sum_a + 1
            sum_a = -1
    return cost


def odd_negative(List):
    sum_a = 0
    cost = 0
    i = 0
    for a in List:
        i += 1
        sum_a += a
        if i & 1 and sum_a >= 0:
            cost += sum_a + 1
            sum_a = -1
        elif (not i & 1) and sum_a <= 0:
            cost += - sum_a + 1
            sum_a = 1
    return cost
    
ans = min(odd_positive(a), odd_negative(a)) 
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

def solve(a, n, bool):  # bool = True: 偶数項を足した時に正
  change = 0
  sum = 0
  for i in range(n):
    sum+=a[i]
    if sum <= 0 and bool:  # 和が正を仮定しているのに0以下なら
      change += abs(1-sum)
      sum=1
    if sum >=0 and not bool:
      change += abs(-1-sum)
      sum=-1 
    bool = not bool
  return change

print(min(solve(a,n,True),solve(a,n,False)))

Submission status: Accepted

Solution code:

n = int(input())
a = list(map(int, input().split(" ")))


def solve(s1, s2):
    "if start == true, assume the first of the sum is positive."
    res = 0
    sum = 0
    for i in range(n):
        sum += a[i]
        if sum <= 0 and i % 2 == s1:
            res += abs(sum) + 1
            sum = 1
        elif sum >= 0 and i % 2 == s2:
            res += abs(sum) + 1
            sum = -1
    return res


print(min(solve(0, 1), solve(1, 0)))

Submission status: Accepted

Solution code:

n = int(input())
a = list(map(int, input().split(" ")))



res1 = 0
sum = 0
# sei, hu, sei, hu....
# guu, ki, guu, ki
for i in range(n):
    sum += a[i]
    if sum <= 0 and i%2 == 0:
        res1 += abs(sum) + 1
        sum = 1
    elif sum >= 0 and i%2 == 1:
        res1 += abs(sum) + 1
        sum = -1
    # hutuunitoku


res2 = 0
sum = 0
# hu, sei, hu, sei....
# guu, ki, guu, ki
for i in range(n):
    sum += a[i]
    if sum <= 0 and i%2 == 1:
        res2 += abs(sum) + 1
        sum = 1
    elif sum >= 0 and i%2 == 0:
        res2 += abs(sum) + 1
        sum = -1
    # hutuunitoku

print(min(res1, res2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

def chk(a,t):     # t=True(奇数項が正), t=False(偶数項が正) 
    cnt=0   # 操作回数
    x=0     # 塁積和        
    for i in a:
        x+=i      
        if t==True and x<=0:       # 正項予定なのに累積が負か0
            cnt+=1-x                              
            x=x+(1-x)               # 今回のcntで符号変更
        elif t==False and x>=0:   # 負項予定なのに累積が正か0
            cnt+=1+x              
            x=x-(1+x)              # 今回のcntで符号変換
        t = not t                  # 次の項は符号が逆
    return cnt

print(min(chk(a,True),chk(a,False)))

Submission status: Accepted

Solution code:
# @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-17 17:23
# @url:https://atcoder.jp/contests/abc059/tasks/arc072_a

import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def main():
    n=int(input())
    a=list(map(int,input().split()))
    prefix=[a[0]]
    for i in range(1,len(a)):
        prefix.append(prefix[-1]+a[i])
    s,t=0,0
    ans1,ans2=0,0
    for i in range(len(prefix)):
        if i%2==0:
            if prefix[i]+s<=0:
                ans1+=abs(prefix[i]+s)+1
                s=s+abs(prefix[i]+s)+1
            if prefix[i]+t>=0:
                ans2+=abs(prefix[i]+t+1)
                t=t-abs(prefix[i]+t+1)
        else:
            if prefix[i]+s>=0:
                ans1+=abs(prefix[i]+s+1)
                s=s-abs(prefix[i]+s+1)
            if prefix[i]+t<=0:
                ans2+=abs(prefix[i]+t)+1
                t=t+abs(prefix[i]+t)+1
    print (min(ans1,ans2))
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-17 17:23
# @url:https://atcoder.jp/contests/abc059/tasks/arc072_a

import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def main():
    n=int(input())
    a=list(map(int,input().split()))
    prefix=[a[0]]
    for i in range(1,len(a)):
        prefix.append(prefix[-1]+a[i])
    s,t=0,0
    ans1,ans2=0,0
    for i in range(len(prefix)):
        if i%2==0:
            if prefix[i]+s<=0:
                ans1+=abs(prefix[i]+s)+1
                s=s+abs(prefix[i]+s)+1
        else:
            if prefix[i]+s>=0:
                ans1+=abs(prefix[i]+s+1)
                s=s-abs(prefix[i]+s+1)
    for i in range(len(prefix)):
        if i%2==1:
            if prefix[i]+t<=0:
                ans2+=abs(prefix[i]+t)+1
                t=t+abs(prefix[i]+t)+1
        else:
            if prefix[i]+t>=0:
                ans2+=abs(prefix[i]+t+1)
                t=t-abs(prefix[i]+t+1)
    print (min(ans1,ans2))
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = tuple(map(int,input().split()))

def solve(f):
    acc = 0
    cnt = 0
    for a in A:
        acc += a
        if f and acc <= 0:
            cnt += 1 - acc
            acc = 1
        elif not f and acc >= 0:
            cnt += acc + 1
            acc = -1
        f = not f
    return cnt

print(min(solve(True),solve(False)))

Submission status: Accepted

Solution code:
def sign(X):
    return [-1,0,1][(X>=0)+(X>0)]

N = int(input())
A = [int(T) for T in input().split()]

AFPCnt = 0
AFPNow = 0
for TFP in range(0,N):
    AFPNow += A[TFP]
    if sign(AFPNow)!=(-1)**TFP:
        AFPCnt += abs(AFPNow)+1
        AFPNow = (-1)**TFP

AFFCnt = 0
AFFNow = 0
for TFF in range(0,N):
    AFFNow += A[TFF]
    if sign(AFFNow)!=(-1)**(TFF+1):
        AFFCnt += abs(AFFNow)+1
        AFFNow = (-1)**(TFF+1)
print(min(AFPCnt,AFFCnt))

Submission status: Accepted

Solution code:
#
# abc059 c
#

import sys
from io import StringIO
import unittest


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4
1 -3 1 0"""
        output = """4"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """5
3 -6 4 -5 7"""
        output = """0"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """6
-1 4 3 2 -5 4"""
        output = """8"""
        self.assertIO(input, output)


def resolve():
    N = int(input())
    A = list(map(int, input().split()))

    # n = odd : plus
    ansa = 0
    sa = 0
    for i in range(N):
        sa += A[i]
        if i % 2 == 0:
            if sa >= 0:
                ansa += abs(sa) + 1
                sa = -1
        else:
            if sa <= 0:
                ansa += abs(sa) + 1
                sa = 1

    # n = even : plus
    ansb = 0
    sb = 0
    for i in range(N):
        sb += A[i]
        if i % 2 == 0:
            if sb <= 0:
                ansb += abs(sb) + 1
                sb = +1
        else:
            if sb >= 0:
                ansb += abs(sb) + 1
                sb = -1

    print(min(ansa, ansb))


if __name__ == "__main__":
    #unittest.main()
    resolve()

Submission status: Accepted

Solution code:
import sys
import math
import collections
import bisect
import itertools

import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

def main():
    n = ni()
    a = na()
    b = a.copy()

    a_cnt = 0
    a_sum = 0
    b_cnt = 0
    b_sum = 0

    for i in range(n):
        tmp = a_sum + a[i]
        if i % 2:
            if tmp <= 0:
                a_cnt += 1 + abs(tmp)
                a_sum = 1
            else:
                a_sum += a[i]
        else:
            if tmp >= 0:
                a_cnt += 1 + abs(tmp)
                a_sum = -1
            else:
                a_sum += a[i]

    for i in range(n):
        tmp = b_sum + b[i]
        if not i % 2:
            if tmp <= 0:
                b_cnt += 1 + abs(tmp)
                b_sum = 1
            else:
                b_sum += b[i]
        else:
            if tmp >= 0:
                b_cnt += 1 + abs(tmp)
                b_sum = -1
            else:
                b_sum += b[i]

    print(min(a_cnt, b_cnt))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def solve():

    n = int(input())
    a = list(map(int, input().split()))

    b = [a[i] for i in range(n)]

   # print(a)
   # print(b)

    #Even
    sum_e = 0
    ans_e = 0

    for i in range(n):
        sum_e += a[i]
        if i%2 == 0:
            if sum_e <= 0:
                ans_e += abs(sum_e) + 1
                sum_e += abs(sum_e) + 1
        else:
            if sum_e >= 0:
                ans_e += abs(sum_e) + 1
                sum_e -= abs(sum_e) + 1

    #Odd
    sum_o = 0
    ans_o = 0

    for i in range(n):
        sum_o += b[i]
        if i%2 == 1:
            if sum_o <= 0:
                ans_o += abs(sum_o) + 1
                sum_o += abs(sum_o) + 1
        else:
            if sum_o >= 0:
                ans_o += abs(sum_o) + 1
                sum_o -= abs(sum_o) + 1

    if ans_o <= ans_e:
        ans = ans_o
    else:
        ans = ans_e


    print(ans)

if __name__ ==  "__main__":
    solve()

Submission status: Accepted

Solution code:
def main():
	n = int(input())
	a = list(map(int, input().split()))

	ans_v1 = 0
	ans_v2 = 0
	a_sum_v1 = 0
	a_sum_v2 = 0

	for i in range(0, n):
		if i % 2 == 0: # 0,2,4...番目までの和を正
			if a_sum_v1 + a[i] < 1:
				ans_v1 += 1 - a_sum_v1 - a[i]
				a_sum_v1 = 1
			else:
				a_sum_v1 += a[i]
		else:          # 1,3,5...番目までの和を負
			if a_sum_v1 + a[i] > -1:
				ans_v1 += 1 + a_sum_v1 + a[i]
				a_sum_v1 = -1
			else:
				a_sum_v1 += a[i]
	
	for i in range(0, n):
		if i % 2 == 0: # 0,2,4...番目までの和を負
			if a_sum_v2 + a[i] > -1:
				ans_v2 += 1 + a_sum_v2 + a[i]
				a_sum_v2 = -1
			else:
				a_sum_v2 += a[i]
		else:          # 1,3,5...番目までの和を正
			if a_sum_v2 + a[i] < 1:
				ans_v2 += 1 - a_sum_v2 - a[i]
				a_sum_v2 = 1
			else:
				a_sum_v2 += a[i]

	print(min(ans_v1, ans_v2))

 
if __name__ == "__main__":
  	main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = list(map(int,readline().split()))

ans1 = 0
ans2 = 0
S1 = 0
S2 = 0
# 偶数項-,奇数項を+にする
for i in range(N):
    S1 += A[i]
    S2 += A[i]
    if i & 1: 
        if S1 >= 0:
            ans1 += S1+1
            S1 = -1
        if S2 <= 0:
            ans2 += 1-S2
            S2 = 1
    else: 
        if S1 <= 0:
            ans1 += 1-S1
            S1 = 1
        if S2 >= 0:
            ans2 += S2+1
            S2 = -1
print(min(ans1,ans2))

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int, input().split()))

def f(a, ans):
    for i in range(1,n):
        b = A[i]            
        if a> 0:
            if a + b >= 0:
                ans += abs(-1-a-b)
                a = -1
            else:
                a += b
        elif a < 0:
            if a+b <= 0:
                ans += abs(1-a-b)
                a = 1
            else:
                a += b
    return ans

# A[0] の初期符号が正しいと仮定してしまっているが、そうとは限らない。
a = A[0]
q = 10**15
if a > 0:
    q = min(f(a,0), f(-1,a+1))
elif a < 0:
    q = min(f(a,0),f(1,-a+1))
else:
    q = min(f(1,1),f(-1,1))

print(q)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate
def input(): return sys.stdin.readline().strip()

def main():
    N = int(input())
    A = list(map(int, input().split()))
    S = list(accumulate(A))

    # 先頭が正の場合
    times_plus = 0
    added = 0
    for i in range(N):
        num = S[i] + added
        if num * (-1)**i > 0: continue
        added += abs(num - (-1)**i) * (-1)**i
        times_plus += abs(num - (-1)**i)
        

    # 先頭が負の場合
    times_minus = 0
    added = 0
    for i in range(1, N + 1):
        num = S[i - 1] + added
        if num * (-1)**i > 0: continue
        added += abs(num - (-1)**i) * (-1)**i
        times_minus += abs(num - (-1)**i)
    
    print(min(times_minus, times_plus))
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
sm1=0
sm2=0
cnt=0
cnt2=0

for i in range(N):
    sm1+=A[i]
    if i%2==1:
        if sm1>=0:               
            cnt+=sm1+1
            sm1=-1
    else:
        if sm1<=0:               
            cnt+=sm1*-1+1
            sm1=1

for i in range(N):
    sm2+=A[i]
    if i%2==1:
        if sm2<=0:
            cnt2+=sm2*-1+1
            sm2=1
    else:
        if sm2>=0:
            cnt2+=sm2+1
            sm2=-1
print(min(cnt,cnt2))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
ans1=0
ans2=0
flg=True
t=0
for i in range(n):
    t+=a[i]
    if flg:
        if t<=0:
            ans1+=1-t
            t=1
        flg=False
    else:
        if t>=0:
            ans1+=t+1
            t=-1
        flg=True
t=0
flg=True
for i in range(n):
    t+=a[i]
    if flg==False:
        if t<=0:
            ans2+=1-t
            t=1
        flg=True
    else:
        if t>=0:
            ans2+=t+1
            t=-1
        flg=False
print(min(ans1,ans2))

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))
cs1=0
s1=0
for i,a in enumerate(l):
    cs1+=a
    if i%2==0:
        if cs1>=0:
            s1+=abs(cs1)+1
            cs1=-1
    else:
        if cs1<=0:
            s1+=abs(cs1)+1
            cs1=1
cs2=0
s2=0
for i,a in enumerate(l):
    cs2+=a
    if i%2==0:
        if cs2<=0:
            s2+=abs(cs2)+1
            cs2=1
    else:
        if cs2>=0:
            s2+=abs(cs2)+1
            cs2=-1
print(min(s1,s2))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))

cumsum1 = 0
ans1 = 0

for n in range(N):
  cumsum1 += A[n]
  if n % 2 == 0:
    if cumsum1 >= 0:
      ans1 += abs(cumsum1)+1
      cumsum1 = -1
  else:
    if cumsum1 <= 0:
      ans1 += abs(cumsum1)+1
      cumsum1 = 1
      
      
cumsum2 = 0
ans2 = 0

for n in range(N):
  cumsum2 += A[n]
  if n % 2 == 0:
    if cumsum2 <= 0:
      ans2 += abs(cumsum2)+1
      cumsum2 = 1
  else:
    if cumsum2 >= 0:
      ans2 += abs(cumsum2)+1
      cumsum2 = -1
      
print(min(ans1,ans2))

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))

CumSum = [0] * n
c = 0
for i,a in enumerate(A):
    c += a
    CumSum[i] = c
# 最初が正の場合
total_cost = 0
c_sum = 0
for i,a in enumerate(A):
    c_sum += a
    if i % 2 ==0:
        if c_sum > 0:
            continue
        total_cost += abs(c_sum)+ 1
        c_sum = 1
        continue

    if c_sum < 0:
        continue
    total_cost += abs(c_sum)+ 1
    c_sum = -1
# 最初が負の場合
total_cost2 = 0
c_sum = 0
for i,a in enumerate(A):
    c_sum += a
    if i % 2 ==0:
        if c_sum < 0:
            continue
        total_cost2 += abs(c_sum)+ 1
        c_sum = -1
        continue

    if c_sum > 0:
        continue
    total_cost2 += abs(c_sum)+ 1
    c_sum = 1
print(min(total_cost,total_cost2))

Submission status: Accepted

Solution code:
def my_sign(x):
    return (x > 0) - (x < 0)

N = int(input())
A = list(map(int,input().split()))
tsum = 0 #これが答え。いくつ足したか。
nsum = A[0]
#一個目をプラスにする場合
if A[0] <= 0:
  nsum = 1
  tsum = 1-A[0]
for i in range(1,N):
  #print(nsum,nsum+A[i],tsum)
  if my_sign(nsum)*my_sign(nsum+A[i]) == -1: #符号が違う場合はそのままでおｋ
    #print(nsum,"A")
    nsum += A[i]
  else:
    if nsum>0: #次で負にする必要がある
      #print(abs(nsum+A[i]+1))
      tsum += abs(nsum+A[i]+1)
      nsum = -1
    else:
      #print(nsum+A[i],abs(nsum+A[i]-1),"X")
      tsum += abs(nsum+A[i]-1)
      nsum = 1      
ans = tsum
#print(ans)
tsum = 0 #これが答え。いくつ足したか。
nsum = A[0]
#一個目をマイナスにする場合
if A[0] >= 0:
  nsum = -1
  tsum = A[0]+1
for i in range(1,N):
  #print(nsum,nsum+A[i],tsum)
  if my_sign(nsum)*my_sign(nsum+A[i]) == -1: #符号が違う場合はそのままでおｋ
    nsum += A[i]
  else:
    if nsum>0: #次で負にする必要がある
      tsum += abs(nsum+A[i]+1)
      nsum = -1
    else:
      #print(nsum,nsum+A[i])
      tsum += abs(nsum+A[i]-1)
      nsum = 1
ans = min(ans,tsum)
print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
As = list(mapint())

cum = As.pop(0)
if cum!=0:
    cum2 = cum
    ans = 0
    for a in As:
        if cum*(cum+a)>=0:
            ans += abs(cum+a)+1
            cum = -1 if cum>0 else 1
        else:
            cum += a
        
    ans2 = abs(cum2)+1
    cum2 = 1 if cum2<0 else -1
    for a in As:
        if cum2*(cum2+a)>=0:
            ans2 += abs(cum2+a)+1
            cum2 = -1 if cum2>0 else 1
        else:
            cum2 += a
    print(min(ans, ans2))
else:
    cum = -1
    ans = 1
    for a in As:
        if cum*(cum+a)>=0:
            ans += abs(cum+a)+1
            cum = -1 if cum>0 else 1
        else:
            cum += a
        
    ans2 = 1
    cum2 = 1
    for a in As:
        if cum2*(cum2+a)>=0:
            ans2 += abs(cum2+a)+1
            cum2 = -1 if cum2>0 else 1
        else:
            cum2 += a
    print(min(ans, ans2))

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
B = A[:]
cntp = 0
totp = 0
for i in range(n):
    if i%2==0:
        if B[i]>=1-totp:
            totp += B[i]
        else:
            cntp += 1-totp-B[i]
            totp = 1
    else:
        if B[i]<=-1-totp:
            totp += B[i]
        else:
            cntp += B[i]+1+totp
            totp = -1
cntm = 0
totm = 0
for i in range(n):
    if i%2==0:
        if B[i]<=-1-totm:
            totm += B[i]
        else:
            cntm += B[i]+1+totm
            totm = -1
    else:
        if B[i]>=1-totm:
            totm += B[i]
        else:
            cntm += 1-totm-B[i]
            totm = 1
print(min(cntp,cntm))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import accumulate, product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b

# https://atcoder.jp/contests/abc059/tasks/arc072_a

# si=a1+..+aiと定義する
# s1...si,si+1,snの符号は+-+-... or -+-+...にしたい←両方試せばいい
# +-+-にするのに最小の操作は？


n = a_int()
A = ints()
S = list(accumulate(A))

#+-+-のとき
now = 1  # 正負
pad = 0
ans1 = 0
for s in S:
    s += pad
    if s * now <= 0:  # 異符号だったら修正する必要あり
        if now == 1:  # +にしたい場合
            n_ope = 1 - s
            pad += n_ope
        else:  # -にしたい場合
            n_ope = s + 1
            pad -= n_ope
        ans1 += n_ope
    now *= -1

#-+-+のとき
now = -1  # 正負
pad = 0
ans2 = 0
for s in S:
    s += pad
    if s * now <= 0:  # 異符号だったら修正する必要あり
        if now == 1:  # +にしたい場合
            n_ope = 1 - s
            pad += n_ope
        else:  # -にしたい場合
            n_ope = s + 1
            pad -= n_ope
        ans2 += n_ope
    now *= -1

# print(S)
# print(ans1, ans2)
print(min(ans1, ans2))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

# 方針:正負正...と負正負...の両方を試す
ans = 0
now = 0
for i in range(N):
    if i % 2 == 0:# 正にする
        if now+A[i] <= 0:
            ans += 1 - (now+A[i])
            now = 1
        else:
            now += A[i]
    else:
        if now+A[i] >= 0:
            ans += 1 + (now+A[i])
            now = -1
        else:
            now += A[i]
ans2 = 0
now = 0
for i in range(N):
    if i % 2 == 1:# 正にする
        if now+A[i] <= 0:
            ans2 += 1 - (now+A[i])
            now = 1
        else:
            now += A[i]
    else:
        if now+A[i] >= 0:
            ans2 += 1 + (now+A[i])
            now = -1
        else:
            now += A[i]

print(min(ans,ans2))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))

ans1 = c = 0
for i,a in enumerate(A):
    if i%2==0:
        if c+a > 0:
            c += a
        else:
            d = 1-(c+a)
            ans1 += d
            c = 1
    else:
        if c+a < 0:
            c += a
        else:
            d = c+a+1
            ans1 += d
            c = -1

ans2 = c = 0
for i,a in enumerate(A):
    if i%2:
        if c+a > 0:
            c += a
        else:
            d = 1-(c+a)
            ans2 += d
            c = 1
    else:
        if c+a < 0:
            c += a
        else:
            d = c+a+1
            ans2 += d
            c = -1

print(min(ans1, ans2))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

c = A[0]
ans1 = 0
for a in A[1:]:
    if c > 0 and c + a >= 0:
        ans1 += c + a + 1
        c = -1

    elif c < 0 and c + a <= 0:
        ans1 += -(c + a) + 1
        c = 1

    else:
        c = c + a


c = 1
ans2 = abs(A[0] - 1)
for a in A[1:]:
    if c > 0 and c + a >= 0:
        ans2 += c + a + 1
        c = -1

    elif c < 0 and c + a <= 0:
        ans2 += -(c + a) + 1
        c = 1

    else:
        c = c + a


c = -1
ans3 = abs(A[0] + 1)
for a in A[1:]:
    if c > 0 and c + a >= 0:
        ans3 += c + a + 1
        c = -1

    elif c < 0 and c + a <= 0:
        ans3 += -(c + a) + 1
        c = 1

    else:
        c = c + a

print(min(ans1, ans2, ans3))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))
cnt1, now = 0, 0

for i in range(n):
    now += a[i]
    
    if i%2==0:
        if now<=0:
            cnt1 += 1-now
            now = 1
    else:
        if now>=0:
            cnt1 += now+1
            now = -1
    
cnt2, now = 0, 0

for i in range(n):
    now += a[i]
    
    if i%2==1:
        if now<=0:
            cnt2 += 1-now
            now = 1
    else:
        if now>=0:
            cnt2 += now+1
            now = -1

print(min(cnt1, cnt2))

Submission status: Accepted

Solution code:
import sys
import copy

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N = in_n()
    A = in_nl()

    def solve():

        ta = copy.copy(A)
        cnt1 = 0

        if ta[0] <= 0:
            t = -ta[0] + 1
            cnt1 += t
            ta[0] += t

        sum_a = ta[0]
        for i in range(1, N):
            if i % 2 == 0:
                if sum_a + ta[i] <= 0:
                    t = -(sum_a + ta[i]) + 1
                    cnt1 += t
                    ta[i] += t
            else:
                if sum_a + ta[i] >= 0:
                    t = sum_a + ta[i] + 1
                    cnt1 += t
                    ta[i] -= t
            sum_a += ta[i]

        #####

        ta = copy.copy(A)
        cnt2 = 0

        if ta[0] >= 0:
            t = ta[0] + 1
            cnt2 += t
            ta[0] -= t

        sum_a = ta[0]
        for i in range(1, N):
            if i % 2 == 1:
                if sum_a + ta[i] <= 0:
                    t = -(sum_a + ta[i]) + 1
                    cnt2 += t
                    ta[i] += t
            else:
                if sum_a + ta[i] >= 0:
                    t = sum_a + ta[i] + 1
                    cnt2 += t
                    ta[i] -= t
            sum_a += ta[i]

        return min(cnt1, cnt2)

    ans = solve()
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n = INT()
a = LIST()

l = [1]*n
l1 = [l[i]*(-1)**i for i in range(n)]
l2 = [l[i]*(-1)**(i+1) for i in range(n)]

ans1 = 0
tmp1 = 0
for i, r in enumerate(a):
	tmp1 += r
	if tmp1*l1[i] <= 0:
		ans1 += abs(tmp1) + 1
		tmp1 = l1[i]

ans2 = 0
tmp2 = 0
for i, r in enumerate(a):
	tmp2 += r
	if tmp2*l2[i] <= 0:
		ans2 += abs(tmp2) + 1
		tmp2 = l2[i]

print(min(ans1, ans2))