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
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))  # 累積和を格納したリスト作成


    ans=10**18
    for i in range(1, N):
        ans = min(abs(B[i]-(zenbu-B[i])),ans)
    print(ans)

resolve()

Submission status: Accepted

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

def main():
    n = int(input())

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

    total = sum(stick)
    mid = total // 2

    cum = 0
    midi = 0
    for i, block in enumerate(stick):
        cum += block
        if cum >= mid:
            midi = i
            break

    l1 = cum
    r1 = total - l1
    diff1 = abs(l1 - r1)
    
    l2 = l1 - stick[midi]
    r2 = r1 + stick[midi]
    diff2 = abs(l2 - r2)
    
    print(min(diff1, diff2))

main()

Submission status: Accepted

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

def main():
    n = int(input())

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

    total = sum(stick)
    mid = total // 2

    cum = 0
    midi = 0
    for i, block in enumerate(stick):
        cum += block
        if cum >= mid:
            midi = i
            break

    l1 = sum(stick[:midi])
    r1 = sum(stick[midi:])
    diff1 = abs(l1 - r1)
    
    l2 = l1 + stick[midi]
    r2 = r1 - stick[midi]
    diff2 = abs(l2 - r2)
    
    print(min(diff1, diff2))

main()

Submission status: Accepted

Solution code:
n = int(input())

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

total = sum(stick)
mid = total // 2

cum = 0
midi = 0
for i, block in enumerate(stick):
    cum += block
    if cum >= mid:
        midi = i
        break

l1 = sum(stick[:midi])
r1 = sum(stick[midi:])
diff1 = abs(l1 - r1)
 
l2 = l1 + stick[midi]
r2 = r1 - stick[midi]
diff2 = abs(l2 - r2)
 
print(min(diff1, diff2))

Submission status: Accepted

Solution code:
n = int(input())

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

total = sum(stick)
mid = total // 2

cum = 0
midi = 0
for i, block in enumerate(stick):
    cum += block
    if cum >= mid:
        midi = i
        break

l1 = stick[:midi]
r1 = stick[midi:]
diff1 = abs(sum(l1) - sum(r1))
 
l2 = stick[:midi+1]
r2 = stick[midi+1:]
diff2 = abs(sum(l2) - sum(r2))
 
print(min(diff1, diff2))

Submission status: Accepted

Solution code:
import sys
import numpy as np

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = list(map(int, input().split()))
    cumsum = np.cumsum(A)
    half = sum(A) // 2

    ans = INF
    for i in range(N - 1):
        left = cumsum[i]
        right = cumsum[-1] - cumsum[i]
        cost = abs(half - left) + abs(right - half)
        if cost < ans:
            ans = cost

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
L = sum(a)
l = 0
i = 0
while l < L / 2:
    l += a[i]
    i += 1
print(min(abs(sum(a[:i - 1]) - sum(a[i - 1:])), abs(sum(a[:i]) - sum(a[i:]))))

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
s = [0]

for i in A:
    s.append(i+s[-1])

M = 10000000000

for i in range(1,len(s)-1):
    dif = abs((s[-1]-s[i]) - s[i])
    M = min(M,dif)

print(M)

Submission status: Accepted

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

tot = sum(arr)

temp = 0
ans = 1e18
for i in range(n):
    temp += arr[i]
    rest = tot-temp
    cost = abs(rest-temp)
    if cost < ans:
        ans = cost

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
barlen = 0
for x in a:
  barlen += x
halflen = barlen/2
curbarlen = 0
minhalfdis = barlen
for i in range(n):
  curbarlen += a[i]
  minhalfdis = min(minhalfdis,abs(halflen-curbarlen))
print(int(minhalfdis*2))

Submission status: Accepted

Solution code:
A=int(input())
l=list(map(int,input().split()))
right=l[0]
left=sum(l[1:])
ans=left-right
for i in range(A-2):
    right+=l[i+1]
    left-=l[i+1]
    ans=min(ans,abs(right-left))
print(ans)

Submission status: Accepted

