TnT/Multi_CodeNet4Repair huggingface dataset:
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
n = int(input())
a = list(map(int,input().split()))
s = sum(a)
dif = float('inf')
snk = 0
for i in range(n-1):
    snk += a[i]
    if abs(snk*2-s) > dif:
        break
    dif = abs(snk*2-s)
print(snk*2-s)


n = int(input())
a = list(map(int,input().split()))
s = sum(a)
dif = float('inf')
snk = 0
for i in range(n-1):
    snk += a[i]
    if abs(snk*2-s) > dif:
        break
    dif = abs(snk*2-s)
print(abs(snk*2-s))


n = int(input())
a = list(map(int,input().split()))
s = sum(a)
dif = float('inf')
snk = 0
for i in range(n-1):
    snk += a[i]
    dif = min(abs(snk*2-s),dif)
print(dif)


Verdicts: Wrong Answer

Wrong Answer

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
# -*- coding: utf-8 -*-
n = int(input())
aa = [0]
s = 0
for x in input().split():
    a = int(x)
    aa.append(aa[-1]+a)
    s += a

ret = abs(2*a[0]-s)
for i in range(1,n):
    if abs(aa[i]-(s-aa[i]))<ret:
        ret = abs(aa[i]-(s-aa[i]))

print(ret)


# -*- coding: utf-8 -*-
n = int(input())
aa = [0]
s = 0
for x in input().split():
    a = int(x)
    aa.append(aa[-1]+a)
    s += a

ret = abs(2*aa[1]-s)
for i in range(1,n):
    if abs(aa[i]-(s-aa[i]))<ret:
        ret = abs(aa[i]-(s-aa[i]))

print(ret)


Verdicts: Runtime Error

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
n=int(input())
num=list(map(int,input().split()))
s=sum(num)
a=num[0]
check=s-2*a
ans=abs(check)
for i in range(1,n-1):
  check-=2*num[i+1]
  if abs(check)<ans:
    ans=abs(check)
print(ans)


n=int(input())
num=list(map(int,input().split()))
s=sum(num)
a=num[0]
check=s-2*a
ans=abs(check)
for i in range(1,n-1):
  check-=2*num[i]
  if abs(check)<ans:
    ans=abs(check)
print(ans)


Verdicts: Wrong Answer

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
n = int(input())
a = list(map(int, input().split()))

x = 0
y = sum(a)
ans = []

if i in range(n-1):
    x += a[i]
    y -= a[i]
    ans.append(abs(x-y))

print(min(ans))

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

x = 0
y = sum(a)
ans = []

for i in range(n-1):
    x += a[i]
    y -= a[i]
    ans.append(abs(x-y))

print(min(ans))


Verdicts: Runtime Error

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
N = int(input())
As = [int(x) for x in input().split()]
S = sum(As)

print(S)
for i in range(1,N):
    subs = sum(As[:i])
    temp = abs(2 * subs - S)
    if ans is None or temp < ans:
        ans = temp
print(ans)


N = int(input())
As = [int(x) for x in input().split()]
S = sum(As)

ans = None
subsum = 0
for i in range(1,N):
    subsum += As[i-1]
    temp = abs(2 * subsum - S)
    if ans is None or temp < ans:
        ans = temp
print(ans)


Verdicts: Runtime Error

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
N = int(input())
x = list(map(int, input().split()))

total = sum(x)
cum_sum = 0
ans = float('inf')
for i in range(N - 1):
    cum_sum += x[i]
    ans = min(ans, total - cum_sum)
print(ans)


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



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

sum_num = sum(a)
current_sum = 0
min_diff = float('inf')
for i in range(0, N - 1):
    current_sum += a[i]
    min_diff = min(min_diff, abs(current_sum - (sum_num - current_sum)))
print(min_diff)


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

total = sum(x)
cum_sum = 0
ans = float('inf')
for i in range(N - 1):
    cum_sum += x[i]
    ans = min(ans, abs(cum_sum - (total - cum_sum)))
print(ans)


Verdicts: Wrong Answer

Runtime Error

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
import sys




def read_int_list():
    return list(map(int, input().split()))
import sys




def read_int_list():
    return list(map(int, input().split()))


def read_int():
    return int(input())


def read_str_list():
    return input().split()


def read_str():
    return input()


