Problem:


Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.



Sample input:
3 20
2 80
9 120
16 1


Sample output:
191

Submission status: Wrong Answer

Solution code:
N,C=map(int,input().split())
li=[list(map(int,input().split())) for i in range(N)]

cumR=[0]*(N+1)
cummaxR=[0]*(N+1)
for i in range(N):
    cumR[i+1]=cumR[i]+li[i][1]-li[i][0]
    cummaxR[i+1]=cummaxR[i]+li[i][1]-li[i][0]*2
    if i>0:
        cumR[i+1]+=li[i-1][0]
        cummaxR[i+1]+=li[i-1][0]*2
for i in range(1,N):
    cummaxR[i]=max(cummaxR[i],cummaxR[i-1])
cumL=[0]*(N+1)
cummaxL=[0]*(N+1)
for i in reversed(range(N)):
    cumL[i]=cumL[i+1]+li[i][1]-(C-li[i][0])
    cummaxL[i]=cummaxL[i+1]+li[i][1]-(C-li[i][0])*2
    if i<N-1:
        cumL[i]+=(C-li[i+1][0])
        cummaxL[i]+=(C-li[i+1][0])*2
for i in reversed(range(N)):
    cummaxL[i]=max(cummaxL[i],cummaxL[i+1])
ans=0
for i in range(N):
    res=cumR[i]+cummaxL[i+1]
    ans=max(ans,res)
    res2=cumL[i]+cummaxR[i]
    ans=max(ans,res2)
print(ans)

Submission status: Wrong Answer

Solution code:
n, c = map(int, input().split())
ss_l = []
ss_l_half = []
adj = 0
c_div_2 = c / 2
cnt_l = 0
for i in range(n):
    x, v = map(int, input().split())
    ss_l.append((x,v))
    if x < c_div_2:
        ss_l_half.append((x, v))
        cnt_l += 1
cnt_r = 0
ss_r = []
ss_r_half = []
for i in ss_l[::-1]:
    x, v = i
    ss_r.append((c-x, v))
    if c-x < c_div_2:
        ss_r_half.append((c-x, v))
        cnt_r += 1
#print(ss_l)
#print(ss_r)
#print(ss_l_half)
#print(ss_r_half)
rsw_all_l = [0]*n
rsw_all_l[0] = ss_l[0][1]
for i in range(1,n):
    rsw_all_l[i] = rsw_all_l[i-1] + ss_l[i][1]
for i in range(n):
    rsw_all_l[i] -= ss_l[i][0]
#print(rsw_all_l)
rsw_all_r = [0]*n
rsw_all_r[0] = ss_r[0][1]
for i in range(1,n):
    rsw_all_r[i] = rsw_all_r[i-1] + ss_r[i][1]
for i in range(n):
    rsw_all_r[i] -= ss_r[i][0]
#print(rsw_all_r)
res = max(0, max(rsw_all_l), max(rsw_all_r))
#print(res)
rsw_l = [0]*(cnt_l)
if cnt_l >= 1:
    rsw_l[0] = ss_l_half[0][1]
if cnt_l >= 2:
    for i in range(1,cnt_l):
        rsw_l[i] = rsw_l[i-1] + ss_l_half[i][1]
#print(rsw_l)
rsw_l_opp = rsw_l.copy()
if cnt_l >= 1:
    rsw_l[0] -= ss_l_half[0][0]
    rsw_l_opp[0] -= ss_l_half[0][0]*2
if cnt_l >= 2:
    for i in range(1,cnt_l):
        rsw_l[i] -= ss_l_half[i][0]
        rsw_l_opp[i] -= ss_l_half[i][0]*2
#print(rsw_l)
#print(rsw_l_opp)
rsw_r = [0]*(cnt_r)
if cnt_r >= 1:
    rsw_r[0] = ss_r_half[0][1]
