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: Accepted

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

# 右まわり
right = [[0,0]]
for i in range(n):
    right.append([xv[i][0],right[-1][1]+xv[i][1]])

right_best =[0]
for i in range(1,len(right)):
    right_best.append(max(right[i][1]-right[i][0],right_best[-1]))

right_return_best = [0]
for i in range(1,len(right)):
    right_return_best.append(max(right[i][1]-right[i][0]*2,right_return_best[-1]))


# 左回り
for i in range(n):
    xv[i][0]=c-xv[i][0]
xv.reverse()

left = [[0,0]]
for i in range(n):
    left.append([xv[i][0],left[-1][1]+xv[i][1]])

left_best =[0]
for i in range(1,len(left)):
    left_best.append(max(left[i][1]-left[i][0],left_best[-1]))

left_return_best = [0]
for i in range(1,len(left)):
    left_return_best.append(max(left[i][1]-left[i][0]*2,left_return_best[-1]))


# 答え計算
ans = 0
for i in range(n+1):
    ans = max(ans,left_best[i]+right_return_best[n-i], right_best[i]+left_return_best[n-i])

print(ans)

Submission status: Accepted

Solution code:
N,C = map(int, input().split())
L = [[int(l) for l in input().split()] for _ in range(N)]

right = [0]*N
right[0] = L[0][1] - L[0][0]
for i in range(N-1):
    right[i+1] = right[i] + L[i+1][1] - (L[i+1][0] - L[i][0])

left = [0]*N
left[N-1] = L[N-1][1] - (C - L[N-1][0])
for i in range(N-1, 0, -1):
    left[i-1] = left[i] + L[i-1][1] - (L[i][0] - L[i-1][0])

Right = [0]*(N+1)
for i in range(N):
    Right[i+1] = max(right[i], Right[i])
Left = [0]*(N+1)
for i in range(N, 0, -1):
    Left[i-1] = max(left[i-1], Left[i])

ans = max(0, max(right), max(left))
for i in range(N-1, -1, -1):
    ans = max(ans, Right[i] + left[i] - (C - L[i][0]))
for i in range(N):
    ans = max(ans, Left[i+1] + right[i] - L[i][0])

print(ans)

Submission status: Accepted

Solution code:
n,c = map(int, input().split())
s = [tuple(map(int, input().split())) for _ in range(n)]
lx = [0] + [x[0] for x in s]
rx = [0] + [c-x[0] for x in s[::-1]]
lv = [0] + [x[1] for x in s]
rv = [0] + [x[1] for x in s[::-1]]
lg = [0]*(n+1)
rg = [0]*(n+1)
for i in range(1,n+1):
  lv[i] += lv[i-1]
  rv[i] += rv[i-1]
  lg[i] = lv[i] - lx[i]
  rg[i] = rv[i] - rx[i]
  if lg[i] < lg[i-1]: lg[i] = lg[i-1]
  if rg[i] < rg[i-1]: rg[i] = rg[i-1]

ans = 0
for i in range(n+1):
  ls = lg[i] + rg[n-i] - lx[i]
  rs = rg[i] + lg[n-i] - rx[i]
  if ls > ans: ans = ls
  if rs > ans: ans = rs
print(ans)

Submission status: Accepted

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

R = [(0,0)]
L = [(0,0)]

for s in sushi:
    R.append((s[0],R[-1][1]+s[1]))

for s in sushi[::-1]:
    L.append((C-s[0],L[-1][1]+s[1]))

R_reversible = [False for _ in range(N+1)]
L_reversible = [False for _ in range(N+1)]

for i in range(N+1):
    if R[i][1]-2*R[i][0] >= 0:
        R_reversible[i] = True
    if L[i][1]-2*L[i][0] >= 0:
        L_reversible[i] = True
        
R_dif = [0 for _ in range(N+1)]
L_dif = [0 for _ in range(N+1)]

for i in range(N+1):
    R_dif[i] = R[i][1]-R[i][0]
    L_dif[i] = L[i][1]-L[i][0]
    