def solve():
    n = read_int()
    a = sorted(read_int_list())
    res = 2 * 10 ** 10
    for i in range(n):
        d = a[i+1] - a[i]
        if res > d:
            res = d
    return res


def main():
    res = solve()
    print(res)


if __name__ == '__main__':
    main()


def read_int():
    return int(input())


def read_str_list():
    return input().split()


def read_str():
    return input()


def solve():
    n = read_int()
    a = sorted(read_int_list())
    res = 2 * 10 ** 10
    for i in range(n):
        d = a[i+1] - a[i]
        if res > d:
            res = d
    return res


def main():
    res = solve()
    print(res)


if __name__ == '__main__':
    main()


import sys




def read_int_list():
    return list(map(int, input().split()))


def read_int():
    return int(input())


def read_str_list():
    return input().split()


def read_str():
    return input()


def solve():
    n = read_int()
    a = read_int_list()
    res = 2 * 10 ** 10
    x = 0
    y = sum(a)
    for i in range(n - 1):
        x += a[i]
        y -= a[i]
        d = abs(x-y)
        if res > d:
            res = d
    return res


def main():
    res = solve()
    print(res)


if __name__ == '__main__':
    main()


Verdicts: Runtime Error

Accepted
Problem: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.  They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.  Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|.

Submission attempts (in order):
N = int(input())
A = list(map(int,input().split()))
P = []

S = sum(A)

snuke = 0
ans = 10 ** 9

for i in range(0,N - 1):
  snuke += A[i]
  ans = (S - 2 * snuke)
  
  if ans >= dif:
    ans = dif
    
print(ans)
  

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

S = sum(A)

snuke = 0
ans = 10 ** 12

for i in range(N - 1):
  snuke += A[i]
  dif = abs(S - (2 * snuke))
  
  if ans >= dif:
    ans = dif
    
print(ans)

Verdicts: Runtime Error

Accepted
Problem: There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i).  On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation:    * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1.  A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally.

Submission attempts (in order):
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines

N = int(readline())
XY = (tuple(int(x)-1 for x in line.split()) for line in readlines())

graph = [[] for _ in range(N)]
for x,y in XY:
    graph[x].append(y)
    graph[y].append(x)

visited = [True] + [False] * (N-1)
q = [1]
ord = [1]
par = [0] * N
while q:
    x = q.pop()
    for y in graph[x]:
        if visited[y]:
            continue
        ord.append(y)
        par[y] = x
        visited[y] = True
        q.append(y)

G = [0] * (N+1)
for x in ord[:0:-1]:
    p = par[x]
    G[p] ^= (G[x]+1)

answer = 'Alice' if G[0] != 0 else 'Bob'
print(answer)


import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines

N = int(readline())
XY = (tuple(int(x)-1 for x in line.split()) for line in readlines())

graph = [[] for _ in range(N)]
for x,y in XY:
    graph[x].append(y)
    graph[y].append(x)

visited = [True] + [False] * (N-1)
q = [0]
ord = [0]
par = [0] * N
while q:
    x = q.pop()
    for y in graph[x]:
        if visited[y]:
            continue
        ord.append(y)
        par[y] = x
        visited[y] = True
        q.append(y)

G = [0] * (N+1)
for x in ord[:0:-1]:
    p = par[x]
    G[p] ^= (G[x]+1)

answer = 'Alice' if G[0] != 0 else 'Bob'
print(answer)


Verdicts: Wrong Answer

Accepted
Problem: There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i).  On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation:    * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1.  A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally.

Submission attempts (in order):
import sys
sys.setrecursionlimit(k:=2*n)
n=int(input())
T=[[]for _ in"_"*k]
for _ in range(n-1):a,b=map(int,input().split());T[a]+=b,;T[b]+=a,
def d(v,p):
 r=0
 for s in T[v]:
  if s!=p:r^=d(s,v)+1
 return r
print("ABloibc e"[d(1,1)<1::2])

import sys
n=int(input())
sys.setrecursionlimit(k:=2*n)
T=[[]for _ in"_"*k]
for _ in range(n-1):a,b=map(int,input().split());T[a]+=b,;T[b]+=a,
def d(v,p):
 r=0
 for s in T[v]:
  if s!=p:r^=d(s,v)+1
 return r