if cnt_r >= 2:
    for i in range(1,cnt_r):
        rsw_r[i] = rsw_r[i-1] + ss_r_half[i][1]
rsw_r_opp = rsw_r.copy()
if cnt_r >= 1:
    rsw_r[0] -= ss_r_half[0][0]
    rsw_r_opp[0] -= ss_r_half[0][0]*2
if cnt_r >= 2:
    for i in range(1,cnt_r):
        rsw_r[i] -= ss_r_half[i][0]
        rsw_r_opp[i] -= ss_r_half[i][0]*2
#print(rsw_r)
#print(rsw_r_opp)
res = max(res,max([0]+rsw_l)+max([0]+rsw_r_opp),max([0]+rsw_r)+max([0]+rsw_l_opp))
print(res)

Submission status: Wrong Answer

Solution code:
N,C = map(int,input().split())
xv = [[0,0]]+[list(map(int,input().split())) for i in range(N)]+[[C,0]]
#0~N+1

#xがある位置
#vがカロリー

#時計回りでの最大値
tokei_maxs = [0]*(N+2)
#時計まわりでの最大値（現状）
tokei=[0]*(N+2)
tokei_max = 0
preans = 0
for i in range(1,N+1,1):
    tmpans = preans + xv[i][1] - (xv[i][0]-xv[i-1][0])
    tokei_max = max(tokei_max,tmpans)
    tokei[i]=tmpans
    tokei_maxs[i]=tokei_max
    preans = tmpans


#h時計回りでの最大値
htokei_maxs = [0]*(N+2)
htokei=[0]*(N+2)
#h時計まわりでの最大値（現状）
htokei_max = 0
preans = 0
for i in range(N,0,-1):
    tmpans = preans + xv[i][1] - (xv[i+1][0]-xv[i][0])
    htokei_max = max(htokei_max,tmpans)
    htokei_maxs[i]=htokei_max
    htokei=tmpans
    preans=tmpans

ans = 0

for i in range(0,N+1,1):
    ans = max(ans,tokei[i]+max(0,htokei_maxs[i+1]-xv[i][0]))

for i in range(N+1,0,1):
    ans = max(ans,htokei[i]+ max(0,tokei_maxs[i-1]-C+xv[i][0]))

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

from itertools import accumulate
N, C = mapint()
xv = [list(mapint()) for _ in range(N)]
righthand = [0]
lefthand = [0]
lastx = 0
for i in range(N):
    x, v = xv[i]
    x -= lastx
    righthand.append(v-x)
    lastx = x

lastx = C
rxv = xv[::-1]
for i in range(N):
    x, v = rxv[i]
    x = lastx-x
    lefthand.append(v-x)
    lastx = C-x

righthand = list(accumulate(righthand))
lefthand = list(accumulate(lefthand))

lmax = 0
for i in range(N):
    lmax = max(lmax, lefthand[i+1]+max(max(righthand[:N-i])-(C-rxv[i][0]), 0))
rmax = 0
for i in range(N):
    rmax = max(rmax, righthand[i+1]+max(max(lefthand[:N-i])-xv[i][0], 0))
print(max(lmax, rmax))

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline


def main():
    N, C = [int(x) for x in input().split()]
    XV = [[int(x) for x in input().split()] for _ in range(N)]

    migi = [0]
    last = 0
    for x, v in XV:
        migi.append(migi[-1] + v - x + last)
        last = x

    hidari = [0]
    last = C
    for x, v in XV[::-1]:
        hidari.append(hidari[-1] + v - (last - x))
        last = x

    ans = max(max(migi), max(hidari))

    migimax = [0]
    ma = 0
    for m in migi:
        ma = max(ma, m)
        migimax.append(ma)

    hidarimax = [0]
    ma = 0
    for m in hidari:
        ma = max(ma, m)
        hidarimax.append(ma)

    for i in range(N):
        ans = max(ans, migi[i + 1] - XV[i][0] + hidarimax[N - i - 1])

    for i in range(N):
        ans = max(ans, hidari[i + 1] - (C - XV[-i - 1][0]) + migimax[N - i - 1])

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

