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:
n = int(input())
a = list(map(int, input().split()))
total = sum(a)
l = 0
for i, ai in enumerate(a):
    l += ai
    if l >= total // 2:
        break
c1 = l - (total - l)
c2 = total - (l - ai) - (l - ai)
print(min(c1, c2))

Submission status: Accepted

Solution code:
N = int(input())
A  = list(map(int,input().split()))
now = 0
sumA = sum(A)
for i in range(N):
    now += A[i]
    if now == sumA/2:
        print(0)
        break
    elif now > sumA/2:
        test1 = now-sum(A[i+1:])
        test2 = sum(A[i:])-(now-A[i])
        print(int(min([test1,test2])))    
        break

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
suml=[0]*n
suml[0]=a[0]
for i in range(1,n):
  suml[i]=suml[i-1]+a[i]
total=suml[-1]
ans=10**20
for i in range(n):
  if ans>abs(total-2*suml[i]):
    ans=abs(total-2*suml[i])
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
SUM=sum(a)
hlf=SUM//2
cnt=0
res=float('inf')
for i in range(n):
    cnt+=a[i]
    rst=SUM-cnt
    if cnt==hlf:
        print(0)
        exit()
    res=min(abs(rst-cnt),res)
print(res)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
s = []
s.append(A[0])
for i in range(1, N):
  s.append(s[i - 1] + A[i])
sum = s[-1]
d = float('inf')
for i in range(N - 1):
  d = min(d, abs((sum - s[i]) - s[i]))
print(d)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    n = int(input())
    a = list(map(int, input().split()))

    total = sum(a)
    count = 0
    length = 0
    while True:
        length += a[count]
        if length >= total // 2:
            break
        count += 1

    ans = abs(total - length * 2)
    if abs(total - (length - a[count]) * 2) < ans:
        ans = abs(total - (length - a[count]) * 2)

    print(ans)

Submission status: Accepted

Solution code:
def main():
  from builtins import abs
  N = int(input())
  A = list(map(int, input().split()))

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

  l = sum(A)
  print(min(abs(p + p - l) for p in a))
main()

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
x=sum(a)
S=0
ans=2020202022
for i in range(n):
  S+=a[i]
  if abs((x-S)-S) < ans:
    ans=abs((x-S)-S)
print(ans)

Submission status: Accepted

Solution code:
import math

n = int(input())

a = [int(x) for x in input().split()]

res = 0

for x in a :
    res += x

ans = 0

i = 0

while ans < res//2 :
    ans += a[i]
    i += 1

i -= 1

rmn = res - ans
print(min(ans - rmn, rmn + 2*a[i] - ans))

Submission status: Accepted

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

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

summ = sum(A)
average = summ / 2

sum_left = 0
j = 0
while sum_left < average:
    sum_left += A[j]
    j += 1
    
sum_right = sum(A[j:])

d = abs(sum_right - sum_left)

sum_l = sum_left - A[j-1]
sum_r = sum_right + A[j-1]

d2 = abs(sum_r - sum_l)

if d2 < d:
    print(d2)
else:
    print(d)

Submission status: Accepted

Solution code:

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

sums =sum(A)

l = 0
mlen = sums
for i in A:
    l += i
    r = sums - l
    #print("l="+str(l) + "r="+str(r))

    lr =l-r
    if lr <0:lr*=-1

    #print("mlen="+str(mlen)+"rl=" + str(lr))
    if mlen < lr:
        break
    else:
        mlen = r-l
        if mlen <0:mlen*=-1



print(mlen)

Submission status: Accepted

Solution code:
input()
xs=list(map(int,input().split()))
sx=sum(xs)
mmx,mnx=sx,0
rs = set()
for x in xs:
    mnx, mmx = mnx + x, mmx - x
    rs.add(abs(mmx - mnx))
print(min(rs))

Submission status: Accepted

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


ans = 2020202020**100
for i in range(n-1):
    before_sum = res[i]
    after_sum = res[n-1]-res[i]
    tmp = abs(before_sum-after_sum)
    ans = min(ans,tmp)
print(ans)

Submission status: Accepted

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

total = sum(B)
mid = total/2