print("ABloibc e"[d(1,1)<1::2])

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
n,m=map(int,input().split())
def C(n, r ,mod=10**9+7):
    if n-r<r: r=n-r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k]) %mod

    return result % mod
print(C(a+1,b))

import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict 
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal as D  
  
from functools import lru_cache
from bisect import bisect_left as bileft, bisect_right as biright
from fractions import Fraction as F  






a,b=map(int,input().split())
if abs(a-b)>=2:
    print(0)
    exit()
mod=10**9+7
re=2 if a==b else 1
def kaijou(n):
    if n==1:return 1
    else:
        return (kaijou(n-1)*n)%mod


print(kaijou(a)*kaijou(b)*re%mod)

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
import math
N,M = map(int,input().split())
if abs(N - M) > 1:
  print(0)
else:
  print((math.factorial(N) * math.factorial(M)) % 1000000007)

import math
N,M = map(int,input().split())
if abs(N - M) > 1:
  print(0)
elif N == M:
  print((2*(math.factorial(N) * math.factorial(M))) % 1000000007)
else:
  print(((math.factorial(N) * math.factorial(M))) % 1000000007)

Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype=int)
Y = np.zeros(N, dtype=int)

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    

sel = np.argsort(np.array(edge_weight))

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    if flg[m]*flg[n] > 0:
        pass
    else:
        res += edge_weight[s]
        flg[m] = 1
        flg[n] = 1
print(res)

# C
N, M = map(int, input().split())
L = 1000000007

res = 1

if (M - N) >= 2 or (N - M) >= 2:
    res = 0
else:
    for k in range(M):
        res *= (k+1)
        res = res % L
    for k in range(N):
        res *= (k+1)
        res = res % L
    if M == N:
        res *= 2
        res = res % L
print(res)

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
#encoding: utf-8

def main():
    N,M=map(int,input().split())
    if(abs(N-M)<=2):
        return 0
    ret=1
    for i in range(1,N+1):
        ret*=i
    for i in range(1,M+1):
        ret*=i
    return ret


if __name__ == '__main__':
    main()

#encoding: utf-8

def main():
    N,M=map(int,input().split())
    if(abs(N-M)>=2):
        print(0)
        return

    ret=1
    mod=10**9+7
    for i in range(1,N+1):
        ret*=i
        ret%=mod
    for i in range(1,M+1):
        ret*=i
        ret %= mod
    if(N==M):
        r=2
    else:
        r=1
    print((ret*r)%mod)


if __name__ == '__main__':
    main()

Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
import math
n,m = map(int, input().split())
if abs(n-m)!=1:
    print(0)
else:
    print(math.factorial(n)%(10**9+7)*math.factorial(m)%(10**9+7))


import math
n,m = map(int, input().split())
if abs(n-m)>1:
    print(0)
elif abs(n-m)==0:
    print(math.factorial(n)*math.factorial(m)*2%(10**9+7))
else:
    print(math.factorial(n)*math.factorial(m)%(10**9+7))


Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
# -*- coding: utf-8 -*-

d = 10**9 + 7
n, m = map(int, input().split(' '))

ans = 0

ans1 = 1
n1 = n
m1 = m
while n1 >= 1 or m1 >= 0:
    ans1 *= n1 * m1
    ans1 %= d
    n1 -= 1
    m1 -= 1


ans2 = 1
n2 = n
m2 = m
while m2 >= 1 or n2 >= 0:
    ans2 *= m2 * n2
    ans2 %= d
    n2 -= 1
    m2 -= 1


print((ans1 + ans2) % d)


# -*- coding: utf-8 -*-

d = 10**9 + 7
n, m = map(int, input().split(' '))

ans = 0

ans1 = 1
n1 = n
m1 = m
while n1 >= 1:
    ans1 *= n1 * m1
    ans1 %= d
    n1 -= 1
    m1 -= 1

if m1 > 1:
    ans1 = 0

ans2 = 1
n2 = n
m2 = m
while m2 >= 1:
    ans2 *= m2 * n2
    ans2 %= d
    n2 -= 1
    m2 -= 1

if n2 > 1:
    ans2 = 0


print((ans1 + ans2) % d)


Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
# -*- coding: utf-8 -*-
#ARC076C
import sys
import math

#n=int(input())

tmp = input().split()
hoge = list(map(lambda a: int(a), tmp))