xv = [(0, 0)]
for i in range(N):
    x, v = map(float, input().split())
    xv.append((x, v))
sumA = np.zeros(N+1, dtype=float)
sumB = np.zeros(N+1, dtype=float)

xv.sort(key=lambda tup:tup[0])
for i in range(N):
    sumA[i+1] = sumA[i] + xv[i+1][1]
    sumB[i+1] = sumB[i] + xv[N-i][1]

for i in range(N):
    if sumA[i+1] < xv[i+1][0]: sumA[i+1] = 0
    else: sumA[i+1] -= xv[i+1][0]
    if sumB[i+1] < C - xv[N-i][0]: sumB[i+1] = 0
    else: sumB[i+1] -= C - xv[N-i][0]

ans = 0
for i in range(N):
    #when to turn back?
    valB = -xv[i][0] + max(sumB[:N-i+1])
    if valB < 0:
        ans = max(ans, sumA[i])
    else:
        ans = max(ans, sumA[i] + valB)

print(int(ans))

Submission status: Wrong Answer

Solution code:
N,C = map(int,input().split())
S = []
for _ in range(N):
    x,v = map(int,input().split())
    S.append([x,v])
S.sort()
A = [[0,0]]
B = [[0,0]]
for i in range(N):
    A.append([S[i][0],A[-1][1]+S[i][1]])
    B.append([C-S[N-i-1][0],B[-1][1]+S[N-i-1][1]])
g = [[0,0]]
for i in range(1,N+1):
    if g[-1][0]<=A[i][1]-A[i][0]:
        g.append([A[i][1]-A[i][0],A[i][0]])
    else:
        g.append(g[-1])
g = g[::-1]
g2 = [[0,0]]
for i in range(1,N+1):
    if g2[-1][0]<=A[i][1]-2*A[i][0]:
        g2.append([A[i][1]-2*A[i][0],A[i][0]])
    else:
        g2.append(g2[-1])
g2 = g2[::-1]
ans = 0
for i in range(N):
    ans = max(ans,B[i][1]-2*B[i][0]+g[i][0],B[i][1]-B[i][0]+g2[i][0])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
l=[[0,0,0]]
r=[[0,0,0]]
n,c=map(int,input().split())
for i in range(n):
	x,v=map(int,input().split())
	r.append([x,v])
	l.append([c-x,v])
r.sort()
l.sort()
now=0
for i in range(n):
	now+=r[i+1][1]
	r[i+1].append(max(now-r[i+1][0],r[i][2]))
	if r[i+1][2]==r[i][2]:
		r[i+1][0]=r[i][0]
now=0
for i in range(n):
	now+=l[i+1][1]
	l[i+1].append(max(now-l[i+1][0],l[i][2]))
	if l[i+1][2]==l[i][2]:
		l[i+1][0]=l[i][0]