behind = 0
for i in range(n):
    if behind + B[i] > mid:
        targetIndex = i
        break
    else:
        behind += B[i]

#targetIndexは配列のindex
right = mid - behind
left = behind + B[i] - mid

if right == left:
    print(int(right//0.5))
elif right > left:
    print(int(left//0.5))
elif right < left:
    print(int(right//0.5))

Submission status: Accepted

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

L = 0
R = 0
l = r = 0
while(l + r != N):
    if l==0 and r==0:
        L += A[l]
        l += 1
        R += A[-1 * (r + 1)]
        r += 1
    
    else:
        if L >= R:
            R += A[-1 * (r + 1)]
            r += 1

        else:
            L += A[l]
            l += 1

#print(L, R)

print(abs(L - R))

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
S=[0 for _ in range(n+1)]
for i in range(n):
  S[i+1]=S[i]+A[i]
print(min(map(lambda x:abs(S[n]-2*x),S)))

Submission status: Accepted

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

prefix = [0]

for i in a:
    prefix.append(prefix[-1] + i)

mini = float('inf')

for i in range(0, n):
    mini = min(abs(prefix[i] - (prefix[-1] - prefix[i])), mini)

print(mini)

Submission status: Accepted

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

PA = [0]
for i, a in enumerate(A):
    PA.append(a + PA[-1])

res = float("inf")
for i in range(1, len(PA) - 1):
    if PA[i] == PA[-1] - PA[i]:
        res = 0
    res = min(res, abs(PA[-1] - PA[i] - PA[i]))

print(res)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
L, R, sumL_R = 0, N - 1, A[0] - A[N - 1]

while R - L > 1:
    if sumL_R < 0:
        L += 1
        sumL_R += A[L]
    else:
        R -= 1
        sumL_R -= A[R]
print(abs(sumL_R))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
sm = sum(a)
tmp = a[0]
for i in range(1, n):
  if tmp > sm / 2:
    print(min(tmp * 2 - sm, sm - (tmp - a[i-1]) * 2))
    break
  tmp += a[i]
else:
  print(sm - (tmp - a[i]) * 2)

Submission status: Accepted

Solution code:
N=int(input())
import numpy as np
a=np.array(input().split(),dtype=int)
asum=np.cumsum(a)
half=asum.max()//2
isodd=(asum.max()%2==1)
import bisect
p=bisect.bisect_left(asum,half)
if abs(half-asum[p])>abs(half-asum[p-1]):
  p=p-1
longer=asum[p]
shorter=asum.max()-asum[p]
print(abs(longer-shorter))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N = int(readline())
A = np.array(read().split(),np.int64)

Acum = A.cumsum()

L = Acum[:-1]
R = Acum[-1] - L

answer = np.abs(L-R).min()
print(answer)

Submission status: Accepted

Solution code:
N=int(input())
A=[a for a in list(map(int,input().split()))]

SUM=sum(A)
MEAN=SUM / 2

idx=-1
pre=0
temp=0
while (temp <= SUM):
    if (MEAN <= temp):
        break
    idx+=1
    pre=temp
    temp+=A[idx]

print(int(min(abs(MEAN-pre),abs(MEAN-temp))/0.5))

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
S=[0] #累積和、S[i]はi番目の領域の始点
for i in range(N):
    S.append(S[-1]+A[i])
L=S[-1] #棒の長さの初期値

Sh=0 #中央に近い切れ込みの位置(領域の始点)
Dh=L #中央と切れ込みの差の最小値
for j in range(N+1):
    if Dh>abs(S[j]-L/2):
        Dh=abs(S[j]-L/2)
        Sh=j
if Dh==0:
    print(0)
else:
    print(int(Dh*2))

Submission status: Accepted

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

length = sum(a)
if length %2 ==0:
    check = 0
    half = length//2
    idx = 0
    for i in range(len(a)):
        check+=a[i]
        if check > half:
            idx = i
            break
    if check - half > half - (check-a[idx]):
        check -=a[idx]
    
    ans = abs((half-check)*2)
else:
    check = 0
    half = length//2
    idx = 0
    for i in range(len(a)):
        check+=a[i]
        if check > half:
            idx = i
            break
    check -=a[idx]
    afte = sum(a[idx:])
    ans = half-check+afte-half
    
    check +=a[idx]
    afte = sum(a[idx+1:])
    ans = min(ans,abs(check-half)+abs(afte-half))
    
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

INF = float("inf")
IINF = 10 ** 18
MOD = 998244353

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

    lengths = list(accumulate([0] + A))

    # length = sum(A)
    # half = len(A) // 2
    half = lengths[-1] // 2

    # print(lengths, half)

    if N == 2:
        print(abs(A[0] - A[1]))
    else:
        a1 = 0
        b1 = 0
        a2 = 0
        b2 = 0
        for i in range(1, N):
            if lengths[i] >= half:
                a1 = lengths[i]
                b1 = lengths[N] - lengths[i]
                a2 = lengths[i-1]
                b2 = lengths[N] - lengths[i-1]
                break

        # print(b2, a2)
        # print(b1, a1)
        print(min(abs(b2 - a2), abs(b1 - a1)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#import math

#input = raw_input
n = int(input())

As = list(map(int, input().split(" ")))
sA = sum(As)
#half_sA= sA // 2 if sA % 2 == 0 else (sA // 2) + 1
half_sA = sA // 2

cur_val = 0
for i, a in enumerate(As):
    cur_val += a
    if half_sA <= cur_val:
        over_i = i # made
        break

cur_val2 = cur_val
cur_val1 = cur_val - a

#print(cur_val1, half_sA, cur_val2)
diff1 = half_sA - cur_val1
diff2 = cur_val2 - half_sA

val_a = cur_val1
val_b = sA - val_a

val_c = cur_val2
val_d = sA - val_c

out = min( abs(val_b-val_a), abs(val_c-val_d) )

#if diff1 <= diff2:
#    #half_sA = int(math.floor(half_sA))
#    out = diff1
#else:
#    out = diff2
print(out)

Submission status: Accepted

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

half=sum(a)/2
sum_=0
min_=np.inf
for i in a:
    sum_+=i
    dist=abs(sum_-half)
    if dist<min_:
        min_=dist
ans=int(min_//0.5)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
L = 0
AS = []
for i in A:
  L += i
  AS.append(L)
R = L
for i in range(N-1):
  X = AS[i]
  Y = L - X
  R = min(R,abs(X - Y))
print(R)

Submission status: Accepted

Solution code:

import math

n = int(input())

a = [int(x) for x in input().split()]

res = 0

for x in a :
    res += x

ans = 0

i = 0

while ans < res//2 :
    ans += a[i]
    i += 1

i -= 1

rmn = res - ans
print(min(ans - rmn, rmn + 2*a[i] - ans))

Submission status: Accepted

Solution code:
N = int(input())
L = list(map(int, input().split()))
long = sum(L)
ans = long
sum1 = 0
sum2 = long
for i in range(N):
	sum1 += L[i]
	sum2 -= L[i]
	ans = min(abs(sum1-sum2), ans);
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
p=q=sum(a)
for i in range(0,n):
  p-=2*a[i]
  q=min(abs(p),q)
print(q)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
l = sum(a)
b = list()
t = 0
ans = 10**10
for i in a:
    t += i
    b.append(t)
for j in b:
    x = abs(l-(2*j))
    if x < ans:
        ans = x

print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl

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

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

half = a[-1] / 2
index = bl(a, half)

print(int(min(half - a[index - 1], a[index] - half) * 2))

Submission status: Accepted

Solution code:
import numpy as np

def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

n = int(input())
ali = list(map(int, input().split()))
naka = sum(ali)/2

zoukali = []
total = 0
for a in ali:
    total += a
    zoukali.append(total)

medi_ind = getNearestValue(zoukali, naka)

mae = sum(ali[:medi_ind+1])
ushiro = sum(ali[medi_ind+1:])


print(abs(mae-ushiro))

Submission status: Accepted

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

cumA = [0] * N
tmp = 0
for i in range(N):
    tmp += A[i]
    cumA[i] = tmp

from bisect import bisect_left

index = bisect_left(cumA, cumA[-1] / 2)

if index == 0:
    left = 0
else:
    left = cumA[index - 1]
right = cumA[index]
ans = min(right * 2 - cumA[-1], cumA[-1] - left * 2)


print(ans)

Submission status: Accepted

Solution code:
# DDCC B
si = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))
n = ni()
a = nl()
a_sum = []
s = sum(a)
ans = 10**10
ss = 0
for i in range(n):
    ss += a[i] 
    a_sum.append(ss)

for i in range(n):
    start = a_sum[i]
    end = s - start
    t = abs(start - end)
    ans = min(t,ans)

print(ans)

Submission status: Accepted

Solution code:
import math
import random
from operator import itemgetter
import re
import sys
from itertools import accumulate
from collections import defaultdict
from collections import deque
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
N = int(input())
A = [int(i) for i in input().split()]
B =sum(A)
count =0
num = 0
while count < B//2:
    count +=A[num]
    num += 1
count_alt = count - A[num-1]
print(min(abs(B-count*2),abs(B-count_alt*2)))

Submission status: Accepted

Solution code:
N, *A = map(int, open(0).read().split())
cnt = 0
tgt = sum(A) // 2
for i in range(N):
    cnt += A[i]
    if cnt >= tgt:
        break
        
a1 = abs(cnt - sum(A[i + 1:]))
a2 = abs((cnt - A[i]) - sum(A[i:]))
print(min(a1, a2))

Submission status: Accepted

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

total_length = sum(A)
left_length = 0
for i in range(len(A)):
    left_length += A[i]
    if left_length * 2 >= total_length:
        break
cost_from_left = left_length * 2 - total_length

right_length = 0
for j in reversed(range(len(A))):
    right_length += A[j]
    if right_length * 2 >= total_length:
        break
cost_from_right = right_length * 2 - total_length

print(min(cost_from_left, cost_from_right))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
S = sum(A)
m = S
s = 0
a = 10**100
for i in range(N):
    m = m - A[i]
    s += A[i]
    if s > m:
        break
    a = m - s
b = s - m
ans = min(a,b)
print(ans)

Submission status: Accepted

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

left_side = 0
right_side = 0
ans = 1e12
# 両サイドの累積和が必要
left_wa = [0, A[0]]
right_wa = [A[-1]]

for i in range(1, N):
    left_wa.append(left_wa[-1] + A[i])
for i in range(2, N+1):
    right_wa.append(right_wa[-1] + A[-i])
# right_wa.append(0)
# print(left_wa)
# print(right_wa)
#
# exit()
for i in range(1, N):
    left_side = left_wa[i]
    right_side = right_wa[-(i+1)]
    # print(left_side, right_side)
    ans = min(ans, abs(left_side-right_side))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
all_val = sum(A)
left = all_val // 2
right = (all_val+1) // 2
sub_sum = 0
for val in A:
    old = sub_sum
    sub_sum += val
    if sub_sum >= left:
        ans = 2 * min(abs(sub_sum - left),abs(left - old) , abs(sub_sum - right), abs(right - old))
        if ans % 2 != all_val % 2:
                ans += 1
        print(ans)
        break

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
cnt = 0
sum = 0
l = []
for i in a:
    sum += i
    l.append(sum)
l2 = [sum - x for x in l]
num = 0
loc = 0
for i in range(n):
    if i == 0:
        num = abs(l[i] - l2[i])
    else:
        if num > abs(l[i] - l2[i]):
            num = abs(l[i] - l2[i])
            loc = i


print(num)

Submission status: Accepted

Solution code:
import bisect
N=int(input())
As=list(map(int,input().split()))
S=sum(As)
l=[]
x=0
for i in range(N):
  x+=As[i]
  l.append(x)
ha=bisect.bisect_left(l,S/2)
sa1=abs(l[ha]-(S-l[ha]))
if ha>0:
  sa2=abs(l[ha-1]-(S-l[ha-1]))
else:
  sa2=sa1+1#便宜的に
print(min([sa1,sa2]))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
total=sum(a)
ideal=sum(a)/2
tmp=10**20
goukei=0
for i in range(n):
  goukei+=a[i]
  if tmp>abs(ideal-goukei):
    tmp=min(tmp,abs(ideal-goukei))
  else:
    break
print(int(tmp*2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
k = 0
f = 0
for i in range(n):
  k += a[i]
  if k >= s//2:
    f = i
    break
k = max(k, s - k)
k2 = k - a[f]
k2 = max(k2, s - k2)
print(min(2*k - s, 2*k2 - s))

Submission status: Accepted

Solution code:

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

total = sum(A)
half = total/2

aa = 0

for i in range(N):
    aa += A[i]
    if aa > half:
        check_num = i
        break

cost = 0 
OK = False
        
if sum(A[:check_num+1]) < sum(A[check_num:]):
    B = A[:check_num+1]
    C = A[check_num+1:]
else:
    B = A[:check_num]
    C = A[check_num:]


print(abs(sum(B)-sum(C)))

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split(' ')]
assert(len(A) == N)
s = sum(A)
Ls = 0
ans = -1

for i in range(N-1):
    Ls += A[i]
    Rs = s - Ls
    diff = abs(Rs - Ls)
    if ans == -1 or diff < ans:
        ans = diff
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
ans = 0
alen = len(A)

r = 0
l = 0
p1, p2 = 0, 1
for i in range(N):
    if p1 + p2 > alen:
        break
    if r >= l:
        l += A[p1]
        p1 += 1
    else:
        r += A[-p2]
        p2 += 1 
print(abs(l- r))

Submission status: Accepted

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

h = sum(a)/2
s = 0
s2 = 0
for i in a:
    s += i
    if s >= h:
        break
a.reverse()
for i in a:
    s2 += i
    if s2 >= h:
        break

s = min([s,s2])
print(2*s-sum(a))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
d = sum(a)
L = d/2
s = 0

for i in range(n):
    s += a[i]
    new_d = abs(L-s)
    if new_d < d:
        d = new_d
    else:
        break

print(int(2*d))

Submission status: Accepted

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

sum_a = 0
for a in a_list:
    sum_a += a

sub_sum_a = 0

for index in range(len(a_list)):
    middle_index_big = index
    sub_sum_a += a_list[index]
    if sub_sum_a >= (sum_a // 2):
        break

diff_big_index = abs(sub_sum_a - (sum_a - sub_sum_a))
sub_sum_a_small = sub_sum_a - a_list[middle_index_big]
diff_small_index = abs(sub_sum_a_small - (sum_a - sub_sum_a_small))

diff = min(diff_big_index, diff_small_index)
print(diff)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
a = list(map(int, input().split()))
ls = [0 for _ in range(len(a))]

tmp = 0
for i, v in enumerate(a):
    tmp += v
    ls[i] = tmp

length = ls[-1]
half = length // 2

cand = 2020202020
for l in ls[:-1]:
    cand = min(cand, abs(l * 2 - length))
print(cand)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
l = sum(a)
ls = 0
md = 100000000000
for aa in a:
    ls += aa
    md = min(md, abs(l-2*ls))

print(md)

Submission status: Accepted

Solution code:
"""
NTC here
"""
from sys import stdin, setrecursionlimit
setrecursionlimit(10**7)

def iin(): return int(stdin.readline())
 
 
def lin(): return list(map(int, stdin.readline().split()))

# range = xrange
# input = raw_input
def main():
    n=iin()
    a=lin()
    s2=sum(a)
    s1=0
    mn=abs(s2-s1)
    for i in range(n-1):
        s1+=a[i]
        s2-=a[i]
        mn=min(mn,abs(s1-s2))
    print(mn)

"""
1 2 5 8 15 20 23 11 45
"""
        


    
    
            



    
                











main()

Submission status: Accepted

Solution code:
N = int(input())
import numpy as np
A = np.array(list(map(int,input().split())))
cumsum = np.cumsum(A)
# ans = 10**9+7
ans = float('inf')
for i in range(N-1):
    if abs(cumsum[i] - (cumsum[-1] - cumsum[i])) < ans:
        ans = abs(cumsum[i] - (cumsum[-1] - cumsum[i]))
print(ans)       
# for i in range(N):
#     l = sum(A[:i])
#     #print(l)
#     r = sum(A[i:])
#     #print(r)
#     diff = abs(l-r)
#     if diff < ans:
#         ans = diff
# print(ans)

Submission status: Accepted

Solution code:
def MAP(): return list(map(int,input().split()))
def INT(): return int(input())
def FLOAT(): return float(input())
MOD = 10**9+7


n = INT()
l = MAP()

s = sum(l)
tmp=0
for i in range(n):
    tmp+=l[i]
    if tmp >= s/2:
        p1 = tmp - (s/2)
        idx1 = i
        break

tmp=0
for i in range(n-1,-1,-1):
    tmp+=l[i]
    if tmp >= s/2:
        p2 = tmp - (s/2)
        idx2 = i
        break

if p1 <= p2:
    left = sum(l[:idx1+1])
    right = sum(l[idx1+1:])
else:
    left = sum(l[:idx2])
    right = sum(l[idx2:])
print(abs(right-left))

Submission status: Accepted

Solution code:
def answer():
    N = int(input())
    As = list(map(int, input().split()))

    total = sum(As)
    half = total//2

    sum_left = 0
    sum_left2 = 0
    idx = 0

    for i, l in enumerate(As[:-1]):
        sum_left += l
        if sum_left >= half:
            idx = i
            sum_left2 = sum_left - l
            break

    sum_right = sum(As[idx+1:])
    sum_right2 = sum(As[idx:])

    ans1 = abs(sum_right - sum_left)
    ans2 = abs(sum_right2 - sum_left2)

    print(min(ans1, ans2))


if __name__ == '__main__':
    answer()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N = inputInt()
	A = inputList()

	to = 0
	for i in A:
		to += i

	to = to // 2
	manaka = 0
	tmp = 0
	for i,val in enumerate(A):
		tmp += val
		if tmp >= to:
			manaka = i
			break

	#print(to)
	#print(manaka)

	to1 = 0
	to11 = 0
	to2 = 0
	to22 = 0

	to111 = 0
	to222 = 0

	for i,val in enumerate(A):
		if i >= manaka+1:
			to2 += val
		else:
			to1 += val

		if i >= manaka-1:
			to22 += val
		else:
			to11 += val

		if i >= manaka:
			to222 += val
		else:
			to111 += val

	ans = min(abs(to1-to2),abs(to11-to22),abs(to111-to222))
	print(ans)


if __name__ == "__main__":
	main()

Submission status: Accepted

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

def readInts():
  return [int(s) for s in input().split(" ")]

def solve(N, A):
  s = sum(A)

  sp = 0
  last = A[0]
  for a in A:
    sp += a
    if sp >= s / 2:
      last = a
      break

  half = sp
  if sp - (s / 2) > abs(sp - last - (s / 2)):
    half = sp - last

  return abs(2 * half - s)

def main():
  N = readInts()
  A = readInts()

  print(solve(N, A))

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
from itertools import accumulate
n = int(input())
a = [int(i) for i in input().split()]
aa = list(accumulate(a))
mind = aa[-1]
for ai in aa:
  d = abs(aa[-1] - ai - ai)
  if d < mind:
    mind = d
  else:
    break
print(mind)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
s0 = sum(a)
s = s0//2 + 1 #半分の長さ
y = 0
x = 0
for i in range(n):
    if x >= s:
        y = i-1
        break
    else:
        x += a[i]
a11 = a[:y]
a12 = a[y:]
a21 = a[:y+1]
a22 = a[y+1:]
a11s = sum(a11)
a12s = sum(a12)
a21s = sum(a21)
a22s = sum(a22)
ans = min(abs(a11s-a12s), abs(a21s-a22s))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(_)for _ in input().split()]
sumA = sum(A)
halfsumA = sumA / 2
pos = 0
for n, a in enumerate(A):
    pos += a
    if pos > halfsumA:
        l = pos - a
        r = pos
        # 小さい方が差が小さい
        if abs(l - halfsumA) < abs(r - halfsumA):
            ans = abs((sumA - l) - l)
        else:
            ans = abs((sumA - r) - r)

        break

print(ans)

Submission status: Accepted

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

mean_a = sum(a)/2

mean_a_disc = 0
ans = 1000000
candidate = 0
#print(mean_a)
for i in range(N):
    if mean_a_disc + a[i] < mean_a:
        mean_a_disc += a[i]
    elif mean_a_disc + a[i] > mean_a:
        candidate = min(mean_a_disc + a[i] -mean_a,mean_a- mean_a_disc)
        break
    else:
        ans = 0
        break
if candidate > 0:
    ans = int(candidate * 2)

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
m=sum(a)
k=0
l=0
for i in range(n):
    k+=a[i]
    if k>m//2:
        l=i
        break
if n==2:
    print(abs(a[1]-a[0]))
else:
    print(min(abs(k-(m-k)),abs(k-a[i]-(m-(k-a[i])))))

Submission status: Accepted

Solution code:
n = int(input())
list = [int(i) for i in input().split()]

len = sum(list)
nlen = 0
d = []
for i in list:
    nlen += i
    d.append(abs(nlen - (len - nlen)))

print(min(d))

Submission status: Accepted

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

sum_left, sum_right = 0, sum(A)
min_diff = sum_right

for i in range(N):
    sum_left += A[i]
    sum_right -= A[i]
    #print(sum_left, sum_right)
    if min_diff < abs(sum_right - sum_left):
        break
    min_diff = abs(sum_right - sum_left)
print(min_diff)

Submission status: Accepted

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


def main():
    N = int(input())
    A = [int(x) for x in input().split()]

    total = sum(A)
    right = [0] * N
    left = [0] * N

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

    right[N - 1] = A[N - 1]
    for i in range(N - 1, 0, -1):
        right[i - 1] += A[i - 1] + right[i]
    
    mi = float("inf")
    for i in range(N - 1):
        mi = min(mi, abs(left[i] - right[i + 1]))
    
    print(mi)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
stdin = sys.stdin
mod = 10**9 + 7

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
sa = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]

n = ni()
a = na()
asum = sum(a)
s1 = 0
for ai in a:
    s0 = s1
    s1 += ai
    if s1 >= asum//2:
        print(min(asum-2*s0, 2*s1 - asum))

        exit()

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
s=sum(a)
l=[0]*n
l[0]=a[0]
for i in range(1,n):
  l[i]=l[i-1]+a[i]
import bisect as bi
x=bi.bisect_left(l,s/2)
if l[x]==s/2:
  print(0)
else:
  print(min(s-l[x-1]*2,l[x]*2-s))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = sum(a)
al = ans
mod = 0
for i in range(n):
  if mod + a[i] == al - a[i]:
    ans = 0
    break
  elif ans > abs(mod - al + 2*a[i]):
    ans = abs(mod - al + 2*a[i])
    mod += a[i]
    al -= a[i]
  else:
    mod += a[i]
    al -= a[i]
print(ans)

Submission status: Accepted

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

accumulated_sums = []
tmp = 0
for a in A:
    tmp += a
    accumulated_sums.append(tmp)

min_cost = 2020202020
for ac_s in accumulated_sums:
    cur_cost = abs(accumulated_sums[-1] - 2 * ac_s)
    min_cost = min(min_cost, cur_cost)

print(min_cost)

Submission status: Accepted

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

L = sum(A)

sum_1 = 0

for i in range(N):
    sum_1 += A[i]
    if sum_1 >= L / 2:
        break

sum_2 = 0

for i in reversed(range(N)):
    sum_2 += A[i]
    if sum_2 >= L / 2:
        break

print(min(2 * sum_1 - L, 2 * sum_2 - L))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
sum_a = sum(a)
total = 0
min_diff = 10**10
min_idx = 0
total_tmp = 0
for i in range(n):
    total += a[i]
    diff = abs(total - sum_a/2)
    if diff < min_diff:
        min_diff = diff
        min_idx = i
        total_tmp = total

print(abs(total_tmp - sum(a[min_idx+1:])))

Submission status: Accepted

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

bar = [0]
bar_tmp = 0
for Ai in A:
    bar_tmp += Ai
    bar.append(bar_tmp)

A_sum = sum(A)
targ = A_sum / 2

for i_r in range(N):
    if bar[i_r] > targ: break
i_l = i_r - 1

pen_l = abs(A_sum - 2 * bar[i_l])
pen_r = abs(2 * bar[i_r] - A_sum)

print(min(pen_l, pen_r))