n=hoge[0]
m=hoge[1]

#total=1
#if(n==m):
#	total+=1

t = math.factorial(min(n,m))
if(abs(n-m)>1):
	print(0)
elif(n==m):
	print(2*t^2)
else:
	print(t^2*max(n,m))

# -*- coding: utf-8 -*-
#ARC076C
import sys
import math

#n=int(input())

tmp = input().split()
hoge = list(map(lambda a: int(a), tmp))

n=hoge[0]
m=hoge[1]

#total=1
#if(n==m):
#	total+=1

t = math.factorial(min(n,m))
#print(t)
#print(t**2)
if(abs(n-m)>1):
	print(0)
elif(n==m):
	print((2*(t**2))%1000000007)
else:
	print(((t**2)*max(n,m))%1000000007)


Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
# -*- coding: utf-8 -*-
from math import factorial

N = int(input())
cities = [[int(m) for m in input().split()] for n in range(N)]

def reasonable_way(A, B):
    A = list(sorted(set(A)))
    B = list(sorted(set(B)))
    
    a = 0
    b = 0
    
    cheap = 10**9 + 1
    
    while a < len(A) and b < len(B):
        if b+1 < len(B):
            while A[a] - B[b+1] > 0:
                if b+1 == len(B):
                    break
                else:
                    b += 1

        cheap = min(abs(A[a] - B[b]), cheap)
        if b+1 < len(B):
            cheap = min(abs(A[a] - B[b+1]), cheap)

        if cheap == 0:
            return 0

        a += 1        

    return cheap

x_key_map = {x: [] for x in set([city[0] for city in cities])}
y_key_map = {y: [] for y in set([city[1] for city in cities])}

for city in cities:
    x_key_map[city[0]].append(city[1])
    y_key_map[city[1]].append(city[1])

x_keys = list(sorted(x_key_map.keys()))
y_keys = list(sorted(y_key_map.keys()))
    
tmp = 0
for i in range(len(x_keys) - 1):
    tmp += min(abs(x_keys[i] - x_keys[i+1]),
               reasonable_way(x_key_map[x_keys[i]], x_key_map[x_keys[i+1]]))

result = tmp
tmp = 0

for i in range(len(y_keys) - 1):
    tmp += min(abs(y_keys[i] - y_keys[i+1]),
               reasonable_way(y_key_map[y_keys[i]], y_key_map[y_keys[i+1]]))    
result = min(result, tmp)

print(result)    

# -*- coding: utf-8 -*-
from math import factorial

N, M = [int(n) for n in input().split()]
if abs(N-M) == 0:
    result = factorial(N)**2 * 2
elif abs(N-M) == 1:
    result = factorial(N) * factorial(M)
else:
    result = 0
    
print(result % (10**9 + 7))

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
from math import factorial

N,M = map(int,input().split())

def foo(N,M):
	if N == M+1 or N+1 == M:
		tm = factorial(min(N,M))
		return(tm*max(N,M)+tm)

	elif N==M:
		return(2*factorial(N)*2)

	else:
		return(0)

print(foo(N,M)/(10**9+7))

from math import factorial

N,M = map(int,input().split())

def foo(N,M):
	if N == M+1 or N+1 == M:
		tm = factorial(min(N,M))
		return(tm*max(N,M)*tm)

	elif N==M:
		return((factorial(N)**2)*2)

	else:
		return(0)

print(foo(N,M)%(10**9+7))

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
n, m = map(int, input().split())
a = 0
b = 0
if abs(n-m) >= 2:
    print(0)
else:
    for i in range(2, n+1):
        a = (a*i) % (10**9+7)
    for j in range(2, m+1):
        b = (b*j) % (10**9+7)
    if n == m:
        print((a*b*2) % (10**9+7))
    else:
        print((a*b) % (10**9+7))


n, m = map(int, input().split())
a = 1
b = 1
if abs(n-m) >= 2:
    print(0)
else:
    for i in range(2, n+1):
        a = (a*i) % (10**9+7)
    for j in range(2, m+1):
        b = (b*j) % (10**9+7)
    if n == m:
        print((a*b*2) % (10**9+7))
    else:
        print((a*b) % (10**9+7))

Verdicts: Wrong Answer

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):
import sys
from functools import reduce,lru_cache
from operator import mul