rmax = 0
lmax = 0

for i in range(N+1):
    if rmax > R_dif[i]:
        R_dif[i] = rmax
    if lmax > L_dif[i]:
        L_dif[i] = lmax
    rmax = max(rmax,R_dif[i])
    lmax = max(lmax,L_dif[i])
    
ans = max(rmax,lmax)

for i in range(1,N+1):
    if R_reversible[i]:
        ans = max(ans,R[i][1]-2*R[i][0]+L_dif[N-i])
    if L_reversible[i]:
        ans = max(ans,L[i][1]-2*L[i][0]+R_dif[N-i])

print(ans)

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
L=R=Rmax=0
x=[0]*n
v=[0]*n
for i in range(n):
  xx,vv=map(int,input().split())
  x[i]=xx
  v[i]=vv
  L+=vv
ans=L-x[-1]
for i in reversed(range(n)):
  L-=v[i]
  R+=v[i]
  Rmax=max(Rmax,R-(c-x[i]))
  ans=max(ans,L-(x[i-1]*2 if i>0 else 0)+Rmax)
Lmax=0
for i in range(n):
  L+=v[i]
  R-=v[i]
  Lmax=max(Lmax,L-x[i])
  ans=max(ans,R-((c-x[i+1])*2 if i<n-1 else 0)+Lmax)
print(ans)

Submission status: Accepted

Solution code:
def main():
    from collections import namedtuple

    Dish = namedtuple('Dish', 'idx x v')

    n, c = map(int, input().split())

    ds = []
    for i in range(n):
        x, v = map(int, input().split())
        ds.append(Dish(idx=i, x=x, v=v))

    gol = [0] * n  # 時計回りの最大値
    s = 0
    ma = 0
    for d in ds:
        s += d.v
        ma = max(ma, s - d.x)
        gol[d.idx] = ma

    gor = [0] * n  # 反時計回りの最大値
    s = 0
    ma = 0
    for d in reversed(ds):
        s += d.v
        ma = max(ma, s - (c - d.x))
        gor[d.idx] = ma

    gol0 = [0] * n  # 時計回りから0に戻ったときのカロリー
    for d in reversed(ds):
        gol0[d.idx] = gol[d.idx] - d.x

    gor0 = [0] * n  # 反時計回りから0に戻ったときのカロリー
    for d in reversed(ds):
        gor0[d.idx] = gor[d.idx] - (c - d.x)

    ret = max(max(gol), max(gor))
    for l in range(n - 1):
        t = gol0[l] + gor[l + 1]
        ret = max(ret, t)

    for r in range(n - 1, 0, -1):
        t = gor0[r] + gol[r - 1]
        ret = max(ret, t)

    print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate
from operator import sub
N, C = map(int, input().split())
X, V = map(list, zip(*[tuple(map(int, input().split())) for _ in range(N)]))
VA = list(accumulate([0]+V))
VR = list(accumulate([0]+V[::-1]))
XR = [0]+list(map(lambda x:C-x, X[::-1]))
X = [0]+X
VA = list(accumulate(map(sub, VA, X), max))
VR = list(accumulate(map(sub, VR, XR), max))
print(max(VA[i]+VR[N-i]-min(X[i], XR[N-i]) for i in range(N+1)))

Submission status: Accepted

