Problem:


Score: 200 points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).

Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 2020202020

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:

Shrink the second section from the left. The lengths of the sections are now [2, 3, 3].

Shrink the first section from the left. The lengths of the sections are now [1, 3, 3].

Shrink the second section from the left. The lengths of the sections are now [1, 2, 3], and we can cut the bar at the second notch from the left into two parts of length 3 each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0



Sample input:
3
2 4 3


Sample output:
3

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
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()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

N = INT()
A = LIST()

ans = INF
A_sum = sum(A)
tmp = 0
for x in A:
	tmp += x
	ans = min(ans, abs(tmp-(A_sum-tmp)))

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
x=[a[0]]
y=[sm-a[0]]
for i in range(1,n):
  x.append(x[i-1]+a[i])
  y.append(sm-x[i])
min=9999999999
for (p,q) in zip(x,y):
  sa=abs(p-q)
  if sa<min:
    min=sa

print(min)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split()]

l = sum(A)
ans = float("inf")
t = 0

for i in range(N-1):
	t += A[i]
	ans = min(ans,abs(l-2*t))
	#print("t,ans",t,ans)

print(ans)

Submission status: Accepted

Solution code:
N,A=open(0)
*A,=map(int,A.split())
S=M=sum(A)
C=0
for a in A:
    C+=a
    M=min(M,abs(S-2*C))
print(M)

Submission status: Accepted

Solution code:
N=int(input())
*A,=map(int,input().split())
S=sum(A)

count1=0
count2=[0]*N
i=0
while i<N:
    count1+=A[i]
    count2[i]=abs(S-2*count1)
    i+=1

print(min(count2))

Submission status: Accepted

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

l1 = 0
l2 = sum(a)
d = l2
for i in range(n):
    l1 += a[i]
    d = min(d, abs(2*l1 - l2))
print(d)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N = I()
L = IL()
S = sum(L)
LL = L[::-1]
SUM = 0
while SUM<S/2:
  SUM+=L.pop()
ans1 = abs(S-SUM*2)
  
SUM=0
while SUM<S/2:
  SUM+=LL.pop()
ans2 = abs(S-SUM*2)
  
print(min(ans1,ans2))

Submission status: Accepted

Solution code:
n = int(input())
li = list(map(int,input().split()))
ans = 100000000000000000

for i in range(1,n):
    if i == 1:
        x = sum(li[:i])
        y = sum(li[i:])
    else:
        x += li[i-1]
        y -= li[i-1]
    z = abs(x-y)
    if z < ans:
        ans = z
    
print(ans)

Submission status: Accepted

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

right = sum(a)
left = 0
ans = float("inf")

for i in a:
    left += i
    right -= i
    # print(right-left)
    ans = min(ans, abs(right-left))
print(ans)

Submission status: Accepted

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

almost_half = sum(A)/2

former = 0
for n in range(N):
  former += A[n]
  if former == almost_half:
    print(0)
    break
    
  if former > almost_half:
    if n == 0:
      #print("case01",n,former)
      print(abs(A[0]-sum(A[1:])))
      break
    elif n == N-1:
      #print("case02",n,former)
      print(abs(A[n]-sum(A[:n])))
      break
    else:
      #print("case03",n,former)
      #print(abs(sum(A[n:])-sum(A[:n])),abs(sum(A[n+1:])-sum(A[:n+1])))
      print(min(abs(sum(A[n:])-sum(A[:n])),abs(sum(A[n+1:])-sum(A[:n+1]))))
      break

Submission status: Accepted

Solution code:
# For taking integer inputs.
import math
from decimal import Decimal
from itertools import permutations


def inp():
    return(int(input()))


# For taking List inputs.
def inlist():
    return(list(map(int, input().split())))


# For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.
def instr():
    s = input()
    return(list(s[:len(s)]))


# For taking space seperated integer variable inputs.
def invr():
    return(map(int, input().split()))


n = inp()
a = inlist()
pref = [0] * (n)
suf = [0] * n
pref[0] = a[0]
suf[n-1] = a[n-1]
j = n - 2
for i in range(1, n):
    pref[i] = a[i] + pref[i-1]
    suf[j] = a[j] + suf[j+1]
    j -= 1