def main():
  sys.setrecursionlimit(10 ** 5)
  N,M = map(int,input().split())
  
  @lru_cache(maxsize = None)
  def recur(n):
    if n == 0:
      return 1
    else:
      m = n * recur(n - 1)
      return m
      
  if N == M:
    L = [i for i in range(1,N + 1)]
    
    ans = (recur(N) % (10 ** 9 + 7))
    print(ans)
  elif abs(M - N) == 1: 
    ans = 1
    ans *= (recur(N) % (10 ** 9 + 7)) 
    ans *= (recur(M) % (10 ** 9 + 7))
    print(ans)
    
  else:
    print(0)
    
main()

import sys
from functools import reduce,lru_cache
import math
from operator import mul

def main():
  
  N,M = map(int,input().split())
  
  @lru_cache(maxsize = None)
  def recur(n):
    if n == 0:
      return 1
    else:
      m = n * recur(n - 1)
      return m
      
  if N == M:
    L = [i for i in range(1,N + 1)]
    
    ans = (math.factorial(M) ** 2) * 2 % ((10 ** 9) + 7)
    print(ans)
  elif abs(M - N) == 1: 
    ans = math.factorial(N) * math.factorial(M) % ((10 ** 9) + 7)
    print(ans)
    
  else:
    print(0)
    
main()

Verdicts: Runtime Error

Accepted
Problem: Snuke has N dogs and M monkeys. He wants them to line up in a row.  As a Japanese saying goes, these dogs and monkeys are on bad terms. _("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.)_ Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.  How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Submission attempts (in order):

mod=10**9+7
N=100005
kaidan=[1 for i in range(N)]
gyaku=[1 for i in range(N)]
for i in range(1,N):
    kaidan[i] = (i * kaidan[i-1])%mod
    gyaku[i]=pow(bikkuri[i], mod-2, mod)
def comb(a,b):
    return kaidan[a]*gyaku[b]*gyaku[a-b]
n,m=map(int,input().split())
if abs(n-m)>=2:
    print(0)
else:
    if n==m:
        print(kaidan[n]*kaidan[n]*2%mod)
    else:
        a=max(n,m)
        b=min(n,m)
        print(kaidan[a]*kaidan[b]%mod)


mod=10**9+7
N=100005
kaidan=[1 for i in range(N)]
gyaku=[1 for i in range(N)]
for i in range(1,N):
    kaidan[i] = (i * kaidan[i-1])%mod
    gyaku[i]=pow(kaidan[i], mod-2, mod)
def comb(a,b):
    return kaidan[a]*gyaku[b]*gyaku[a-b]
n,m=map(int,input().split())
if abs(n-m)>=2:
    print(0)
else:
    if n==m:
        print(kaidan[n]*kaidan[n]*2%mod)
    else:
        a=max(n,m)
        b=min(n,m)
        print(kaidan[a]*kaidan[b]%mod)

Verdicts: Runtime Error

Accepted
Problem: There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).  Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows:    * `.` : A square without a leaf.   * `o` : A square with a leaf floating on the water.   * `S` : A square with the leaf S.   * `T` : A square with the leaf T.  The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."  Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Submission attempts (in order):
import scipy.sparse as z;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+W]+A
 elif S[h][w]=='T':A=[h,m*3,w+W,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=z.csgraph.maximum_flow(z.csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+W]+A
 elif S[h][w]=='T':A=[h,m*3,w+W,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

import scipy.sparse as z;H,W,*S=open(0).read().split();W=int(W);m=int(H)*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=z.csgraph.maximum_flow(z.csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),[m*4]*2),m*2,m*3).flow_value;print(f if f<999 else -1)

Verdicts: Wrong Answer

Wrong Answer

Wrong Answer

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
import numpy as np
import math

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

maenogoukei = a[0]
goukei = a[0]
kaisuu = 0

if goukei == 0:
	kaisuu += 1
	maenogoukei = -1 
	goukei = maenogoukei



for a_i in a[1:]:
	goukei += a_i
	if maenogoukei > 0 and goukei >= 0:
		kaisuu += goukei + 1
		goukei = -1
		maenogoukei = -1
	elif maenogoukei < 0 and goukei <= 0:
		kaisuu += -goukei + 1
		goukei = 1
		maenogoukei = 1
	else:
		maenogoukei += a_i