Solution code:
from bisect import bisect_left
def main():
    n,c = map(int,input().split())
    xv = [tuple(map(int,input().split())) for _ in range(n)]
    xvr = []
    for i in range(n):
        j = n-i-1
        xvr.append((c-xv[j][0],xv[j][1]))
    xvv = [0]*n
    xvv[0] = xv[0]
    for i in range(1,n):
        xvv[i] = (xv[i][0],xvv[i-1][1]+xv[i][1])
    xvrv = [0]*n
    xvrv[0] = xvr[0]
    for i in range(1,n):
        xvrv[i] = (xvr[i][0],xvrv[i-1][1]+xvr[i][1])
    xvm = [(0,0)]
    xvmi = [0]
    for i in xvv:
        j = xvm[-1]
        if i[1]-i[0] >= j[1]-j[0]:
            xvm.append(tuple(i))
            xvmi.append(i[0])
    xvrm = [(0,0)]
    xvrmi = [0]
    for i in xvrv:
        j = xvrm[-1]
        if i[1]-i[0] >= j[1]-j[0]:
            xvrm.append(tuple(i))
            xvrmi.append(i[0])
    ans = max([xvm[-1][1]-xvm[-1][0],xvrm[-1][1]-xvrm[-1][0]])
    for i in xvm:
        t = c-i[0]
        idx = bisect_left(xvrmi,t)-1
        tans = xvrm[idx][1]-xvrm[idx][0]+i[1]-i[0]*2
        if tans > ans:
            ans = tans
    for i in xvrm:
        t = c-i[0]
        idx = bisect_left(xvmi,t)-1
        tans = xvm[idx][1]-xvm[idx][0]+i[1]-i[0]*2
        if tans > ans:
            ans = tans
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans, value = 0, 0
for i in L:
    cost = i[0]
    value += i[1]
    ans = max(ans, value - cost)

value = 0
for i in L[::-1]:
    cost = C - i[0]
    value += i[1]
    ans = max(ans, value - cost)

rList = [0] * (N + 1)
value = 0
for i in range(N):
    sushi = L[i]
    cost = sushi[0]
    value += sushi[1]
    rList[i + 1] = max(rList[i], value - cost)

lList = [0] * (N + 1)
value = 0
for i in range(N):
    sushi = L[-1-i]
    cost = C - sushi[0]
    value += sushi[1]
    lList[i + 1] = max(lList[i], value - cost)

value = 0
for i in range(N):
    sushi = L[i]
    cost = sushi[0]
    value += sushi[1]
    ans = max(ans, value - cost * 2 + lList[N - (i + 1)])

value = 0
for i in range(N):
    sushi = L[-1-i]
    cost = C - sushi[0]
    value += sushi[1]
    ans = max(ans, value - cost * 2 + rList[N - (i + 1)])

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,C=map(int,input().split())
x=[]
v=[0]
for i in range(N):
    xx,vv=map(int,input().split())
    x.append(xx)
    v.append(v[i]+vv)

cw=[0]
for i in range(N):
    cw.append(max(cw[i],v[i+1]-x[i]))

ccw=[0]
for i in range(N):
    ccw.append(max(ccw[i],v[N]-v[N-i-1]-(C-x[-i-1])))

cw_ccw=0
for i in range(N-1):
    cw_ccw=max(cw_ccw,v[i+1]-x[i]*2+ccw[N-i-1])

ccw_cw=0
for i in range(N-1):
    ccw_cw=max(ccw_cw,v[N]-v[N-i-1]-(C-x[-i-1])*2+cw[N-i-1])
#print(cw,ccw)
#print(list([cw_ccw,ccw_cw]))
print(max(cw+ccw+list([cw_ccw,ccw_cw])))

Submission status: Accepted

Solution code:
from itertools import accumulate

N, C  = map(int, input().split())
x_cw = []   # 時計
x_acw = []  # 反時計
v_cw = []     # 寿司
for i in range(N):
    x,v = map(int, input().split())
    x_cw.append(x)
    v_cw.append(v)
v_acw = v_cw[::-1]
x_acw = [C - x for x in x_cw[::-1]]
x_cw = [0] + x_cw
x_acw = [0] + x_acw
# print(x_cw)
# print(x_acw)
v_cw1 = [v_cw[i]-(x_cw[i+1]-x_cw[i]) for i in range(N)]        # 時計回り折り返さない
v_cw2 = [v_cw[i]-2*(x_cw[i+1]-x_cw[i]) for i in range(N)]     # 時計回り折返しが入るとき
v_acw1 = [v_acw[i]-(x_acw[i+1]-x_acw[i]) for i in range(N)]        # 反時計折り返さない
v_acw2 = [v_acw[i]-2*(x_acw[i+1]-x_acw[i]) for i in range(N)]     # 反時計折返しがはいるとき