D = 10000000000000000
for i in range(0, n-1):

    s1 = pref[i]
    s2 = suf[i+1]
    d = abs(s1 - s2)
    if d < D:

        D = d

print(D)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split(" ")]
Min = float("inf")
index = 0
L = 0
R = sum(A)
for i in range(0,len(A)):
    L+=A[i]
    R-=A[i]
    diff = abs(L - R)
    if diff < Min:
        Min = diff
print(Min)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=sum(A)
b=0
ans=202020202020
for a in A:
    b+=a
    ans=min(ans,abs(B-b*2))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
left = 0
SUM = sum(A)
res = SUM
for i in range(N):
    left += A[i] 
    res = min(res,abs(2*left-SUM))
print(res)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

sys.setrecursionlimit(10**7)

ni = lambda: int(ns())
nin = lambda y: [ni() for _ in range(y)]
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda y: [na() for _ in range(y)]
nf = lambda: float(ns())
nfn = lambda y: [nf() for _ in range(y)]
nfa = lambda: list(map(float, stdin.readline().split()))
nfan = lambda y: [nfa() for _ in range(y)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda y: [ns() for _ in range(y)]
ncl = lambda y: [list(ns()) for _ in range(y)]
nas = lambda: stdin.readline().split()

n = ni()
a = na()

ans = inf
s = sum(a)
cur = 0
for i in range(n):
    cur += a[i]
    ans = min(ans, abs(cur * 2 - s))

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
m = 10**10
x = sum(a)
y = 0
for i in range(n):
    x -= a[i]
    y += a[i]
    m = min(abs(x-y),m)
print(m)

Submission status: Accepted

Solution code:
from itertools import accumulate
n = int(input())
A = list(map(int,input().split()))
B = list(accumulate(A))
m = float("inf")
for i in B:
    m = min(m,abs(2*i-B[-1]))
print(m)

Submission status: Accepted

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

for i in range(1,N):
    A[i] += A[i-1]

diff_min = 10**16

for i in range(N):
    diff_min = min(diff_min,abs(A[N-1]-2*A[i]))

print(diff_min)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def main():
    N = int(input())
    A = list(map(int, input().split()))
    com_left = [0] * (N+1)
    com_right = [0] * (N+1)
    total = sum(A)
    for i in range(N):
        com_left[i+1] = com_left[i] + A[i]
        com_right[i] = total - com_left[i]
    ans = 2020202020
    for i in range(N):
        diff = abs(com_left[i] - com_right[i])
        ans = min(ans, diff)
    print(ans)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def main():
    N = int(input())
    A = list(map(int, input().split()))
    mid = sum(A) / 2
    x = 0
    near_length = 0
    for a in A:
        x += a
        if x >= mid:
            if x - mid > abs(x - a - mid):
                near_length = abs(x - a)
            else:
                near_length = x
            break
    ans = int(abs(mid-near_length) * 2)
    print(ans)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
ruiseki_WA=[0]
for i in range(n):
    ruiseki_WA.append(ruiseki_WA[i]+a[i])
ans=float("inf")
for i in range(n):
    kari=abs(ruiseki_WA[i]-(ruiseki_WA[-1]-ruiseki_WA[i]))
    ans=min(ans,kari)
print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import itertools
def main():
    #入力
    readline=stdin.readline
    n=int(readline())
    a=list(map(int,readline().split()))

    s1=[0]*n
    s2=[0]*n
    for i in range(n):
        if i==0:
            s1[i]=a[i]
        else:
            s1[i]+=s1[i-1]+a[i]

    for i in range(n-1,-1,-1):
        if i==n-1:
            s2[i]=a[i]
        else:
            s2[i]+=s2[i+1]+a[i]

    ans=float("inf")
    for i in range(n-1):
        ans=min(ans,abs(s1[i]-s2[i+1]))

    print(ans)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate


N = int(input())
A = [0] + list(accumulate(map(int, input().split())))
min_diff = float("inf")
for i in range(N - 1):
    if abs(A[N] - 2 * A[i + 1]) < min_diff:
        min_diff = abs(A[N] - 2 * A[i + 1])
print(min_diff)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(x) for x in input().rstrip().split()]
full=sum(a)
now=0
ans=float('inf')
for i in a:
  now+=i
  ans=min(abs(full-2*now),ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N = ii()
A = li()

acc = list(accumulate(A))
#sa = acc[-1] -acc[0]

for i in range(N):
    if acc[i] - (acc[-1] - acc[i]) >= 0:
        break

if i == N-1:
    print(abs(A[i] - acc[i-1]))
elif i == 0:
    print(abs(acc[i] - (acc[-1] - acc[i])))
else:
    ans = min(abs(acc[i] - (acc[-1] - acc[i])), abs(acc[i-1] - (acc[-1] - acc[i-1])))
    print(ans)

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 accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
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()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = LIST()

ans = INF

sum_A = sum(A)
tmp = 0
for a in A:
	tmp += a
	ans = min(ans, abs(tmp-(sum_A-tmp)))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
S = sum(A)
L = 0
for i, a in enumerate(A):
  if L + a <= S/2:
    L += a
  else:
    R = S - L
    diff = R - L
    if 2*a - diff < diff:
      L += a
      R -= a
    break
    
R = S - L
print(abs(R - L))

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int, input().split()))
for i in range(n - 1):
	A[i + 1] += A[i]