maenogoukei2 = a[0]
goukei2 = a[0]
kaisuu2 = 0

if goukei2 == 0:
	kaisuu2 += 1
	maenogoukei2 = 1 
	goukei2 = 1
else:
	kaisuu2 += math.abs(goukei2) + 1
	maenogoukei2 = - int(np.sign(a[0]))
	goukei2 = - int(np.sign(a[0]))


for a_i2 in a[1:]:
	goukei2 += a_i2
	if maenogoukei2 > 0 and goukei2 >= 0:
		kaisuu2 += goukei2 + 1
		goukei2 = -1
		maenogoukei2 = -1
	elif maenogoukei2 < 0 and goukei2 <= 0:
		kaisuu2 += -goukei2 + 1
		goukei2 = 1
		maenogoukei2 = 1
	else:
		maenogoukei2 += a_i2

print( min([kaisuu,kaisuu2]) )

import numpy as np
import math

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

maenogoukei = a[0]
goukei = a[0]
kaisuu = 0

if goukei == 0:
	kaisuu += 1
	maenogoukei = -1 
	goukei = maenogoukei



for a_i in a[1:]:
	goukei += a_i
	if maenogoukei > 0 and goukei >= 0:
		kaisuu += goukei + 1
		goukei = -1
		maenogoukei = -1
	elif maenogoukei < 0 and goukei <= 0:
		kaisuu += -goukei + 1
		goukei = 1
		maenogoukei = 1
	else:
		maenogoukei += a_i




maenogoukei2 = a[0]
goukei2 = a[0]
kaisuu2 = 0

if goukei2 == 0:
	kaisuu2 += 1
	maenogoukei2 = 1 
	goukei2 = 1
else:
	kaisuu2 += abs(goukei2) + 1
	maenogoukei2 = - int(np.sign(a[0]))
	goukei2 = - int(np.sign(a[0]))


for a_i2 in a[1:]:
	goukei2 += a_i2
	if maenogoukei2 > 0 and goukei2 >= 0:
		kaisuu2 += goukei2 + 1
		goukei2 = -1
		maenogoukei2 = -1
	elif maenogoukei2 < 0 and goukei2 <= 0:
		kaisuu2 += -goukei2 + 1
		goukei2 = 1
		maenogoukei2 = 1
	else:
		maenogoukei2 += a_i2

print( min([kaisuu,kaisuu2]) )

Verdicts: Runtime Error

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
import sys,time
X, Y = map(int,input().split())
time.sleep((X%7)/5)


n = int(input())
ar = list(map(int,input().split()))
su = [0]*n
su[0]=ar[0]
for i in range(1,n):
    su[i] = ar[i] + su[i-1]

# +
ans1,off = 0,0
for i in range(0,n):
    if i%2 == 0:
        if su[i] + off <= 0:
            ans1 += 1-(su[i]+off)
            off += 1-(su[i]+off)
    else:
        if su[i] + off >= 0:
            ans1 += (su[i]+off+1)
            off -= (su[i]+off+1)

# -
ans2,off = 0,0
for i in range(0,n):
    if i%2 != 0:
        if su[i] + off <= 0:
            ans2 += 1-(su[i]+off)
            off += 1-(su[i]+off)
    else:
        if su[i] + off >= 0:
            ans2 += (su[i]+off+1)
            off -= (su[i]+off+1)
print(min(ans1,ans2))


Verdicts: Runtime Error

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
n = int(input())
l = list(map(int, input().split()))
 
ans = 0

def func(l, pn):
  ans = 0
  sum_ = 0
  for i in range(n):
    sum_ += l[i]
    if sum_ >= 0 and pn[i] < 0:
      ans += sum_+1
      sum_ = -1
    elif sum_ <= 0 and pn[i] > 0:
      ans += -sum_+1
      sum_ = 1
    else:
      continue
  return ans

pn1 = [1 if i%2 == 0 else -1 for i in range(n)]
pn2 = [-1 if i%2 == 0 else 1 for i in range(n)]

print(func(l, pn2))

n = int(input())
l = list(map(int, input().split()))
 
ans = 0

def func(l, pn):
  ans = 0
  sum_ = 0
  for i in range(n):
    sum_ += l[i]
    if sum_ >= 0 and pn[i] < 0:
      ans += sum_+1
      sum_ = -1
    elif sum_ <= 0 and pn[i] > 0:
      ans += -sum_+1
      sum_ = 1
    else:
      continue
  return ans