acc_cw1 = list(accumulate(v_cw1))
acc_acw1 = list(accumulate(v_acw1))
acc_cw2 = list(accumulate(v_cw2))
acc_acw2 = list(accumulate(v_acw2))

acc_acw1 = acc_acw1[::-1]
acc_cw1 = acc_cw1[::-1]


max_cw2 = []
m = 0
# 右スタート、左バックパターン
for c in acc_cw2:
    m = max(c,m)
    max_cw2.append(m)
ans_cw = acc_acw1[0] #初期値
for i in range(1,N):
    ans_cw = max(ans_cw, max_cw2[i-1]+acc_acw1[i])

# 左スタート、右バックパターン
m = 0
max_acw2 = []
for c in acc_acw2:
    m = max(c, m)
    max_acw2.append(m)
ans_acw = acc_cw1[0] # 初期値 
for i in range(1,N):
    ans_acw = max(ans_acw, max_acw2[i-1]+acc_cw1[i])
ans = max(ans_acw,ans_cw)
print(max(0,ans))

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
x=[];v=[]
for i in range(N):
    xi,vi=map(int,input().split())
    x.append(xi);v.append(vi)

# 時計回りにj番目までの寿司を（全部）食べて初期位置まで戻った場合の差し引き摂取カロリー
rc=[v[0]-2*x[0]]
for j in range(1,N):
    rc.append(rc[-1]+v[j]-2*(x[j]-x[j-1]))
# print(f'rc:{rc}') #DB
# 時計回りにj番目までの寿司を（必ずしも最後までではなく）食べて初期位置まで戻った場合の差し引き摂取カロリーの最大値
mrc=[rc[0]]
for j in range(1,N):
    mrc.append(max(mrc[-1],rc[j]))
# print(f'mrc:{mrc}')
# 反時計回りにN-1-i番目までの寿司を（全部）食べて退店した場合の差し引き摂取カロリー
ca=[v[N-1]-(C-x[N-1])]
for i in range(1,N):
    ca.append(ca[-1]+v[N-1-i]-(x[N-i]-x[N-1-i]))
# print(f'ca:{ca}')
# 反時計回りにN-1-i番目までの寿司を（必ずしも最後までではなく）食べて退店した場合の差し引き摂取カロリーの最大値
mca=[ca[0]]
for i in range(1,N):
    mca.append(max(mca[-1],ca[i]))
# print(f'mca:{mca}')


# 反時計回りにN-1-j番目までの寿司を食べて初期位置まで戻った場合の差し引き摂取カロリー
ra=[v[N-1]-2*(C-x[N-1])]
for j in range(1,N):
    ra.append(ra[-1]+v[N-1-j]-2*(x[N-j]-x[N-1-j]))
# print(f'ra:{ra}')
mra=[ra[0]]
for j in range(1,N):
    mra.append(max(mra[-1],ra[j]))
# print(f'mra:{mra}')

# 時計回りにi番目までの寿司を食べて退店した場合の差し引き摂取カロリー
cc=[v[0]-x[0]]
for i in range(1,N):
    cc.append(cc[-1]+v[i]-(x[i]-x[i-1]))
# print(f'cc:{cc}')
mcc=[cc[0]]
for i in range(1,N):
    mcc.append(max(mcc[-1],cc[i]))
# print(f'mcc:{mcc}')

ans=0
if N==1:
    ans=max(ans,v[0]-x[0],v[0]-(C-x[0]))
