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 bisect
def double(n):
    return n*2

N = int(input())
A = list(map(int,input().split()))
B = list(map(double,A))
# print(A) 
# print(B) 
sum=0
rsum=[]
tocutsum=0
rsumcut=[] 
for x in B:
    sum = sum + x
    tocut= max(0,x-2)
    rsum.append(sum)
    tocutsum = tocutsum + tocut 
    rsumcut.append(tocutsum)
# print(sum)
# print(rsum)
# print("rsumcut",rsumcut)
middle= sum // 2;
# print("Middle",middle)
br = bisect.bisect_right(rsum,middle)
# print(br)


xleft = middle - rsum[br-1]
xright = rsum[br] - middle 

print(min(xleft,xright))
# print("Ans",min(xleft,xright))
# print("Costleft,rigth",costleft,costright)

Submission status: Accepted

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

s2=s/2
cnt=0
for i,k in zip(a,range(len(a))):
    cnt+=i
    if cnt>s/2:
        break
my2=True
if cnt-a[k]<s-cnt:#小さいほう
    res=0
    my=True
    b=cnt
else:
    res=0
    my=True
    b=s-cnt+a[k]

c=s-b
if s-(c*2)==b-c:
    print(int(b-c))
else:
    print(0)

Submission status: Accepted

Solution code:
import math

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

sum = 0
mArr = []

for n in Arr:
    m = n
    sum += m
    mArr.append(m)

half = sum / 2

l = 0
last = 0

for n in mArr:
    l += n
    if l >= half:
        last = n
        break

if l == half:
    print(0)
else:
    d = l - half
    if d > (last / 2):
        if l == mArr[0]:
            left = l
            right = sum - left
            print(left - right)
        else:
            left = l - last
            right = sum - left
            print(right - left)
    else:
        if l == sum:
            left = l - last
            right = sum - left
            print(right - left)
        else:
            left = l
            right = sum - left
            print(left - right)

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())
a = tuple(map(int, input().split()))
b = np.full(n, np.inf)
f = 0
s = sum(a)
for i in range(n-1):
    f += a[i]
    s -= a[i]
    x = abs(f - s)
    b[i] = x
print(int(min(b)))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A_1 = sum(A)//2
A_tmp = 0
for i in range(N):
    A_tmp += A[i]
    if A_tmp < A_1:
        pass
    elif A_tmp == A_1:
        print(0)
        exit()
    else:
        A_tmp2 = A_tmp-A[i]
        ans1 = abs(A_tmp - (sum(A) - A_tmp))
        ans2 = abs(A_tmp2 - (sum(A) - A_tmp2))
        print(min(ans1,ans2))
        exit()

Submission status: Accepted

Solution code:
N = int(input())
li = list(map(int,input().split()))
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
for i in range(N):
    sum1 += li[i]
    sum4 += li[i]
sum1 //= 2
for i in range(N):
    sum2 += li[i]
    if sum2 >= sum1:
        ans = min((sum2 - sum1 + abs(sum4-sum2-sum1)),((sum1-sum3)+sum4-sum3-sum1))
        break
    sum3 += li[i]
print(ans)

Submission status: Accepted

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

c= 0
d=0
s=sum(a)

for i in range(0,N):
  if c<s/2:
    c+=a[i]
  else:
    break

a.reverse()
for i in range(0,N):
  if d<s/2:
    d+=a[i]
  else:
    break

if c<d:
  print(c*2-s)
else:
  print(d*2-s)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

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

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    


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

    
def main(): 
    S = [0]*N
    S[0] = A[0]
    for n in range(1,N):
        S[n] += S[n-1]+A[n]
    S2 = S[n]/2
    li = bisect.bisect_left(S, S2)

    if S2 == S[li]:
        return print(0)
    if abs(S2 - S[li-1]) < abs(S[li]-S2):
        rod1 = S[li-1]
    else:
        rod1 = S[li]
    rod2 = S[n]-rod1
    res = abs(rod1-rod2)

        
    print(int(res))
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()