pn1 = [1 if i%2 == 0 else -1 for i in range(n)]
pn2 = [-1 if i%2 == 0 else 1 for i in range(n)]

print(min(func(l, pn1), func(l, pn2)))

Verdicts: Wrong Answer

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
N=int(input())
A=list(map(int,input().split()))
s=0
t=0
a=0
b=0
for i in range(N):
    s+=A[i]
    if i%2==0:
        if s>=0:
            a+=s+1
            s=-1
    if i%2!=0:
        if s<=0:
            a+=-s+1
            s=1
for j in range(N):
    t+=A[i]
    if j%2!=0:
        if t>=0:
            b+=t+1
            t=-1
    if j%2==0:
        if t<=0:
            b+=-t+1
            t=1
print(min(a,b))

N=int(input())
A=list(map(int,input().split()))
s=0
t=0
a=0
b=0
for i in range(N):
    s+=A[i]
    if i%2==0:
        if s>=0:
            a+=s+1
            s=-1
    if i%2!=0:
        if s<=0:
            a+=-s+1
            s=1
for j in range(N):
    t+=A[j]
    if j%2!=0:
        if t>=0:
            b+=t+1
            t=-1
    if j%2==0:
        if t<=0:
            b+=-t+1
            t=1
print(min(a,b))

Verdicts: Wrong Answer

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  9 14:32:30 2019

@author: shinjisu
"""


# arc 072 c sequence
def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def db(x):
    global debug
    if debug:
        print(x)


def count(N, A, initSum):
    # global N, A
    sm = initSum
    cnt = abs(sm-A[0])
    db(cnt)
    for i in range(N-1):
        nextSum = sm + A[i+1]
        db((sm, nextSum))
        if sm > 0 and nextSum >= 0:
            cnt += abs(nextSum)+1
            sm = -1
        elif sm < 0 and nextSum <= 0:
            cnt += abs(nextSum)+1
            sm = 1
        else:
            sm = nextSum
        db(cnt)
    return cnt


def probC():
    N = getInt()
    A = getIntList()
    db((N, A))
    if A[0] != 0:
        initSum = A[0]
    else:
        initSum = 1
    cnt1 = count(N, A, initSum)
    db(('a[0] or +1: ', cnt1))
    if initSum > 0:
        cnt2 = count(N, A, -1)
    else:
        cnt2 = count(N, A, 1)
    db(('反対符号 or -1: ', cnt2))
    return min(cnt1, cnt2)


debug = True
print(probC())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  9 14:32:30 2019

@author: shinjisu
"""


# arc 072 c sequence
def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def db(x):
    global debug
    if debug:
        print(x)


def count(N, A, initSum):
    # global N, A
    sm = initSum
    cnt = abs(sm-A[0])
    db(cnt)
    for i in range(N-1):
        nextSum = sm + A[i+1]
        db((sm, nextSum))
        if sm > 0 and nextSum >= 0:
            cnt += abs(nextSum)+1
            sm = -1
        elif sm < 0 and nextSum <= 0:
            cnt += abs(nextSum)+1
            sm = 1
        else:
            sm = nextSum
        db(cnt)
    return cnt


def probC():
    N = getInt()
    A = getIntList()
    db((N, A))
    if A[0] != 0:
        initSum = A[0]
    else:
        initSum = 1
    cnt1 = count(N, A, initSum)
    db(('a[0] or +1: ', cnt1))
    if initSum > 0:
        cnt2 = count(N, A, -1)
    else:
        cnt2 = count(N, A, 1)
    db(('反対符号 or -1: ', cnt2))
    return min(cnt1, cnt2)


debug = False
print(probC())


Verdicts: Wrong Answer

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
n=int(input())
a=list(map(int,input().split()))
p=[1,-1]
j=[-1,1]
c=a[0]
l=a[0]
d=0
e=0
for i in range(1,n):
    s=i%2
    c+=a[i]
    l+=a[i]
    if p[s]*c<=0:
        d+=abs(c-p[s])
        c=p[s]
    if j[s]*c>=0:
        e+=abs(c-j[s])
        l=j[s]      
print(min(e,d))