else:
    # まず時計回りに進み，初期位置まで戻って反時計回りに進む場合
    for i in range(N-1):
        ans=max(ans,mrc[i]+mca[N-2-i])
    # 時計回りに全部食べてから初期位置に戻る(i=N-1)場合は考慮する必要がない。
    # そのような食べ方は，反時計回りに進まず，時計回りに全部食べてそのまま退店する場合よりも常に差し引き摂取カロリーが少ない。

    # 時計回りに進み，そのまま退店する場合
    for i in range(N):
        ans=max(ans,mcc[i])

    # まず反時計回りに進み，初期位置まで戻って時計回りに進む場合
    for i in range(N-1):
        ans=max(ans,mra[i],mra[i]+mcc[N-2-i])
    
    # 反時計回りに進み，そのまま退店する場合
    for i in range(N):
        ans=max(ans,mca[i])

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate as f

def main():
	n, c, *L = map(int, open(0).read().split())
	acc = [a - x for x, a in zip(L[::2], f(L[1::2]))]
	acc_max = list(f(acc, max))[::-1]
	R = L[::-1]
	rev = [a - (c - x) for x, a in zip(R[1::2], f(R[::2]))]
	rev_max = list(f(rev, max))[::-1]
	p = max([a - b + d for a, b, d in zip(acc, L[::2], rev_max[1:])]+[0])
	q = max([a - (c - b) + d for a, b, d in zip(rev, R[1::2], acc_max[1:])]+[0])
	r = max(0, acc_max[0], rev_max[0])
	print(max(p, q, r))

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
from itertools import*
n,c,*L=map(int,open(0).read().split())
acc=[a-x for x,a in zip(L[::2],accumulate(L[1::2]))]
acc_max=list(accumulate([0]+acc,max))
R=L[::-1]
rev=[a-(c-x) for x,a in zip(R[1::2],accumulate(R[::2]))]
rev_max=list(accumulate([0]+rev,max))
p=max(rev_max[n-i-1]+a-b for i,(a,b) in enumerate(zip(acc,L[::2])))
q=max(acc_max[n-i-1]+a-(c-b) for i,(a,b) in enumerate(zip(rev,R[1::2])))
r=max(0,acc_max[-1],rev_max[-1])
print(max(p,q,r))

Submission status: Accepted

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

R = [[0 for _ in range(4)] for _ in range(N)]
L = [[0 for _ in range(4)] for _ in range(N)]

for i in range(N):
  R[i][3] = 0
  L[i][3] = 0

for i in range(N):
  R[i][0] = XV[i][0]
  R[i][1] = XV[i][1]
  L[i][0] = C - XV[i][0]
  L[i][1] = XV[i][1]
L.sort()

for i in range(N):
  R[i][2] = R[i - 1][2] + R[i][1]
  L[i][2] = L[i - 1][2] + L[i][1]
for i in range(N):
  R[i][2] -= R[i][0]
  L[i][2] -= L[i][0] 
  R[i][3] = max(R[i - 1][3], R[i][2])
  L[i][3] = max(L[i - 1][3], L[i][2])
#print("R:", R)
#print("L:", L)

answer = []
for i in range(N):
  if i != N - 1:
    answer.append(R[i][2] + max(L[N - 2 - i][3] - R[i][0], 0))
  else:
    answer.append(R[i][2])

L, R = R, L
for i in range(N):
  if i != N - 1:
    answer.append(R[i][2] + max(L[N - 2 - i][3] - R[i][0], 0))
  else:
    answer.append(R[i][2])

answer = max(answer)
print(answer if answer > 0 else 0)

Submission status: Accepted

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

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

# 左右について、片側に進んだ場合の累積max
accL = [0] * (N+1)
cur = 0
for i in range(1, N+1):
    x, v = L[i]
    dist = x - L[i-1][0]
    cur +=  v - dist
    accL[i] = max(accL[i-1], cur)
accR = [0] * (N+1)
cur = 0
for i in range(1, N+1):
    x, v = R[i]
    dist = x - R[i-1][0]
    cur +=  v - dist
    accR[i] = max(accR[i-1], cur)