Solution code:
'''
参考
https://qiita.com/c-yan/items/f7c99c8f8ec418a58c42

棒の全長をL、切断箇所をCとすると、かかるコストは|2C-L|となる
（左端から切断箇所までの長さを2倍し、元の棒の全長を引いたものの絶対値）
∵
・CがL/2よりも左にある場合（=棒の左端からCまでの長さのほうが短い）
⇒Cよりも左側に2C-L足すか、右側を2C-L減らす
・CがL/2よりも右にある場合（=棒の左端からCまでの長さのほうが長い）
⇒Cよりも左側を2C-L減らすか、右側に2C-L足す

与えられたリストAのうち、どの地点をCとするかは
リストAの先頭の要素からN-1個の要素をそれぞれ調べ、
先頭要素から現在の要素までの合計（累積和）を格納するリストを別途作成、
そのリストに対して|2C-L|が最小となるケースを調べる
'''
N = int(input())
A = list(map(int, input().split()))
L = sum(A)
#tmp = []
tmp = A[:-1]

for i in range(1, N-1):
#    tmp.append(sum(A[:i+1]))       # 実行時間超過してしまうためコメントアウト
    tmp[i] += tmp[i-1]

cost = min(abs(c*2-L) for c in tmp)
print(cost)

Submission status: Accepted

Solution code:
def main():
    N=int(input())
    A=[int(_) for _ in input().split()]
    left=0
    right=sum(A)
    ans=right
    for i in range(N):
        left+=A[i]
        right-=A[i]
        ans = min(ans, abs(left-right))
    print(ans)

main()

Submission status: Accepted

Solution code:
n, *a = map(int, open(0).read().split())
half_a = sum(a)//2
tmp = 0
for i in range(n):
    if tmp + a[i] >= half_a:
        ans1 = abs(tmp + a[i] - half_a) + abs(sum(a[i+1:]) - half_a)
        ans2 = abs(tmp - half_a) + abs(sum(a[i:]) - half_a)
        ans = min(ans1, ans2)
        break
    tmp += a[i]
print(ans)

Submission status: Accepted

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

S = sum(la)
lsum = 0
i = 0
while lsum < S/2:
    lsum += la[i]
    i += 1

sm = min(lsum , lsum-la[i-1])

if lsum - S/2 > S/2 - (lsum-la[i-1]):
    print(S - 2*(lsum-la[i-1]))
else:
    print(2*lsum - S)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

input = sys.stdin.readline


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

    cumsum_A = list(accumulate(A))
    sum_A = sum(A)

    ans = float("inf")
    for i in range(N - 1):
        # cost = abs((sum_A - cumsum_A[i]) - cumsum_A[i])
        cost = abs(sum_A - 2 * cumsum_A[i])
        if cost < ans:
            ans = cost

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

input = sys.stdin.readline


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

    cumsum_A = list(accumulate(A))
    sum_A = sum(A)

    ans = float("inf")
    for i in range(N - 1):
        cost = abs((sum_A - cumsum_A[i]) - cumsum_A[i])
        if cost < ans:
            ans = cost

    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()))

    sum_A = sum(A)
    center = sum_A / 2
    total = 0
    near_center = 0
    for a in A:
        total += a
        if abs(total - center) < abs(near_center - center):
            near_center = total

    ans = abs((sum_A - near_center) - near_center)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=(sum(a))/2
count=0
if n==2:
    ans=int(abs((b-a[0])*2))
else:
    for i in range(n):
        count+=a[i]
        if b<=count:
            if i==0:
                c=count
                d=count+a[i+1]
            else:
                c=count-a[i]
                d=count
            break
    e=min(abs(c-b),abs(d-b))
    ans=int(e*2)
print(ans)

Submission status: Accepted

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

a = list(itertools.accumulate(a))

target = a[-1]
for i in a:
    target = min(abs(a[-1] - i * 2), target)

print(target)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**9)
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
def lispin(t=int):return list(pin(t))
#%%code
def resolve():
    N,=pin()
    A=lispin()
    temp=0
    sumA=[0]*N
    sumA[0]=A[0]
    for j in range(1,N):
        sumA[j]=sumA[j-1]+A[j]
    #print(sumA)
    ans=2**32-1
    t=sumA[-1]
    for i in range(N):
        ans=min(ans,abs(t-sumA[i]*2))
        
    print(ans)
#%%submit!
resolve()

Submission status: Accepted

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

import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from operator import mul
from functools import reduce
from collections import Counter
#from collections import deque

#input = stdin.readline


j=0
k=0
n=3
r=1
a=[0]
#n=int(input())
#r=int(input())
#print(M)
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"


#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
    print(number_list[i-1])#

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'''
x=[]
y=[]
for i in range(N):
    x1, y1=[int(i) for i in input().split()]
    x.append(x1)
    y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''

'''
mixlist=[]
for i in range(N):
    a,b=input().split()
    mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ，今回はリスト一つで処理している"