"""
N, X = map(int, input().split())

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

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())


all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
# itemgetterには何番目の配列をキーにしたいか渡します
A, B, totAB = zip(*ABT)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# Submit as pypy2


from __future__ import print_function, division, unicode_literals

__metaclass__ = type

try:
    input = raw_input
    range = xrange
except NameError:
    pass


import sys


# Test code requires python3
# from hypothesis import given
# from hypothesis import strategies as st
#
#
# def debug(*args, **kwargs):
#     print(*args, *('{}={}'.format(k, v) for k, v in kwargs.items()),
#           sep='; ', file=sys.stderr)


def main():
    N = int(input())
    A = [int(x) for x in input().split()]
    tot = sum(A)
    i = 0
    psum = 0
    while i < N and 2*psum < tot:
        psum += A[i]
        i += 1
    print(min(2*psum - tot, tot - 2*(psum - A[i - 1])))


if __name__ == "__main__":
    main()

Submission status: Accepted

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

#print(N)
#print(A)

#合計を求める
sum = 0
for i in range(N):
  sum += A[i]

#半分を超える要素pを求める
half1st = 0
half1st2 = 0
half2nd = 0
i = 0
temp = 0
flag = 0
for i in range(N):
  if( half1st <= (int)(sum/2) ):
    half1st += A[i]
    temp += 1
  else:
    half2nd += A[i]
thre = temp-1
half1st2 = half1st - A[thre]
half2nd1 = half2nd + A[thre]
#その要素pを減らす/増やす，あるいは要素p-1を減らす/増やす，どちらが早いか判定
P = abs(half1st2 - half1st)
Q = abs(half1st - half2nd)
R = abs(half1st2 - half2nd1)
#ちょうど半分
if (half1st2 == half2nd1):
  print(0)
#P > Q
elif ( P < Q and P < R):
  #print('ans = '+str(Q))
  print(P)
elif (Q < R):
  #print('ans = '+str(P))
  print(Q)
else:
  print(R)


#A[i-1] が要素p 
#要素のインクリ数，でクリ数を計算
#出力
#print(sum)
#print(A[thre])
#print('h1 = '+str(half1st))
#print('h2 = '+str(half2nd))

#print('h12 = '+str(half1st2))
#print('h21 = '+str(half2nd1))
#print(R)

Submission status: Accepted

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

def h(n,A):
    res = float('inf')
    f = []
    b = []
    t = 0
    for i in range(len(A)):
        t+=A[i]
        f.append(t)
    t = 0
    for i in range(len(A)-1,-1,-1):
        t += A[i]
        b.append(t)
    b.reverse()
    for i in range(len(A)-1):
        temp1 = f[i]
        temp2 = b[i+1]
        res = min(res,abs(temp1-temp2))
        
    #print(f)
    #print(b)
    print(res)
    
    
    
h(n,A)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    start_len = sum(A)
    mokuteki = start_len/2
    temp = 0
    for n in range(N):
        temp += A[n]
        if(temp >= mokuteki):
            break
    n1 = n-1
    kouho1 = temp - A[n]
    n2 = n
    kouho2 = temp
    kouho1_ = start_len - kouho1*2
    kouho2_ = kouho2*2 - start_len
    res = min(kouho1_, kouho2_)
    print(res)
            

if __name__ == "__main__":
    main()

Submission status: Accepted

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

def func(A):
    A_inf = 0
    A_sup = 0
    N_inf = 0
    N_sup = 0
    L = sum(A)

    for a in A:
        if A_inf <= L/2 - a:
            A_inf += a
            A_sup += a
            N_inf += 1
            N_sup += 1
            continue
        else:
            if A_sup <= L/2 and A_sup + a > L/2:
                A_sup += a
                N_sup += 1
            break

    if A_inf == A_sup:
        return 0

    A_mid = A_sup - A_inf
    A_left = L/2 - A_inf
    A_right = A_sup - L/2
    A_lrmin = min(A_left, A_right)
    if A_mid-1 >= 2*A_lrmin:
        return int(2*A_lrmin)
    else:
        return int(A_mid)

print(func(A))

Submission status: Accepted

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

sep = N//2
for i in range(N):
  if sum(A[:sep]) >= sum(A[sep:]):
    sep -= N//((i+2)**2)
  else:
    sep += N//((i+2)**2)
  if N//((i+2)**2) == 1:
    break
#print(sep)


a = abs(sum(A[:sep])-sum(A[sep:]))
b = abs(sum(A[:sep+1])-sum(A[sep+1:]))
c = abs(sum(A[:sep-1])-sum(A[sep-1:]))
d = abs(sum(A[:sep+2])-sum(A[sep+2:]))
e = abs(sum(A[:sep-2])-sum(A[sep-2:]))
print(min(a,b,c,d,e))

Submission status: Accepted

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

for a in A:
    sum += a
check = sum / 2

for b in A:
    sum1 += b
    if check < sum1:
        sum2 = sum1 - b
        break
sum1_2 = sum - sum2
sum2_2 = sum - sum1
if (sum1_2 - sum2) > (sum1 - sum2_2):
    print(sum1 - sum2_2)
else:
    print(sum1_2 - sum2)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)


def main():
    N = int(input())
    A = list(map(int, input().split()))
    s = sum(A)
    a = 0
    b = 0
    tmp = []
    for i in range(len(A)):
        if s % 2 != 0:
            if a >= (s // 2) - 1 or i == N-1:
                b += A[i]
            else:
                a += A[i]
                tmp.append(A[i])
        else:
            if a >= (s // 2) or i == N-1:
                b += A[i]
            else:
                a += A[i]
                tmp.append(A[i])
    ans1 = abs(a-b)
    ans2 = abs((a-tmp[-1]) - (b+tmp[-1]))
    print(min(ans1, ans2))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
a=input().split()
a=[int(i) for i in a]
l=0
r=0
s=sum(a)/2
for i in range(n):
	l=a[i]+l
	if l>=s and abs(l-s)>=abs(l-s-a[i]):
		print(int(abs(l-s-a[i])*2))
		exit()
	elif l>=s and abs(l-s)<=abs(l-s-a[i]):
		print(int(abs(s-l)*2))
		exit()

Submission status: Accepted

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

def getNearestValue(list, num):
  idx = np.abs(np.asarray(list) - num).argmin()
  return list[idx]

a=(np.cumsum(A))
l=getNearestValue(a, sum(A)/2)

ans=abs(sum(A)-2*l)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
# A = input().split()
A = list(map(int, input().split()))
# f = open("tmp.text")
# A = list(map(int, f.read().split()))



# left = 0
# right = N - 1
# tmp = 10**9
# while True:
#     # print(left)
#     # print(right)
#     mid = (left + right) // 2
#     # print("mid: " + str(mid))
#     lnum = A[:mid+1]
#     rnum = A[mid+1:]
#     # print(lnum)
#     # print(rnum)
#     new = abs(sum(lnum) - sum(rnum))
#     if tmp == new:
#         break
#     if tmp > new:
#         tmp = new
#     if lnum > rnum:
#         right = mid

#     # print("tmp: "+str(tmp))
#     # input()
#     if left == right:
#         break

# print(tmp)



left = A[0]
right = A[-1]

front = 1
back = 1
for _ in range(N-2):
    if left > right:
        right += A[-1 - back]
        back += 1
    else:
        left += A[front]
        front += 1

print(abs(left-right))

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
n = int(input())
a = deque()
a = deque(map(int, input().split()))
asum = sum(a)
ah = asum / 2
it = a.popleft()
l1 = [it]
sl1 = it
sl2 = asum
dp = []
sdp = 0

for i in range(n - 1):
    it = a.popleft()
    dp = l1
    sdp = sl1
    l1.append(it)
    sl1 += it
    sl2 -= it
    if sl1 > ah:
        break
if (sl1 - ah) ** 2 + (asum - sl1 - ah) ** 2 > (sdp - ah) ** 2 + (asum - sdp - ah) ** 2:
    l1 = dp
    a.append(it)
    sl1 = sdp
    sl2 += it
print(int(abs(sl1 - ah) * 2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(int(x) for x in input().split(" "))
center = sum(a) / 2

sum = 0
diff = float('inf')
for x in a:
    if abs(sum + x - center) > diff:
        break
    sum += x
    diff = abs(sum - center)

print(int(diff * 2))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30

def main():
    n = int(input().strip())
    v = list(map(int, input().strip().split()))

    a = [0] * n
    b = [0] * n
    for i in range(n):
        if i == 0:
            a[i] = v[i]
            continue
        a[i] = a[i-1] + v[i]
    for i in reversed(range(n)):
        if i == n-1:
            b[i] = v[i]
            continue
        b[i] = b[i+1] + v[i]
    ans = INF
    for i in range(n-1):
        ans = min(ans, abs(a[i] - b[i+1]))
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

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

left = A[0]
left_count = 0
right = A[N - 1]
right_count = 0
for i in range(N - 2):
    if left <= right:
        left_count += 1
        left += A[left_count]
    else:
        right_count += 1
        right += A[N - right_count - 1]

print(abs(left- right))

Submission status: Accepted

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

s = 0
i = 0
while i < N:
    s += A[i]
    if A_sum - s < s:
        t = s
        u = s - A[i]
        break
    i += 1
      
print(min(t-A_sum+t, A_sum-u-u))

Submission status: Accepted

Solution code:
n=int(input())
li=list(map(int,input().split()))
a=0
for i in range(0,n):
  a=a+li[i]
total=0
k=0
while 2*total<=a:
  total=total+li[k]
  k=k+1
if 2*total==a:
  print(0)
else:
  if 2*total-a<=a-2*(total-li[k-1]):
    print(2*total-a)
  elif 2*total-a>a-2*(total-li[k-1]):
    print(a-2*(total-li[k-1]))

Submission status: Accepted

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


diff = 2020202020 * 200000 + 1
tot = sum(A)

temp1 = 0

for i in range(N):
    temp1 += A[i]
    # temp2 = A[i+1:]
    temp3 = abs(tot - 2 * temp1)
    if temp3 <= diff:
        # mid = i
        diff = temp3
    else:
        break

print(diff)

Submission status: Accepted

Solution code:
N = int(input())

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

sum_of_an = sum(An)

if sum_of_an % 2 == 0:
    half_of_an = sum_of_an / 2
    sum_left_len = 0
    for l in An:
        sum_left_len += l
        if sum_left_len == half_of_an:
            print(0)
            exit(0)
        elif sum_left_len > half_of_an:
            break
min_yen = None
left_len = 0
for (i, l) in zip(range(0, N), An):
    if i == N - 1:
        break

    left_len += l
    if min_yen is None:
        min_yen = abs(sum_of_an - left_len * 2)
    else:
        min_yen = min(min_yen, abs(sum_of_an - left_len * 2))

print(min_yen)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
S = sum(A)
b = 0
a = 0
c = 0
if N == 2:
    print(abs(A[0]-A[1]))
else:
    for i in range(len(A)):
        if S/2-0.5 > a:
            a += A[i]
        else:
            b = a + A[i]
            c = a - A[i-1]
            break
        if i == len(A)-1:
            b = a
            a = a-A[i]
        else:
            None
    print(min(abs(S - a*2), abs(S - b*2),abs(S-c*2)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
A_list = list(map(int, input().split()))
 
div_sum_A = sum(A_list) / 2
ans = 0
calculator = 0
for i in range(N):
    calculator += A_list[i]
    if calculator >= div_sum_A:
        if calculator == div_sum_A:
            ans = 0
            break
        elif A_list[i] > div_sum_A:
            ans = 2 * A_list[i] - calculator
            break
        else:
            cand_1 = calculator - (2 * div_sum_A - calculator)
            cand_2 = abs((calculator - A_list[i]) - (2 * div_sum_A - (calculator - A_list[i])))
            ans = min(cand_1, cand_2)
            break

print(int(ans))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
m = sum(A) // 2
n = 0
if N > 2:
  for i in range(N):
    if n < m:
      n += A[i]
    elif n >= m and i == N - 1:
      a = i
    elif n >= m and i != N - 1:
      a = i
      break
  if a == 0:
    print(abs(A[a]-sum(A[a:])))
  elif abs(sum(A[:a-1]) - sum(A[a-1:])) > abs(sum(A[:a]) - sum(A[a:])):
    print(abs(sum(A[:a]) - sum(A[a:])))
  else:
    print(abs(sum(A[: a - 1]) - sum(A[a - 1 :])))
else:
  print(abs(A[0]-A[1]))

Submission status: Accepted

Solution code:
n, *a = map(int, open(0).read().split())
l, r = a[0], sum(a[1::])
ans = abs(l-r)
for i in range(1, n):
    l += a[i]
    r -= a[i]
    ans = min(ans, abs(l-r))
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
a = inpl()
s = sum(a)
cnt = 0
res = INF
b = [0] * n
for i in range(n-1):
    a[i+1] = a[i+1] + a[i]
for i in range(n):
    res = min(res,abs(s-a[i]-a[i]))
print(res)

Submission status: Accepted

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

A_sum = sum(A)
A_sum_hulf = A_sum / 2

A_sum_rui = 0

for i in range(N):
    A_sum_rui += A[i]
    if A_sum_rui > A_sum / 2:
        if A_sum_rui - (A_sum / 2) < (A_sum / 2) -(A_sum_rui - A[i]):
            print(A_sum_rui - (sum(A) - A_sum_rui))
        else:
            print(sum(A) - 2 * (A_sum_rui - A[i]))
        break

Submission status: Accepted

Solution code:
import numpy as np
N=int(input())
A=list(map(int, input().split()))
A=np.array(A)
left=0 
right=N-1
while left<right:
  mid=(left+right)//2
  if A[:mid+1].sum()<A[mid+1:].sum():
    left=mid+1
  else:
    right=mid
if (abs(A[:left+1].sum()-A[left+1:].sum()))>(abs(A[:left].sum()-A[left:].sum())):
  print((abs(A[:left].sum()-A[left:].sum())))
else:
  print((abs(A[:left+1].sum()-A[left+1:].sum())))

Submission status: Accepted

Solution code:
import math
N = int(input())
li = list(map(int,input().split()))
#合計
leng=sum(li)
#tasizan
leng2=0
count=0

for i in range(N):
  if leng2<leng/2:
    leng2+=li[i]  
  
  if leng2==leng/2 and leng%2 ==0:  #OK
    print(count)
    break
    
  elif leng2>leng/2:
    if i>0:
      xx = abs(leng/2 - leng2)#leng2がより大きい
      xxx = abs(leng/2 - leng2 + li[i])
      if xx < xxx:#差分が小さいほうを採用
        count = xx/0.5
      else:
        count = xxx/0.5
    elif i==0:
      xx = abs(leng/2 - leng2)#leng2がより大きい
      count = xxx/0.5
    print(int(count))
    break

Submission status: Accepted

Solution code:
import math

n = int(input())
a = [int(i) for i in input().split(" ")]

sum_length = sum(a)
min_diff = 1e18
r = 0

for i in range(len(a)):
    r += a[i]
    l = sum_length - r
    if(abs(r - l) <= min_diff):
        min_diff = abs(r - l)
        
print(min_diff)

Submission status: Accepted

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

    sm = sum(A)
    agg = 0
    idx = 0
    mid = sm / 2
    shrink_cnt = sm - N
    while agg < mid and idx < N-1:
        
        agg += A[idx]
        idx += 1
    
    oneleft = agg
    oneright = sm - oneleft 
    twoleft = agg-A[idx-1]
    tworight = sm - twoleft
    ans = min(abs(oneleft-oneright), abs(twoleft-tworight))

    print(int(ans))

if __name__ == '__main__':
    solve()

Submission status: Accepted

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

s=sum(A)
left=0
right=n-1

while(left+1<right):
    if 2*sum(A[0:(left+right)//2])>s:
        right=(left+right)//2
    elif 2*sum(A[0:(left+right)//2])<s:
        left = (left+right)//2
    else:
        left=(left+right)//2
        right=(left+right)//2
        break

print(min(abs(s-2*sum(A[0:left+1])),abs(s-2*sum(A[0:left]))))

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect, insort_left, insort
from itertools import accumulate
INF = float("inf")
def solve():
    n = int(input())
    A = list(map(int, input().split()))
    sum_a = sum(A)
    X = list(accumulate(A))
    Y = list(accumulate(A[::-1]))
    Z = {sum_a // 2, (sum_a + 1) // 2}
    def f(z, B):
        ret = INF
        left = bisect_left(B, z)
        for a in [left, left + 1]:
            if a == n + 1:
                continue
            if a < n - 1:
                t = B[a]
                ret = min(ret, abs(t - (sum_a - t)))
            if a <= n:
                t = B[a - 1]
                ret = min(ret, abs(t - (sum_a - t)))
        return max(0, ret)
    ans = INF
    for z in Z:
        ans = min(ans, f(z, X), f(z, Y))
    print(ans)
solve()

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys
n=int(input())
A=list(map(int,input().split()))
S=sum(A)/2
B=list(accumulate(A))

for i in range(n):
    B[i]-=S
    if B[i]<0:
        continue
    elif B[i]==0:
        print(0)
        sys.exit()
    else:
        if i==0:
            print(A[0]-A[1:])
        elif i>0 and i<n-1:
            a=abs(sum(A[:i])-sum(A[i:]))
            b=abs(sum(A[:i+1])-sum(A[i+1:]))
            print(min(a,b))
        else:
            print(A[n-1]-sum(A[:n-1]))
        sys.exit()

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
p=sum(A)//2
S=0
cost=0
i=0
while S<p:
  S=S+A[i]
  i=i+1
#print(i,S,A[i-1])
if S==p:
  cost=0
else:
  if sum(A[0:i])>sum(A[i-1:N]):
    cost=sum(A[i-1:N])-sum(A[0:i-1])
  else:
    cost=sum(A[0:i])-sum(A[i:N])
print(cost)

Submission status: Accepted

Solution code:
from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math

N = int(stdin.readline().rstrip())
d = [int(s) for s in stdin.readline().rstrip().split()]
count = 0
sumF = d[0]
sumB = d[len(d) - 1]
count = 0
countF = 0
countB = len(d) - 1
while count < len(d):
    if sumF < sumB:
        sumF += d[countF+1]
        countF += 1
        count += 1
    elif sumB < sumF:
        sumB += d[countB-1]
        countB -= 1
        count += 1
    else:
        sumF += d[countF+1]
        countF += 1
        sumB += d[countB-1]
        countB -= 1
        count += 2
print(abs(sum(d[0:countF])-sum(d[countF:len(d)])))

Submission status: Accepted

Solution code:
N=int(input())
A = list(map(int,input().split()))
A2 = [ A[i]*2 for i in range(N) ]
asum = sum(A2)
tgt = asum//2
tmpa = 0
ans = 0
for i in range(N):
  tmpa += A2[i]
  if tmpa >= tgt:
    if i == 0:
      ans = tmpa - tgt
    else:
      ans = min(tmpa-tgt, tgt-(tmpa-A2[i]))
#      print(tgt, tmpa,A2[i],ans)
    break
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
sumFrontHalf=0
halfIndex=0
sumA=sum(a)
for i in range(n):
  sumFrontHalf+=a[i]
  if sumFrontHalf>=sumA/2:
    halfIndex=i
    break
sumBackHalf=sumA-sumFrontHalf+a[halfIndex]
if sumFrontHalf<sumBackHalf:
  print(sumFrontHalf-sumBackHalf+a[halfIndex])
else:
  print(sumBackHalf-sumFrontHalf+a[halfIndex])

Submission status: Accepted

Solution code:
# coding: utf-8
from math import ceil
N = int(input())
A = list(map(int, input().split()))
total = sum(A)
half = ceil(sum(A) / 2)
tmp = 0
diff = sum(A)
for i in range(N):
    tmp += A[i]
    total -= A[i]
    if total == tmp:
        print(0)
        exit()
    diff = min(diff, abs(total - tmp))
print(diff)

Submission status: Accepted

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

left_length = sum(A[:int(N/2)])
right_length = sum(A[int(N/2):])
if left_length > right_length :
  price = left_length - right_length
  for i in range(int(N/2)-1,0,-1) :
    var = abs(sum(A[:i]) - sum(A[i:]))
    if price > var :
      price = var
    else :
      break
else :
  price = right_length - left_length
  for i in range(int(N/2)+1,N) :
    var = abs(sum(A[i:]) - sum(A[:i]))
    if price > var :
      price = var
    else :
      break

print(price)

Submission status: Accepted

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

all_length = sum(A)
sum_length = 0
num = 0

for i in range(N):
    sum_length += A[i]
    if sum_length >= all_length // 2:
        num = i + 1
        break

half_l1 = [A[i] for i in range(num-1)]
sum_half_l1 = sum(half_l1)
rest1 = all_length - sum_half_l1

half_l2 = [A[i] for i in range(num)]
sum_half_l2 = sum(half_l2)
rest2 = all_length - sum_half_l2

need = min(abs(sum_half_l1 - rest1), abs(sum_half_l2 - rest2))
print(need)

Submission status: Accepted

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

len=sum(a)
len_l=0
for i in range(n):
    if len/2>len_l:
        len_l+=a[i]
    else:
        center=i-1
        break
else:
    center=n-1
    
len_r=len-len_l
len_l-=a[center]
#半分との差
d=len/2-max(len_r,len_l)

print(int(d*2))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import sys
f = sys.stdin
n = int(f.readline())
a = list(map(int, f.readline().split(' ')))

prefix = [0] * (n+1)
for i in range(1, n+1):
    prefix[i] = prefix[i-1] + a[i-1]

def sum_fragment(p, q, prefix):
    return prefix[q+1] - prefix[p]

l = prefix[n]
diff = l
k = 0
for i in range(1, n):
    l1 = prefix[i]
    if l == 2*l1:
        k = i
        diff = 0
        break
    if l < 2*l1:
        if diff > (2*l1 - l):
            k = i
            diff = 2*l1 - l
        break
    diff = l - 2*l1
    k = i

print(diff)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import itertools
import sys


class CumulativeSum(object):

    def __init__(self, sequence):
        self.cumulative_sum = [0]
        self.cumulative_sum.extend(itertools.accumulate(sequence))

    def partial_sum(self, first, last):
        return self.cumulative_sum[last + 1] - self.cumulative_sum[first]


def div_ceil(a, b):
    return (a + b - 1) // b


def solve(n, xs):
    cs = CumulativeSum(xs)
    res = sys.maxsize // 10
    for p in range(n):
        left_sum = cs.partial_sum(0, p - 1)
        right_sum = cs.partial_sum(p, n - 1)
        res = min(res, abs(right_sum - left_sum))
    return res


def main():
    n = int(input())
    xs = [int(x) for x in input().split()]
    res = solve(n, xs)
    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

s = sum(A)

oe = s % 2
h = s // 2

p = 0
p0 = None
p1 = None
for i in A:
    p += i
    if p == h:
        if oe == 0:
            print(0)
            exit()
        print(1)
        exit()
    if p > h:
        p1 = p
        break
    p0 = p

if oe == 1:
    h += 1

p = p0 if p1 == s or abs(p0 - h) < abs(p1 - h) else p1

print(abs(p*2 - s))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
 
N=int(input())
A = np.array([int(x) for x in input().split()])
if N==2:
  print(abs(A[0]-A[1]))
else:
  B = np.concatenate([[0],A.cumsum()])
  H = np.searchsorted(B,sum(A)//2)
  result=float('inf')
  for i in range(min(5,len(A)//2)):
    result=min(result,abs(sum(A[:H+i])-sum(A[H+i:])),abs(sum(A[:H-i])-sum(A[H-i:])))

  print(result)