ans = max(max(accL), max(accR))
# 両側に行く場合を確認
for i in range(N+1):
    # 先に左に行って、戻って右へ
    ans = max(ans, accL[i] - L[i][0] + accR[N-i])
    # 先に右に行って、戻って左へ
    ans = max(ans, accR[i] - R[i][0] + accL[N-i])
print(ans)

Submission status: Accepted

Solution code:
# D - Static Sushi

import sys
import numpy as np

N, C = map(int, sys.stdin.buffer.readline().split())
x, v = [], []
for _ in range(N):
    tmp, tmp2 = map(int, sys.stdin.buffer.readline().split())
    x.append(tmp)
    v.append(tmp2)

x = np.array(x, np.int64)
v = np.array(v, np.int64)
v_cum = v.cumsum()
tx = np.flipud(x)
tv_cum = np.flipud(v).cumsum()
left_cum = v_cum - x

right_cum = tv_cum - np.flipud(C - x)
right_cum_max = np.maximum.accumulate(right_cum)

right_cum_return = right_cum - np.flipud(C - x)
right_cum_return_max = np.maximum.accumulate(right_cum_return)

ans = max(0, np.max(left_cum), np.max(right_cum))

for first_abandon_idx in range(1, N):
    ans = max(ans, left_cum[first_abandon_idx-1] - x[first_abandon_idx-1] + right_cum_max[N-1 - first_abandon_idx])
    ans = max(ans, left_cum[first_abandon_idx-1] + right_cum_return_max[N-1 - first_abandon_idx])

print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase

#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
#show_flg=True

n,c=LI()
s=[]

for i in range(n):
    x,v=LI()
    s.append((x,v))

show(c,s)
def solve(s):
    show('s',s)
    rt=-inf
    n=len(s)
    av=[0]
    for i in range(n):
        av.append(av[-1]+s[i][1])
    
    rav=[0]
    for i in range(n):
        rav.append(rav[-1]+s[-i-1][1])
    
    f=[-inf]*(n+1)
    for i in range(n):
        f[i+1]=max(av[i+1]-s[i][0],f[i])
    f.append(-inf)
    
    for i in range(1,n+1):
        rt=max(rt,rav[i]-(c-s[-i][0]),rav[i]-(c-s[-i][0])*2+f[n-i])

    return rt

ans=solve(s)
ans=max(ans,solve([(c-x,v) for x,v in s[::-1]]),0)
print(ans)

Submission status: Accepted

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


n, c = map(int, input().split())
sushi = [list(map(int, input().split())) for _ in range(n)]
half = c//2

DP_left = {}
DP_right = {}
ans = []
# 時計まわりでスタート地点からposまでの最高値
energy = 0
maxim = 0
prev = 0
for pos, cal in sushi:
    lost = pos - prev
    energy += cal - lost
    maxim = max(maxim, energy)
    DP_left[pos] = maxim
    prev = pos
ans.append(maxim)

# 反時計回り
energy = 0
maxim = 0
prev = c
for pos, cal in sushi[::-1]:
    lost = prev - pos
    energy += cal - lost
    maxim = max(maxim, energy)
    DP_right[pos] = maxim
    prev = pos
ans.append(maxim)

# 時計まわりで途中でターン
energy = 0
maxim = 0
prev = 0
for idx, (pos, cal) in enumerate(sushi):
    if idx == n-1:
        break
    if pos > half:
        break
    lost = pos - prev
    energy += cal - lost
    next_pos, _ = sushi[idx+1]
    back_cost = pos
    result = energy - back_cost + DP_right[next_pos]
    maxim = max(maxim, result)
    prev = pos
ans.append(maxim)

# 反時計まわりで途中でターン
energy = 0
maxim = 0
prev = c
for idx, (pos, cal) in enumerate(sushi[::-1], 1):
    if idx == n:
        break
    if pos < half:
        break
    lost = prev - pos
    energy += cal - lost
    back_cost = c - pos
    next_pos, _ = sushi[-idx-1]
    result = energy - back_cost + DP_left[next_pos]
    maxim = max(maxim, result)
    prev = pos
ans.append(maxim)