'''

'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''

#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]

print(type(N))
print(N)
print(type(M))
print(M)

print(type(table))
print(table)
'''




#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値．桁ごとに分割したい．入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
#intを取ると文字列分解に使える
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''




'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''



'''
A, B, C=stdin.readline().rstrip().split()#str style 何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''


#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"


#a,b=map(int, input().split())  #int style 複数数値入力　「A B」みたいなスペース空いた入力のとき

#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成


##############################################################################################
##############################################################################################
#under this line explains example calculation



'''
コンビネーションの組み合わせの中身を出力する形式
for i in itertools.combinations(brray, 2)
combinationsをpermutationsにすれば順列になる
今回なら(abc133B)
入力
1 2
5 5
-2 8
出力
[[1, 2], [5, 5], [-2, 8]]
もちろん一次元リストでも使えるし
何よりiもリストのように使えるので便利
'''

#nCr combination
'''
def cmb(n,r):
    #When n < r , this function isn't valid
    r= min(n-r,r)
    #print(n,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n-r, -1))
    #flochart mul(n,n-1)=x
    #next     mul(x,n-2)........(n-r+1,n-r)
    #mul read a,b and returns a*b

    under = reduce(mul, range(1, r+1))
    #print(over, under)
    #reduce is applied mul(1,2)=2
    #next   mul(2,3)=6
    #next   mul(6,4)=4.........last(r!,r+1)=r+1!

    return over // under
    #// is integer divide
    #calc example 5C2
    #over=5*4*3
    #under=3*2*1
a = cmb(n, r)
#print(a)
'''

'''
import itertools
from itertools import combinations_with_replacement

combinationについて
以下の違いを意識しよう
combinations() p, r 長さrのタプル列、ソートされた順で重複なし

combinations_with_replacement() p, r 長さrのタプル列、ソートされた順で重複あり


使用例 　　　　　　　　　　　                  出力　　
combinations('ABCD', 2)　　　　　　　　　　　　AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)　　 AA AB AC AD BB BC BD CC CD DD
'''



'''
#集計
#example
#a=[2,2,2,3,4,3,1,2,1,3,1,2,1,2,2,1,2,1]
#a=Counter(a)
for i in a.most_common(n):print(i)
#most_common()メソッドは、出現回数が多い要素順にCounterオブジェクトを並び替えます。
#引数にint型の数字nを設定した場合は、出現回数が高い上位ｎ個の要素を返します。
#何も設定しなければ、コンテナ型にあるすべての要素を出現回数の順番に並び替えたタプル型オブジェクトを返します。
#out put
#(2, 8)
 #(1, 6)
#(3, 3)
#(4, 1)
'''


#二部探索(binary search)
#A = [1, 2, 3, 3, 3, 4, 4, 6, 6, 6, 6]
#print(A)
#index = bisect.bisect_left(A, 5) # 7 最も左(前)の挿入箇所が返ってきている
#A.insert(index, 5)
#print(index)
#print(A)
'''
bisect.bisect_left(a, x, lo=0, h=len(a))
引数
a: ソート済みリスト
x: 挿入したい値
lo: 探索範囲の下限
hi: 探索範囲の上限
(lo, hiはスライスと同様の指定方法)
bisect_leftはソートされたリストaに対して順序を保ったままxを挿入できる箇所を探索します。leftが示す通り、aにすでにxが存在している場合は、挿入箇所は既存のxよりも左側になります。また、lo, hiを指定することで探索範囲を絞り込むことも可能です。デフォルトはaの全体が探索対象です。
'''

'''
素数の判定
'''


def is_prime(n):
    if n == 1: return False

    for k in range(2, int(np.sqrt(n)) + 1):
        #sqrt(n)+1以上は考えて約数はないので却下
        if n % k == 0:
            return False
            #割り切れたらFalse
    return True


'''
npのmaxとmaximumの違い
xs = np.array([1, -2, 3])
np.max(xs, 0)
この出力は3となります．[1, -2, 3]と0の4つの数字のうち，最も大きい値を出力します．

一方で，[max(1, 0), max(-2, 0), max(3, 0)]を出力したい時があります．
その時は，numpyのmaximum関数を用います．

xs = np.array([1, -2, 3])
np.maximum(xs, 0)  # [1, 0, 3]