minv = float('inf')
for a in A[:-1]:
	minv = min(minv, abs(A[-1]/2 - a))
print(int(minv * 2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = [0]*n
for i in range(n):
  b[i] = a[i] + b[i-1]
ans = b[-1]
for j in range(n):
  ans = min(ans,abs(b[-1]-b[j]*2))
print(ans)

Submission status: Accepted

Solution code:
import numpy
import numpy as np
N=int(input())
AList=list(map(int,input().split()))
AListSum=sum(AList)
CumSum=numpy.cumsum(numpy.array(AList))
CumSum=list(CumSum)
#print(AList)
#print(CumSum)
#print(AListSum)

def getNearestValue(List, num):
    idx = np.abs(np.asarray(List) - num).argmin()
    return idx
#print(getNearestValue(CumSum, AListSum/2))

MAE=sum(AList[:(getNearestValue(CumSum, AListSum/2))+1])
USHIRO=sum(AList[(getNearestValue(CumSum, AListSum/2))+1:])
print(abs(MAE-USHIRO))

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
b = []
sum_a = sum(a)
cum = 0
for i in a:
  cum += i
  b.append(abs(sum_a  - cum * 2))
print(min(b))

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
x=sum(A)
y=10**19
a=0
for i in range(N):
    a+=A[i]
    if y>abs(x-2*a):#2区間の差
        y=abs(x-2*a)
        
    else:
        break

print(y)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
a_cumsum = [0]*(n+1)
for i in range(n):
    a_cumsum[i+1] = a_cumsum[i] + a[i]

ans = 10**18
for i in range(n):
    ans = min(ans, abs(a_cumsum[-1] - a_cumsum[i]*2))
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
total=sum(A)
cost=total
cumulative=0
for i in range(N):
    cumulative+=A[i]
    cost=min(cost,abs(cumulative-(total-cumulative)))
print(cost)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/ddcc2020-qual/tasks/ddcc2020_qual_b

n = int(input())
nums = [int(i) for i in input().split()]
for i in range(n - 1):
    nums[i + 1] += nums[i]

ans = float('inf')
for i in range(n - 1):
    d = abs(nums[-1] - nums[i] * 2)
    ans = min(ans, d)
print(ans)

Submission status: Accepted

Solution code:
import sys, itertools

N = int(input())
A = list(map(int, sys.stdin.readline().rsplit()))

S = list(itertools.accumulate(A))

mini = 10 ** 18
for i in range(N):
    mini = min(mini, abs(S[N - 1] - 2 * S[i]))

print(mini)

Submission status: Accepted

Solution code:
import sys

N = int(input())
A = list(map(int, sys.stdin.readline().rsplit()))
S = [0] * (N + 1)
s = sum(A)

for i in range(N):
    S[i + 1] += S[i] + A[i]

mini = 10 ** 18
for i in range(1, N + 1):
    mini = min(mini, abs(S[N] - 2 * S[i]))

print(mini)

Submission status: Accepted

Solution code:
import bisect
n=int(input())
a=list(map(int,input().split()))
suma=[]
sumans=0
for i in range(n):
	sumans += a[i]
	suma.append(sumans)
u=bisect.bisect_right(suma, sumans//2)
print(min(abs(2*suma[u-1]-sumans), abs(2*suma[u]-sumans)))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
sum=[0]*(len(a)+1)
for i in range(len(a)):
    sum[i+1]=sum[i]+a[i]
# print(sum)

mini=2020202020
for i in range(len(sum)):
    mini=min(mini, abs(sum[i] - (sum[-1] - sum[i])))

print(mini)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
hoge = [0] * n
cnt = 0
for i in range(n):
    #hoge[i + 1] = hoge[i] + a[i]
    cnt += a[i]
    hoge[i] = cnt
hoge_ = [0] * n
cnt = 0
for i in range(n - 1, -1, -1):
    cnt += a[i]
    hoge_[i] = cnt
ans = float('Inf')
for i in range(n - 1):
    ans = min(ans, abs(hoge[i] - hoge_[i + 1]))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

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

cnt = 0
ave = sum(a)/2

for i in range(n):
    cnt += a[i]
    if cnt >= ave:
        ans = min(cnt*2-ave*2, ave*2-(cnt-a[i])*2)
        break

print(int(ans))

Submission status: Accepted

Solution code:
import sys

n = int(input())

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

cnt = 0
ave = sum(a)/2

for i in range(n):
    cnt += a[i]
    if cnt == ave:
        print(0)
        sys.exit()
    
    elif cnt > ave:
        x = ave -cnt +a[i]
        if x >= cnt -ave:
            x = cnt -ave
        break

print(int(x*2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split())) # 横入力

x = [0]
aaa = 0
aa = sum(a)
# y = [aa]
for i in range(n):
    aaa += a[i]
    x.append(aaa)
    # aa -= a[i]
    # y.append(aa)

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(aa - x[i]*2))

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split())) # 横入力