print(max(ans))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



n, c = LI()
clock_pos = []
value = []
for pos, v in LIR(n):
    clock_pos += [pos]
    value += [v]


rounding_max = [0]
counter_rounding_max = [0]
return_max = [0]
counter_return_max = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    counter_ret += value[-i - 1]
    rounding_max += [max(rounding_max[-1], ret - clock_pos[i])]
    counter_rounding_max += [max(counter_rounding_max[-1], counter_ret - (c - clock_pos[-i - 1]))]
    return_max += [max(return_max[-1], ret - clock_pos[i] * 2)]
    counter_return_max += [max(counter_return_max[-1], counter_ret - (c - clock_pos[-i - 1]) * 2)]



ans = max(rounding_max[-1], counter_rounding_max[-1])
for j in range(1, n + 1):
    ans = max(ans, return_max[j] + counter_rounding_max[n - j], counter_return_max[j] + rounding_max[n - j])


print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
INF = 10**20
rightSushi = [tuple(map(int, input().split())) for _ in range(N)]
leftSushi = [(C - x, v) for x, v in rightSushi[:: -1]]

def calc(sushi):
    ret = [-INF] * (N + 1)
    ret[0] = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret[i] = max(vSum - x, ret[i - 1])
    return ret

leftV = calc(leftSushi)
rightV = calc(rightSushi)

def sol(sushi, maxV):
    ret = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret = max(
            ret,
            vSum - x,
            vSum - x * 2 + maxV[N - i]
        )
    return ret

ans = max(sol(rightSushi, leftV), sol(leftSushi, rightV))

print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
INF = 10**20
rightSushi = [tuple(map(int, input().split())) for _ in range(N)]
leftSushi = [(C - x, v) for x, v in rightSushi[:: -1]]

def calc(sushi):
    ret = [-INF] * (N + 1)
    ret[0] = 0
    vSum = 0
    for i, (x, v) in enumerate(sushi, start=1):
        vSum += v
        ret[i] = max(vSum - x, ret[i - 1])
    return ret

leftV = calc(leftSushi)
rightV = calc(rightSushi)

ans = 0
vSum = 0
for right, (x, v) in enumerate(rightSushi, start=1):
    vSum += v
    ans = max(
        ans,
        vSum - x,
        vSum - x * 2 + leftV[N - right]
    )

vSum = 0
for left, (x, v) in enumerate(leftSushi, start=1):
    vSum += v
    ans = max(
        ans,
        vSum - x,
        vSum - x * 2 + rightV[N - left]
    )

print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
sushi = [(0, 0)]
for _ in range(N):
    x, v = map(int, input().split())
    sushi.append((x, v))
# preprocess
cumsum = [(0, 0)]
cumsum_max = [(0, 0)]
prev = 0
for x, v in sushi[1:]:
    cumsum.append((x, cumsum[-1][1] + prev + v - x))
    cumsum_max.append(cumsum_max[-1] if cumsum_max[-1][1] > cumsum[-1][1] else cumsum[-1])
    prev = x
cumsum_rev = [(0, 0)]
cumsum_rev_max = [(0, 0)]
prev = 0
for x, v in reversed(sushi[1:]):
    cumsum_rev.append((C - x, cumsum_rev[-1][1] + prev + v - (C - x)))
    cumsum_rev_max.append(cumsum_rev_max[-1] if cumsum_rev_max[-1][1] > cumsum_rev[-1][1] else cumsum_rev[-1])
    prev = C - x
ans = 0
for i in range(N+1):
    temp1 = cumsum_max[N-i][1] + cumsum_rev[i][1] - cumsum_rev[i][0]
    temp2 = cumsum_rev_max[N-i][1] + cumsum[i][1] - cumsum[i][0]
    ans = max(ans, temp1, temp2)
print(ans)

Submission status: Accepted

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