'''



########################################################################
########################################################################
#b2=a[:]  #1次元のときはコピーはこれで良い
#print(b2)

#a= [[0]*3 for i in range(5)] #2次元配列はこう準備、[[0]*3]*5だとだめ
#b3=copy.deepcopy(a)  #2次元配列はこうコピーする
#print(b3)

def main():

    w=1
    j=0
    k=0
    dlen=0
    dsum=0
    ota=0
    n=int(input())
    al=list(map(int, input().split(" ")))
    dlen=sum(al)
    for i in range(n):
        dsum=dsum+al[i]
        if dsum*2 > dlen:
           ota=dsum-al[i]
           break

    #if dlen//2==0:#2で割り切れる時
    #    print(abs(dsum-dlen/2))
    #    sys.exit()
    #print(2*dsum,2*ota,dlen)
    print(min(abs(2*dsum-dlen),abs(2*ota-dlen)))
    #r=int(input())
    #dp= [[0]*3 for i in range(5)]#列　行
    #dp用の0の入ったやつ
    #dp= [[0]*(w+1) for i in range(n+1)]#0からwまでのw+1回計算するから
    #print(dp)＃初期条件が入る分計算回数+1列分必要(この場合は判断すべきものの数)
    DP = np.zeros(w+1, dtype=int)#これでも一次元リストが作れる
    exdp=np.zeros((3,4)) # ３×４の２次元配列を生成。2次元ならこう
    #dtypeは指定しないとfloatになる
    #for i in range(n):#ちょっとした入力に便利
    #    a, b = map(int, input().split())
        #dp[i][0] += [a]
        #これだとintとlistをつなぐことになって不適
    #    dp[i] += [a]
    #    dp[i] += [b]
        #これはうまくいく
        #やり方はいろいろあるということ
    #print(dp)


    "1行1つの整数を入力を取得し、整数と取得する"
    #number_list=list(map(int, input().split(" ")))#数字の時
    #print(number_list)
    "12 21 332 とか入力する時に使う"
    "1行に複数の整数の入力を取得し、整数として扱う"
    #brray=[list(map(int, input().split(" ")))for i in range(N)
    #print(brray)


    #s=input()
    #a=[int(i) for i in s]#int取るとstrでも行ける
    #print(a)
    '''
    入力
    1234
    出力
    [1, 2, 3, 4]
    '''
    pin_l=["x" for i in range(10)]#内包表記に慣れろ
    #print(pin_l)

    ls = ["a", "b", "c", "d", "e"]


    #print(ls[2:5])
    #スライスでの取得

    #print(ls[:-3])
    #一番左端から右から3番目より左まで取得

    #print(ls[:4:2])
    #スライスで1個飛ばしで取得
    #ないときは左端スタート
    #始点のインデックス番号 : 終点のインデックス番号 : スキップする数+1
    #print(ls[::2])
    '''
    lsというリストの場合に、1つ飛びの値を取得したい場合には
    ls[::2]
    のようにします。こうすると、
    ["a", "c", "d"]と出力される
    '''

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a_inputs = list(map(int,input().split()))
len_bar = sum(a_inputs)

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

gap = float('inf')
for i in range(n-1):
    g = abs(len_bar-2*cum_bar[i])
    if g<gap:
        gap=g
print(gap)

Submission status: Accepted

Solution code:
N = int(input())
arr = list(map(int, input().split()))
first = 0
second = sum(arr)
min_delta = second - first
for i in range(N):
    first += arr[i]
    second -= arr[i]
    min_delta = min(abs(second - first), min_delta)

print(min_delta)

Submission status: Accepted

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

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

mind = 1 << 40
sumA = csum[-1]
for i in range(n):
	diff = abs(sumA - 2 * csum[i])
	mind = min(mind, diff)

print(mind)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
l = sum(a)
accu = 0
for i in a:
    accu += i
    if accu>l/2:
        if abs(l/2-accu)<abs(l/2-accu+i):
            print(accu*2-l)
        else:
            print(l-(accu-i)*2)
        break

Submission status: Accepted

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

t1 = 0
t2 = sum(a)
ans = 10**18
for i in a:
    t1 += i
    t2 -= i
    ans = min(ans, abs(t1 - t2))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
s = sum(a)
d = s // 2
t = 0
i = -1
while(t <= d):
    i += 1
    t += a[i]
t2 = t - a[i]
# print(t,t2,s)
# print(t-(s-t),(s-t2)-t2)
print(min(t - (s - t),(s - t2) - t2))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
sA = [A[0]]
d = []
for i in range(1, N):
    sA.append(sA[-1] + A[i])

for i in range(N):
    d.append(abs(sA[i] - (sA[-1] - sA[i])))
print(min(d))

Submission status: Accepted

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

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

from itertools import accumulate
acc = [0] + a
acc = list(accumulate(acc))

suma = sum(a)

ans = float('inf')

for i in range(n):
    ans = min(abs( 2*acc[i]-suma  ),ans  )

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
s=sum(a)
ans = 12345678901234
cnt = 0
for i in range(n):
    cnt += a[i]
    ans = min(ans,abs(s-cnt - cnt))
print(ans)

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
## libs ##
from itertools import accumulate as acc
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    n = II()
    aa = MII()
    aa_acc = list(acc([0]+aa))
    min_num = 0
    min_d = abs(2*aa_acc[1]-aa_acc[n])
    for i in range(2,n):
        l = aa_acc[i]
        r = aa_acc[n] - aa_acc[i]
        min_d = min(min_d, abs(l-r))
    print(min_d)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

length = sum(A)
center = length / 2

now = 0
for i in range(N):
    now += A[i]
    if now == center:
        print(0)
        break
    if now > center:
        print(int(min(now-center, center-now+A[i]) * 2))
        break

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
def Csum(a):
    b,c=[0],0
    for i in range(len(a)):
        c+=a[i]
        b.append(c)
    return b
b=Csum(a)
c=sum(a)
d=[]
for i in range(1,n):
    d.append(abs((c-b[i])-b[i]))
print(min(d))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
_sum = sum(A)
diff = [0]*(N-1)
cumul = 0
for i in range(N-1):
    cumul += A[i]
    diff[i] = abs(cumul - (_sum - cumul))
# print(diff)
print(min(diff))

Submission status: Accepted

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

S=[]
s=0
for i in range(N):
    s+=A[i]
    S.append(s)
sm=sum(A)
ans=10**18
for i in range(N):
    val=abs(S[i]-(sm-S[i]))
    ans=min(ans,val)
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
def myAnswer(N:int,A:list) -> int:
   accum = [A[0]]
   accumRev = [sum(A)]
   ans = 10**10
   for i in range(1,N):
      accumRev.append(accumRev[-1] - A[i-1])
      accum.append(accum[-1]+A[i])
   for i in range(len(accum)-1):
      ans = min(ans,abs(accumRev[i+1] - accum[i]))
   return ans
      
def modelAnswer(N:int,A:list) -> int:
   T1 = [A[0]]
   T2 = [sum(A)]
   for i in range(1,N): # O(N)
      T1.append(T1[-1]+A[i])
      T2.append(T2[0] - T1[i-1])
   # print(T1,T2)
   ans = 10**10
   for i in range(len(T1)-1): # O(N/2)
      # print(abs(T1[i]-T2[i+1]))
      ans = min(ans,abs(T1[i]-T2[i+1]))
   return ans


def main():
   N = int(input())
   A = list(map(int,input().split()))
   # print(modelAnswer(N,A[:]))
   # print("-----------------------------")
   print(myAnswer(N,A[:]))
if __name__ == '__main__':
   main()

Submission status: Accepted

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

tmp = [0 for i in range(N+1)]
length = 0
for i in range(N):
  tmp[i+1] = tmp[i] + A[i]
  length += A[i]
  
ans = 10 ** 10
for i in range(1, N+1):
 ans = min(ans, abs((length - tmp[i]) - tmp[i]))

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
SUM = sum(a) 
ans = []
l = [[0, SUM]]
for i in range(n):
    l.append([l[i][0] + a[i], SUM - (l[i][0] + a[i])])
for i in l:
    ans.append(abs(i[0] - i[1]))
print(min(ans))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
sA = [A[0]]
d = []
for i in range(1, N):
    sA.append(sA[-1] + A[i])

for i in range(N):
    d.append(abs(sA[i] - (sA[-1] - sA[i])))
print(min(d))

Submission status: Accepted

Solution code:
def modelAnswer(N:int,A:list) -> int:
   T1 = [A[0]]
   T2 = [sum(A)]
   for i in range(1,N):
      T1.append(T1[-1]+A[i])
      T2.append(T2[0] - T1[i-1])
   # print(T1,T2)
   ans = 10**10
   for i in range(len(T1)-1):
      # print(abs(T1[i]-T2[i+1]))
      ans = min(ans,abs(T1[i]-T2[i+1]))
   return ans


def main():
   N = int(input())
   A = list(map(int,input().split()))
   print(modelAnswer(N,A[:]))
if __name__ == '__main__':
   main()

Submission status: Accepted

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

s = [0]*(N+1)
for i in range(N):
    s[i+1] = s[i] + A[i]

ans = float('inf')
for i in range(1,N):
    ans = min(abs(s[N]-s[i]-s[i]),ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = int(input())
    A = np.array(input().split(), np.int64)
    B = np.append(0, A.cumsum())
    C = A[::-1].cumsum()
    C = np.append(C[::-1], 0)
    print(np.abs(B-C).min())



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np

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

r = sum(A)
l = 0

ans = np.inf
for ai in A:
    l += ai
    r -= ai
    ans = min(np.abs(r-l), ans)

print(ans)

Submission status: Accepted

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

sum_a = sum(a)
tmp = 0
p = sum_a - 2 * tmp

for x in a:
    tmp += x
    p = min(p, abs(sum_a - 2 * tmp))

print(p)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
suma=sum(a)
f=0
p=suma-2*f
for i in a:
    f+=i
    p=min(p,abs(suma-2*f))
print(p)

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n = int(input())
    A = readInts()
    # 全体の合計 その差が答え 全部で最小値を取る
    total = sum(A)
    mi_ = float("inf")
    left = 0
    for i in range(n):
        left += A[i]
        total -= A[i]
        mi_ = min(mi_,abs(left - total))
    print(mi_)
if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
n=int(input())
A =list(map(int,input().split()))
k = sum(A)/2
cnt=0
cnt2 = 0
for i in A:
    k -= i
    if k < 0:
        cnt += abs(k) 
        cnt2 += k + i
        break
    
print(int(2*min(cnt,cnt2)))

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))
count=0
suml=sum(l)
i=0
while count<suml/2:
    count+=l[i]
    i+=1
k=suml/2
a=l[i-1]
if count==k:
    print(0)
else:
    print(int(2*(min(count-k,a-count+k))))

Submission status: Accepted

Solution code:
n = int(input())
A = []

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

sum_b = sum(B)
left = 0
for i in range(n-1):
    left += B[i]
    right = sum_b - left
    A.append(abs(right - left))
print(min(A))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
sm = sum(A)
t = 0
for i in range(N):
    if t > sm/2:
        break
    else:
        t += A[i]
        s = t-A[i]
u = 2*t - sm
v = sm - 2*s
print(min(u,v))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
ans = float('inf')
l_sum = 0
r_sum = sum(A)
for i in range(N):
    l_sum += A[i]
    r_sum -= A[i]
    ans = min(ans, abs(r_sum - l_sum))

print(ans)

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]
ans = a[n-1]
for x in a[:n-1]:
    ans = min(ans, abs(a[n-1] - 2 * x))
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split(' ')))
acc = A[0]
S = sum(A)
ans= abs(S-2*acc)
for i in A[1:]:
    acc += i
    ans = min(ans,abs(S-2*acc))
print(ans)

Submission status: Accepted

Solution code:
from numpy import*
input();a=array(list(map(int,input().split())))
print(int(min(abs(cumsum(a)-(sum(a)/2)))*2))

Submission status: Accepted

Solution code:
from numpy import*
n, *a = map(int, open(0).read().split())
a = array(a)
print(int(min(abs(cumsum(a)-(sum(a)/2)))*2))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
a = list(itertools.accumulate(list(map(int, input().split()))))
sum_a = a[-1]
res = 2020202020
for i in range(n):
  res = min(res, abs(sum_a - a[i]*2))
print(res)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int, input().split()))
d=sum(a)
ans=d
for i in range(n):
  d=d-2*a[i]
  if abs(d)<ans:
    ans=abs(d)
print(ans)

Submission status: Accepted

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

s = sum(A)
ans = float("inf")
cum = 0

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

print(ans)

Submission status: Accepted

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

result = 2020202020
num_left = 0
num_right = sum(a)

for i in range(n):
    num_left += a[i]
    num_right -= a[i]
    result = min(result, abs(num_left - num_right))
print(result)

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
index = 0
suml = 0
sumr = sum(A)
diff = sumr
ans = 0
for i in range(n):
    suml += A[i]
    sumr -= A[i]
    tmp  = abs(sumr -suml)
    if diff < tmp:
        ans = diff
        break
    diff = tmp
print(ans)