x = [0]
aaa = 0
aa = sum(a)
y = [aa]
for i in range(n):
    aaa += a[i]
    x.append(aaa)
    aa -= a[i]
    y.append(aa)

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(x[i] - y[i]))

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split())) # 横入力

x = [0]
aaa = 0
for i in range(n):
    aaa += a[i]
    x.append(aaa)
aa = sum(a)
y = [aa]
for i in range(n):
    aa -= a[i]
    y.append(aa)

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(x[i] - y[i]))

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[15]:


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


# In[17]:


total = sum(A)
ans = total
left = 0
for i in A:
    left += i
    right = total - left
    ans = min(ans, abs(left - right))
#     print(left, right, ans)
print(ans)


# In[ ]:

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d


# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定



# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n = int(input())    
a = list(map(int, input().split()))
total = sum(a)
cnt = 0
ans = 0
for i in range(n):
    cnt += a[i]
    if cnt == total / 2:
        break
    if cnt >= -(-total // 2):
        ans += a[i] - (abs(total - cnt - (cnt - a[i])))
        break
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
right = sum(a)
left = 0
ans=10**20
for l in a:
  left+=l
  right-=l
  ans=min(ans,abs(left-right))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
LEFT = A[0]
RIGHT = sum(A[1:])
MIN = abs(LEFT-RIGHT)
for i in range(1,N-1):
    LEFT += A[i]
    RIGHT -= A[i]
    MIN = min(MIN,abs(LEFT-RIGHT))
print(MIN)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
t = sum(a)
ans = sum(a)
l = 0
for i in a:
    l += i 
    r = t-l
    ans = min(ans, abs(l-r))
print(ans)

Submission status: Accepted

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

ans = (2020202020)**100
sum_A = sum(A)
hoge = 0


for i in range(N-1):
  hoge = hoge + A[i]
  ans = min(ans,(abs(sum_A - (hoge*2))))

print(ans)

Submission status: Accepted

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

ans = float('inf') 
sum_A = sum(A)
CumSum = 0


for i in range(N-1):
  CumSum = CumSum + A[i]
  ans = min(ans,(abs((sum_A - CumSum)-(CumSum))))

print(ans)

Submission status: Accepted

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

ans = float('inf')
sum_A = sum(A)
hoge = 0


for i in range(N-1):
  hoge = hoge + A[i]
  ans = min(ans,abs(sum_A - (hoge*2)))

print(ans)

Submission status: Accepted

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

left = a[0]
right = a[-1]
center = 0
sum_a = sum(a)
flg = False
for i in range(1, n-1):
    if left + a[i] > sum_a/2 and flg is False:
        flg = True
        center = a[i]
        right -= a[i]
    elif left + a[i] == sum_a / 2:
        print(0)
        exit()
    if flg is False:
        left += a[i]
    else:
        right += a[i]

print(abs(min(left+center-right, right+center-left)))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
allL = sum(A)
L, mL = 0, float('inf')
for i in range(N):
    L += A[i]
    if abs(2*L-allL) < mL:
        mL = abs(2*L-allL)
    else:
        break
print(mL)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
nagasa = sum(a)
now = 0
for i in range(n):
    if now + a[i] < nagasa/2:
        now += a[i]
    elif now + a[i] == nagasa/2:
        print(0)
        exit()
    elif now + a[i] > nagasa/2:
        print(min(nagasa-2*now,2*(now+a[i])-nagasa))
        exit()

Submission status: Accepted

Solution code:
import itertools,numpy as np,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N = I()
A = LI()
sum_A = sum(A)
accumulate_A = np.array(list(itertools.accumulate(A)))
sub_A1 = sum_A-accumulate_A
sub_A2 = sum_A-sub_A1
print(np.abs(sub_A1-sub_A2).min())

Submission status: Accepted

Solution code:
import itertools,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N = I()
A = LI()
ans = float('INF')
sum_A = sum(A)
accumulate_A = list(itertools.accumulate(A))
for i in range(N-1):
    ans = min(ans,abs(sum_A-accumulate_A[i]*2))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
total = sum(a)
total_a, total_b = 0, 0
i = 0
while total_a + a[i] <= total / 2:
    total_a += a[i]
    i += 1
i = n - 1
while total_b + a[i] <=  total / 2:
    total_b += a[i]
    i -= 1

print(total - max(total_a, total_b) * 2)

Submission status: Accepted

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

total_length = sum(as_)
current = 0
for a in as_:
    if current + a == total_length // 2:
        print(0)
        exit(0)
    if current + a > total_length / 2:
        candidate1 = current
        candidate2 = current + a
        break

    current += a

left1 = candidate1
right1 = total_length - left1
left2 = candidate2
right2 = total_length - left2


ans = min(
    right1 - left1, # 左が短いので左を伸ばすまたは右を縮める
    left2 - right2 # 左が長いので左を縮めるまたは右を伸ばす
)
print(ans)

Submission status: Accepted

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

mid = sum(a)/2
cum = 0
diff = 10**10
for each in a:
  cum += each
  diff = min(diff, abs(mid-cum))
  
print(int(diff/0.5))

Submission status: Accepted

Solution code:
import numpy as np

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

cum = np.cumsum(a)
mid = cum[-1]/2
diff = 10**10
for each in cum:
  diff = min(diff, abs(mid-each))
  
print(int(diff/0.5))

Submission status: Accepted

Solution code:
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))

A_cs = A.cumsum()
A_cs = A_cs - A_cs[-1]/2
div = np.abs(A_cs).argmin()

print(abs(A[:div+1].sum() - A[div+1:].sum()))

Submission status: Accepted

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

def resolve():
    from itertools import accumulate

    N = int(input())  # len(A)
    A = list(map(int, input().split()))
    zenbu=sum(A)
    B = [0] + A
    B = list(accumulate(B))
    C = [zenbu]*(N+1)
    import numpy as np
    B=np.array(B)
    C=np.array(C)
    D=C-B
    ans=10**18
    for i in range(1, N):
        ans = min(abs(B[i]-D[i]),ans)
    print(ans)
resolve()