X = [0]
V = [0]
sV = [0]
Amax1 = [0]
Amax2 = [0]
for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
    sV.append(sV[-1]+v)
    Amax1.append(max(Amax1[-1], sV[-1]-x))
    Amax2.append(max(Amax2[-1], sV[-1]-2*x))
X.append(C)

ans = 0
for b in range(1, N+2):
    # O -> A -> B
    a1 = Amax2[b-1]+sV[-1]-sV[b-1]-(C-X[b])

    # O -> B -> A
    a2 = Amax1[b-1]+sV[-1]-sV[b-1]-2*(C-X[b])

    ans = max(ans, a1, a2)

print(ans)

Submission status: Accepted

Solution code:
mininf = 0

def cumsum(inlist):
    s = 0
    outlist = []
    for i in inlist:
        s += i
        outlist.append(s)
    return outlist

def maxtohere(inlist):
    s = mininf
    outlist = []
    for i in inlist:
        s = max(s, i)
        outlist.append(s)
    return outlist

n, length = [int(v) for v in input().split()]
sushi = [[int(v) for v in input().split()] for i in range(n)]

diff_distance_from_left = [sushi[i][0] - sushi[i-1][0] if i > 0 else sushi[0][0] for i in range(n)]
diff_distance_from_right = [sushi[i+1][0] - sushi[i][0] if i < n-1 else length - sushi[i][0] for i in range(n-1,-1,-1)]
sushi_oneway_from_left = [sushi[i][1]-diff_distance_from_left[i] for i in range(n)]
sushi_oneway_from_right = [sushi[-i-1][1] - diff_distance_from_right[i] for i in range(n)]
sushi_roundtrip_from_left = [sushi[i][1]-diff_distance_from_left[i]*2 for i in range(n)]
sushi_roundtrip_from_right = [sushi[-i-1][1] - diff_distance_from_right[i]*2 for i in range(n)]

sum_of_sushi_oneway_from_left = cumsum(sushi_oneway_from_left)
sum_of_sushi_roundtrip_from_left = cumsum(sushi_roundtrip_from_left)
sum_of_sushi_oneway_from_right = cumsum(sushi_oneway_from_right)
sum_of_sushi_roundtrip_from_right = cumsum(sushi_roundtrip_from_right)

sum_of_sushi_oneway_from_left = maxtohere(sum_of_sushi_oneway_from_left)
sum_of_sushi_roundtrip_from_left = maxtohere(sum_of_sushi_roundtrip_from_left)
sum_of_sushi_oneway_from_right = maxtohere(sum_of_sushi_oneway_from_right)
sum_of_sushi_roundtrip_from_right = maxtohere(sum_of_sushi_roundtrip_from_right)

sum_of_sushi_from_left = sum_of_sushi_oneway_from_left
sum_of_sushi_from_right = sum_of_sushi_oneway_from_right
for i in range(n-1):
    sum_of_sushi_from_left[i] += sum_of_sushi_roundtrip_from_right[-2-i]
for i in range(n-1):
    sum_of_sushi_from_right[i] += sum_of_sushi_roundtrip_from_left[-2-i]

print(max(sum_of_sushi_from_left+sum_of_sushi_from_right))

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
X,V=[0],[0]
X2,V2=[],[]
for _ in range(n):
    x,v=map(int,input().split())
    X.append(x)
    V.append(v)
    X2.append(c-x)
    V2.append(v)
X2.append(0)
V2.append(0)
X2.reverse()
V2.reverse()
r=[0]
l=[0]
for i in range(n):
    V[i+1]+=V[i]
    V2[i+1]+=V2[i]
rr=[0]
ll=[0]
for i in range(1,n+1):
    r.append(max(r[-1],V[i]-X[i]))
    rr.append(max(rr[-1],V[i]-2*X[i]))
for i in range(1,n+1):
    l.append(max(l[-1],V2[i]-X2[i]))
    ll.append(max(ll[-1],V2[i]-2*X2[i]))
ans=0
for i in range(n+1):
    ans=max(ans,r[i]+ll[n-i],l[i]+rr[n-i])

print(ans)