n=int(input())
a=list(map(int,input().split()))
p=[1,-1]
j=[-1,1]
c=0
l=0
d=0
e=0
for i in range(n):
    s=i%2
    c+=a[i]
    l+=a[i]
    print(c,l)
    if p[s]*c<=0:
        d+=abs(c-p[s])
        c=p[s]
    if j[s]*l<=0:
        e+=abs(l-j[s])
        l=j[s] 
print(min(e,d))

n=int(input())
a=list(map(int,input().split()))
p=[1,-1]
j=[-1,1]
c=0
l=0
d=0
e=0
for i in range(n):
    s=i%2
    c+=a[i]
    l+=a[i]
    if p[s]*c<=0:
        d+=abs(c-p[s])
        c=p[s]
    if j[s]*l<=0:
        e+=abs(l-j[s])
        l=j[s] 
print(min(e,d))

Verdicts: Wrong Answer

Wrong Answer

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
n = int(input())
lis = list(map(int,input().split()))
cou = 0
co = 0
ans1 = 0
ans2 = 0
for i in range(n):
  cou += lis[i]
  co += lis[i]
  if cou <= 0 and i % 2 == 0:
    ans1 += (1 -cou)
    cou = 1
  if cou => 0 and i % 2 == 1:
    ans1 += (cou +1)
    cou = -1
  if co => 0 and i % 2 == 0:
    ans2 += (co +1)
    co = -1
  if co <= 0 and i % 2 == 1:
    ans2 += (1 -co)
    co = 1
print(min(ans1,ans2))

n = int(input())
lis = list(map(int,input().split()))
cou = 0
co = 0
ans1 = 0
ans2 = 0
for i in range(n):
  cou += lis[i]
  co += lis[i]
  if cou <= 0 and i % 2 == 0:
    ans1 += (1 -cou)
    cou = 1
  if cou >= 0 and i % 2 == 1:
    ans1 += (cou +1)
    cou = -1
  if co >= 0 and i % 2 == 0:
    ans2 += (co +1)
    co = -1
  if co <= 0 and i % 2 == 1:
    ans2 += (1 -co)
    co = 1
print(min(ans1,ans2))

Verdicts: Runtime Error

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
import sys


def func(lst, sign):
  cur, res = 0, 0
  for i in alst:
    cur += i
    if sign and cur <= 0:
      res += abs(cur) + 1
      cur = 1
    elif not sign and cur >= 0:
      res += abs(cur) + 1
      cur = -1
    sign = not sign
  return res


def main():
  n, *alst = map(int, sys.stdin.read().split())
  print(min(func(alst, True), func(alst, False)))


if __name__ == '__main__':
  main()

import sys


def func(alst, sign):
  cur, res = 0, 0
  for i in alst:
    cur += i
    if sign and cur <= 0:
      res += abs(cur) + 1
      cur = 1
    elif not sign and cur >= 0:
      res += abs(cur) + 1
      cur = -1
    sign = not sign
  return res


def main():
  n, *alst = map(int, sys.stdin.read().split())
  print(min(func(alst, True), func(alst, False)))


if __name__ == '__main__':
  main()

Verdicts: Runtime Error

Accepted
Problem: You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.  At least how many operations are necessary to satisfy the following conditions?    * For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.   * For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Submission attempts (in order):
N = int(input())
A = list(map(int, input().split()))

def func(A, plus):
  total = 0
  ans = 0
  if plus:
    if A[0] <= 0:
      ans = abs(A[0])+1
      total = 1
  else:
    if A[0] >= 0:
      ans += abs(A[0])+1
      total = -1
  for a in A[1:]:
    t = total + a
    if total * t < 0:
      total = t
      continue
    ans += abs(t)+1
    total = -1 if total > 0 else 1
  return ans

print(min(func(A, True), func(A, False)))

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

def func(A, plus):
  total = A[0]
  ans = 0
  if plus:
    if A[0] <= 0:
      ans = abs(A[0])+1
      total = 1
  else:
    if A[0] >= 0:
      ans += abs(A[0])+1
      total = -1
  for a in A[1:]:
    t = total + a
    if total * t < 0:
      total = t
      continue
    ans += abs(t)+1
    total = -1 if total > 0 else 1
  return ans

print(min(func(A, True), func(A, False)))

Verdicts: Wrong Answer

Accepted