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: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>han:
  if i==n-1:
    break
  han+=a[i]
  i+=1

print(abs(2*han-sm))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>han:
  if i==n-1:
    break
  han+=a[i]
  i+=1

print(2*han-sm)

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>han:
  if i==n-1:
    break
  han+=a[i]
  i+=1
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>=han:
  if i==n-1:
    break
  han+=a[i]
  i+=1
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>=han:
  han+=a[i]
  i+=1
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>=han:
  han+=a[i]
  i+=1
print(han)
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm/2>han:
  han+=a[i]
  i+=1
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
sm=sum(a)
i=0
han=0

while sm//2>han:
  han+=a[i]
  i+=1
nhan=sm-han

print(abs(han-nhan))

Submission status: Wrong Answer

Solution code:
N=int(input())
*A,=map(int,input().split())
B=A[::-1]

count1=0
count2=0
i=0
while i<N:
    count1+=A[i]
    count2+=B[i]
    ans1=count1-sum(A[i+1:])
    ans2=count2-sum(B[i+1:])
    if ans1>=0 or ans2>=0:
        break
    i+=1

print(min(i for i in [ans1,ans2] if i>=0))

Submission status: Wrong Answer

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

count1=0
i=0
while i<N:
    count1+=A[i]
    i+=1
    ans1=count1-sum(A[i:])
    if ans1>=0:
        break

if ans1<=count1-i:
    print(ans1)
else:
    print(sum(A[i-1:])-sum(A[:i-1]))

Submission status: Wrong Answer

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

count1=0
i=0
while i<N:
    count1+=A[i]
    i+=1
    ans1=count1-sum(A[i:])
    if ans1>=0 and ans1<=i:
        break


A=A[::-1]
count2=0
j=0
while j<N:
    count2+=A[j]
    j+=1
    ans2=count2-sum(A[j:])
    if ans2>=0 and ans2<=j:
        break

print(min(ans1,ans2))

Submission status: Wrong Answer

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

count1=0
i=0
while count1<0--sum(A)//2:
    count1+=A[i]
    i+=1

print(count1-sum(A[i:]))

Submission status: Wrong Answer

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

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

import sys
input = sys.stdin.readline

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


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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

Submission status: Wrong Answer

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

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

import sys
input = sys.stdin.readline

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


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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

#############
# Main Code #
#############
N = I()
L = IL()

SUM = 0
while SUM<N:
  SUM+=L.pop()
  
print(abs(N-SUM*2))

Submission status: Wrong Answer

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

almost_half = sum(A)/2

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

Submission status: Wrong Answer

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


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


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


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


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


n = inp()
mid = n // 2
if n % 2 != 0:
    mid = (n // 2) + 1
a = inlist()
s1 = sum(a[:mid])
s2 = sum(a[mid:])
print(abs(s1-s2))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [int(i) for i in input().split(" ")]
Min = 10**9
for i in range(1,len(A)):
    diff = abs(sum(A[:i]) - sum(A[i:]))
    if diff < Min:
        Min = diff
print(Min)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int, input().split()))
res = 10**9
left = 0
right = sum(A)
for i in range(N):
    left += A[i] 
    right -= A[i]
    if abs(right-left) < res:
        res = abs(right-left)
print(res)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int, input().split()))
res = 10**9
left = A[0]
right = sum(A) - left
for i in range(1,N):
    left += A[i] 
    right -= A[i]
    if abs(right-left) < res:
        res = abs(right-left)
print(res)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int, input().split()))
res = 10**9
for i in range(1,N):
    left = sum(A[0:i])
    right = sum(A[i:N])
    if abs(right-left) < res:
        res = abs(right-left)
print(res)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
from itertools import accumulate


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

Submission status: Wrong Answer

Solution code:
n=int(input())
a=[int(x) for x in input().rstrip().split()]
full=sum(a)
ans=0
for i in a:
  ans+=i
  if ans>=full-ans:
    break
print(abs(2*ans-full))

Submission status: Wrong Answer

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

N = ii()
A = li()

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

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

if i == N-1:
    print(abs(A[i] - acc[i-1]))
else:
    print(abs(acc[i] - (acc[-1] - acc[i])))

Submission status: Wrong Answer

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

#入力
# s = list(input()[0:-1])
n = int(input())
a = list(map(int, input().split()))
# a = list(map(int,input().split()))
# b = list(map(int,input().split()))
# w = [int(input()) for i in range(n)]

# ab=[]
# for i in range(N):
#     a,b = map(int, input().split())
#     ab.append((a,b))
 
def main():
    tmp = 0
    l = sum(a)
    for i in a:
        tmp+=i
        if tmp >=(l//2):
            break
    left = tmp
    right = l -tmp
    print(abs(l//2 - left) + abs(l//2 - right))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

l = 0
r = n - 1
mid = (l + r) // 2

left = sum(nums[:mid])
right = sum(nums[mid:])
ans1 = abs(left - right)

left = sum(nums[:mid + 1])
right = sum(nums[mid + 1:])
ans2 = abs(left - right)

ans = min(ans1, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

n = int(input())

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

cnt = 0
sum_ = sum(a)/2

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

print(int(x1*2))

Submission status: Wrong Answer

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

b = [0]
aaa = 0
for i in range(n):
    aaa += a[i]
    b.append(aaa)

sum_a = sum(a)
ans = 202020202020
for i in range(n):
    if ans < abs(sum_a -b[i]*2):
        break
    ans = min(ans, abs(sum_a - b[i]*2))
print(ans)

Submission status: Wrong Answer

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

# In[15]:


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


# In[16]:


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


# In[ ]:

Submission status: Wrong Answer

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

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

    return arr

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

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

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

# 素数判定



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

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

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

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

    else:
        ret = []

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

        for i in S:

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

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

        return ret


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

Submission status: Wrong Answer

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

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

    return arr

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

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

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

# 素数判定



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

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

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

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

    else:
        ret = []

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

        for i in S:

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

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

        return ret


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

Submission status: Wrong Answer

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

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

    return arr

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

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

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

# 素数判定



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

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

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

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

    else:
        ret = []

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

        for i in S:

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

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

        return ret


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