ans=0
for i in range(n+1):
	a=l[i][0]
	b=r[i][0]
	ans=max(l[i][2]+r[n-i][2]-min(a,b),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
l=[[0,0,0]]
r=[[0,0,0]]
n,c=map(int,input().split())
for i in range(n):
	x,v=map(int,input().split())
	r.append([x,v])
	l.append([c-x,v])
r.sort()
l.sort()
now=0
for i in range(n):
	now+=r[i+1][1]
	r[i+1].append(max(now-r[i+1][0],r[i][2]))
now=0
for i in range(n):
	now+=l[i+1][1]
	l[i+1].append(max(now-l[i+1][0],l[i][2]))
ans=0
for i in range(n+1):
	a=l[i][0]
	b=r[i][0]
	ans=max(l[i][2]+r[n-i][2]-min(a,b),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
#import sys
#import numpy as np
import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
#import bisect
n,c=map(int,input().split())
xv= [map(int, input().split()) for _ in range(n)]
x, v = [list(i) for i in zip(*xv)]
calolic=[0]*(n+1)
l=[0]*(n+1)
l[1]=v[0]
calolic[1]=max(0,l[1]-x[0])
for i in range(2,n+1):
    l[i]=l[i-1]+v[i-1]
    res=l[i]-x[i-1]
    if res>calolic[i-1]:
        calolic[i]=res
    else:
        calolic[i]=calolic[i-1]
ans=0
for i in range(n+1):
    if i==0:
        ans=max(ans,calolic[n])
    else:
        ans=max(ans,calolic[i-1]+l[-1]-l[i-1]-2*(c-x[i-1]))
calolic=[0]*(n+1)
l=[0]*(n+1)
l[1]=v[-1]
calolic[1]=max(0,l[1]-c+x[-1])
for i in range(2,n+1):
    l[i]=l[i-1]+v[n-i]
    res=l[i]-c+x[n-i]
    if res>calolic[i-1]:
        calolic[i]=res
    else:
        calolic[i]=calolic[i-1]

for i in range(n+1):
    if i==0:
        ans=max(ans,calolic[n])
    else:
        ans=max(ans,calolic[n-i]+l[i]-2*x[i-1])
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

n,c = map(int,input().split())
li = [[0,0]]

for _ in range(n):
    x,v = map(int,input().split())
    li.append([x,v])

# 中橋君が時計回りか反時計回りかを決める

# 時計回りの時どこの地点まで食べるかを決める(累積和)
l = [0]+[li[i][1]-(li[i][0]-li[i-1][0]) for i in range(1,n+1)]
l = list(accumulate(l))

max_l = max(l)

li = li[::-1]
# 半時計回りの時どこの地点まで食べるかを決める
r = [0]+[li[i][1]-((c-li[i][0])-(c-li[i-1][0])) for i in range(1,n+1)]
r = list(accumulate(r))

max_r = max(r)

print(max(max_l,max_r))

Submission status: Wrong Answer

Solution code:
N, C = map(int,input().split())
X = []
V = []
for _ in range(N):
    x, v = map(int,input().split())
    X.append(x)
    V.append(v)

A = V[:]
B = V[::-1]

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

P = []
Q = []

for i in range(N):
    P.append(max(0, A[i] - X[i] * 2))
    Q.append(max(0, B[i] - (C - X[N-i-1]) * 2))

for i in range(N-1):
    P[i+1] = max(P[i], P[i+1])
    Q[i+1] = max(Q[i], Q[i+1])

ans = 0

for i in range(N-1):
    ans = max(ans, A[i] + Q[N-i-2] - X[i])
    ans = max(ans, B[i] + P[N-i-2]- (C - X[N-i-1]))

print(ans)

Submission status: Wrong Answer

Solution code:
n,c = map(int,input().split())
xv = [[int(i) for i in input().split()] for j in range(n)]

jun1 = [0]*n
jun2 = [0]*n

rev1 = [0]*n
rev2 = [0]*n

tmpj = 0
oldj = 0

tmpr = 0
oldr = 0

rv = [[0 for i in range(2)] for j in range(n)]

for i in range(n):
    rv[i][0] = c - xv[n-1-i][0]
    rv[i][1] = xv[n-1-i][1]

for i in range(n):
    #old += xv[i][1]
    tj = xv[i][1] - (xv[i][0]-oldj)
    tmpj += tj
    oldj = xv[i][0]
    jun1[i] = tmpj
    
    
    tr = rv[i][1] - (rv[i][0]-oldr)
    tmpr += tr
    oldr = rv[i][0]
    rev1[i] = tmpr

tmpj = 0
oldj = 0

tmpr = 0
oldr = 0
   
for i in range(n):
    tj = xv[i][1] - (xv[i][0]-oldj)*2
    tmpj += tj
    oldj = xv[i][0]
    jun2[i] = tmpj
    
    tr = rv[i][1] - (rv[i][0]-oldr)*2
    tmpr += tr
    oldr = rv[i][0]
    rev2[i] = tmpr
    
tmp = 0    
for i in range(n):
    tmp = max(tmp,jun1[i])
    jun1[i] = tmp
    
tmp = 0
for i in range(n):
    tmp = max(tmp,rev1[i])
    rev1[i] = tmp

#print(jun2,rev1,rev2,jun1)
ans = 0

for i in range(n):
    if i == n-1:
        ans = max(ans,jun2[i],rev2[i])
        break
    ans = max(max(0,jun2[i])+rev1[n-i-2],ans)
    ans = max(max(0,rev2[i])+jun1[n-i-2],ans)

print(ans)

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, c = mi()
    place = []
    inv_place = []
    value = []
    for _ in range(n):
        x, v = mi()
        place.append(x)
        inv_place.append(c - x)
        value.append(v)
    accum_val = list(accumulate(value))
    counter_accum_val = list(reversed(list(accumulate(reversed(value)))))

    clockwise = [[] for _ in range(n)]
    counter_clockwise = [[] for _ in range(n)]

    for i in range(n):
        clockwise[i] = [accum_val[i] - place[i], accum_val[i] - 2 * place[i]]
        counter_clockwise[i]= [counter_accum_val[i] - inv_place[i], counter_accum_val[i] - 2 * inv_place[i]]
    
    # import pprint
    # pprint.pprint(clockwise)
    # pprint.pprint(counter_clockwise)
    # print('')

    # 時計回りのみ -> clockwise の [0] の max
    # 反時計回りのみ -> counter_clockwise の [0] の max
    max_memo = - inf
    max_memo_clock_0 = [0] * n
    for i in range(n):
        max_memo = max(max_memo, clockwise[i][0])
        max_memo_clock_0[i] = max_memo
    
    max_memo = -inf
    max_memo_clock_1 = [0] * n
    for i in range(n):
        max_memo = max(max_memo, clockwise[i][1])
        max_memo_clock_1[i] = max_memo

    max_memo = - inf
    max_memo_counter_clock_0 = [0] * n
    for i in range(n-1, -1, -1):
        max_memo = max(max_memo, counter_clockwise[i][0])
        max_memo_counter_clock_0[i] = max_memo
    
    max_memo = -inf
    max_memo_counter_clock_1 = [0] * n
    for i in range(n-1, -1, -1):
        max_memo = max(max_memo, counter_clockwise[i][1])
        max_memo_counter_clock_1[i] = max_memo
    
    # print(max_memo_clock_0)
    # print(max_memo_clock_1)
    # print(max_memo_counter_clock_0)
    # print(max_memo_counter_clock_1)
    ans = max(max(max_memo_clock_0), max(max_memo_clock_1), 0)
    # print(ans)

    for i in range(n-1):
        ans = max(ans, clockwise[i][0] + max_memo_counter_clock_1[i+1])
    for i in range(n-1, 0, -1):
        ans = max(ans, counter_clockwise[i][0] + max_memo_clock_1[i-1])

    
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, c = mi()
    place = []
    inv_place = []
    value = []
    for _ in range(n):
        x, v = mi()
        place.append(x)
        inv_place.append(c - x)
        value.append(v)
    accum_val = list(accumulate(value))
    counter_accum_val = list(reversed(list(accumulate(reversed(value)))))

    clockwise = [[] for _ in range(n)]
    counter_clockwise = [[] for _ in range(n)]

    for i in range(n):
        clockwise[i] = [accum_val[i] - place[i], accum_val[i] - 2 * place[i]]
        counter_clockwise[i]= [counter_accum_val[i] - inv_place[i], counter_accum_val[i] - 2 * inv_place[i]]
    
    # import pprint
    # pprint.pprint(clockwise)
    # pprint.pprint(counter_clockwise)
    # print('')

    # 時計回りのみ -> clockwise の [0] の max
    # 反時計回りのみ -> counter_clockwise の [0] の max
    max_memo = - inf
    max_memo_clock_0 = [0] * n
    for i in range(n):
        max_memo = max(max_memo, clockwise[i][0])
        max_memo_clock_0[i] = max_memo
    
    max_memo = -inf
    max_memo_clock_1 = [0] * n
    for i in range(n):
        max_memo = max(max_memo, clockwise[i][1])
        max_memo_clock_1[i] = max_memo

    max_memo = - inf
    max_memo_counter_clock_0 = [0] * n
    for i in range(n):
        max_memo = max(max_memo, counter_clockwise[i][0])
        max_memo_counter_clock_0[i] = max_memo
    
    max_memo = -inf
    max_memo_counter_clock_1 = [0] * n
    for i in range(n-1, -1, -1):
        max_memo = max(max_memo, counter_clockwise[i][1])
        max_memo_counter_clock_1[i] = max_memo
    
    # print(max_memo_clock_0)
    # print(max_memo_clock_1)
    # print(max_memo_counter_clock_0)
    # print(max_memo_counter_clock_1)
    ans = max(max(max_memo_clock_0), max(max_memo_clock_1), 0)
    # print(ans)

    for i in range(n-1):
        ans = max(ans, clockwise[i][0] + max_memo_counter_clock_1[i+1])
    for i in range(n-1, 0, -1):
        ans = max(ans, counter_clockwise[i][0] + max_memo_clock_1[i-1])

    
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
x = [None] * N
v = [None] * N
for i in range(N):
    x[i], v[i] = map(int, input().split())

a0 = [None] * N
a = v[0] - x[0]
a0[0] = max(0, a)
for i in range(1, N):
    a += v[i] - (x[i] - x[i - 1])
    a0[i] = max(a, a0[i - 1])

a1 = [None] * N
a = v[N - 1] - (C - x[N - 1])
a1[0] = max(0, a)
for i in range(1, N):
    a += v[N - 1 - i] - ((C - x[N - 1 - i]) - (C - x[N - 1 - (i - 1)]))
    a1[i] = max(a, a1[i - 1])

result = max(a0[N - 1], a1[N - 1])
for i in range(N):
    result = max(result, a0[i] - x[i] + a1[N - 1 - (i + 1)])
for i in range(N):
    result = max(result, a1[i] - (C - x[N - 1 - i]) + a0[N - 1 - (i + 1)])
print(result)

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
x = [None] * N
v = [None] * N
for i in range(N):
    x[i], v[i] = map(int, input().split())

a0 = [None] * N
a = v[0] - x[0]
a0[0] = max(0, a)
for i in range(1, N):
    a += v[i] - (x[i] - x[i - 1])
    a0[i] = max(a, a0[i - 1])

a1 = [None] * N
a = v[N - 1] - (C - x[N - 1])
a1[0] = max(0, a)
for i in range(1, N):
    a += v[N - 1 - i] - ((C - x[N - 1 - (i - 1)]) - (C - x[N - 1 - i]))
    a1[i] = max(a, a1[i - 1])

result = max(a0[N - 1], a1[N - 1])
for i in range(N):
    result = max(result, a0[i] - x[i] + a1[N - 1 - (i + 1)])
for i in range(N):
    result = max(result, a1[i] - (C - x[N - 1 - i]) + a0[N - 1 - (i + 1)])
print(result)

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
x = [None] * N
v = [None] * N
for i in range(N):
    x[i], v[i] = map(int, input().split())

a0 = [None] * N
a = v[0] - x[0]
a0[0] = max(0, a)
for i in range(1, N):
    a += v[i] - (x[i] - x[i - 1])
    a0[i] = max(a, a0[i - 1])

a1 = [None] * N
a = v[N - 1] - (C - x[N - 1])
a1[0] = max(0, a)
for i in range(1, N):
    print(a, (C - x[N - 1 - (i - 1)]), (C - x[N - 1 - i]))
    a += v[N - 1 - i] - ((C - x[N - 1 - (i - 1)]) - (C - x[N - 1 - i]))
    a1[i] = max(a, a1[i - 1])

result = max(a0[N - 1], a1[N - 1])
for i in range(N):
    result = max(result, a0[i] - x[i] + a1[N - 1 - (i + 1)])
for i in range(N):
    result = max(result, a1[i] - (C - x[N - 1 - i]) + a0[N - 1 - (i + 1)])
print(result)

Submission status: Wrong Answer

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

x,v=[0]*N,[0]*N
for i in range(N):
    x[i],v[i]=map(int,input().split())

R=[0]*N
calorie=0
for i in range(N):
    calorie+=v[i]
    R[i]=calorie-x[i]

L=[0]*N
y=[0]*N
calorie=0
for i in range(N-1,-1,-1):
    calorie+=v[i]
    y[i]=C-x[i]
    L[i]=calorie-y[i]
L.append(0)
y.append(0)
R=[0]+R
x=[0]+x

MAX=0
d=0
for i in range(N,-1,-1):
    if L[i]>=MAX:
        MAX=L[i]
        d=y[i]
    else:
        L[i]=MAX
        y[i]=d

ans=0
for i in range(N):
    val=R[i]+L[i]-min(x[i],y[i])
    ans=max(ans,val)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, C = map(int, input().split())
X = []
V = []
for n in range(N):
    x, v = map(int,input().split())
    X.append(x)
    V.append(v)
Xr = X[::-1]
Vr = V[::-1]
Xl = [0] + X
Vl = [0] + V
Xr = [0] + [C-x for x in Xr] # 逆に回るのでCから引く
Vr = [0] + Vr

Vl = list(itertools.accumulate(Vl)) # xは累積した値なので、vも累積和に統一
Vr = list(itertools.accumulate(Vr))

def update_mx(ls):
    mx = 0
    for i in range(len(ls)):
        mx = max(mx, ls[i])
        ls[i] = mx
    return ls

def create(V,X,k):
    ls = []
    for n in range(N+1):
        ls.append(V[n]-k*X[n]) # 往復する場合はk=2
    return update_mx(ls)

L = create(Vl,Xl,1) # 最良の値[左端として許容される位置]（片道）
Lt = create(Vl,Xl,2) # 最良の値[左端として許容される位置]（往復）
R = create(Vr,Xr,1)
Rt = create(Vr,Xr,2)

ans = 0
for n in range(N+1):
    print (n,N-n)
    ans = max(ans, Lt[n] + R[N-n])
    ans = max(ans, Rt[n] + L[N-n])
print (ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, C = map(int, input().split())
X = []
V = []
for n in range(N):
    x, v = map(int,input().split())
    X.append(x)
    V.append(v)
X_r = X[::-1]
V_r = V[::-1]
X = [0] + X
V = [0] + V
X_r = [0] + [C-x for x in X_r]
V_r = [0] + V_r

#cx = list(itertools.accumulate(X))
cv = list(itertools.accumulate(V))
#cxr = list(itertools.accumulate(X_r))
cvr = list(itertools.accumulate(V_r))

# print (X)
# print (X_r)
# print (cv)
# print (cvr)

# L = []
# for i in range(N+1):
#     L.append(cv[i]-X[i])
# R = []
# for i in range(N+1):
#     R.append(cvr[i]-X_r[i])

# print (L,R)
mx = 0
for l in range(N):
    for r in range(N-l):
        a = -2*X[l]+cv[l]+cvr[r]-X_r[r]
        mx = max(mx,a)
        a = -2*X_r[l]+cv[r]+cvr[l]-X[r]
        mx = max(mx,a)
print (mx)