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:
# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, C = lr()
XV = np.array([lr() for _ in range(N)])
right = XV[:, 1]
r_pos = XV[:, 0]
rcum = right.cumsum() - r_pos
r_max_cum = np.maximum.accumulate(rcum)
left = right[::-1]
l_pos = (C - r_pos)[::-1]
lcum = left.cumsum() - l_pos
l_max_cum = np.maximum.accumulate(lcum)

answer = max(0, r_max_cum[-1], l_max_cum[-1])
# i個目で折り返す
for i in range(N-1):
    temp = rcum[i] - r_pos[i]  # 帰りの距離を引く
    temp += l_max_cum[N-2-i]
    if temp > answer:
        answer = temp

for i in range(N-1):
    temp = lcum[i] - l_pos[i]  # 帰りの距離を引く
    temp += r_max_cum[N-2-i]
    if temp > answer:
        answer = temp

print(answer)

Submission status: Accepted

Solution code:
n,c = map(int,input().split())
x = [0]*n
v = [0]*n
for i in range(n): x[i],v[i] = map(int,input().split())
x1 = [0]+x
v1 = [0]+v
x2 = [0]+list(map(lambda a:c-a,x[::-1]))
v2 = [0]+v[::-1]
lst1 = [0]*(n+1)
lst2 = [0]*(n+1)
lst1[0] = lst2[0] = (0,0)

def f(l,x,v):
    maxcal = pos = sumcal = 0
    for i in range(1,n+1):
        dist = x[i]-x[i-1]
        sumcal += v[i] - dist
        if sumcal > maxcal:
            maxcal = sumcal
            pos = x[i]
        l[i] = (maxcal,pos)

f(lst1,x1,v1)
f(lst2,x2,v2)
# print(lst1)
# print(lst2)

ans = 0
for i in range(n+1):
    maxcal1,dist1 = lst1[i]
    maxcal2,dist2 = lst2[n-i]
    ans = max(ans,maxcal1+maxcal2-min(dist1,dist2))
print(ans)

Submission status: Accepted

Solution code:
n,c = map(int,input().split())
x = [0]*n
v = [0]*n
for i in range(n): x[i],v[i] = map(int,input().split())
x1 = [0]+x
v1 = [0]+v
x2 = [0]+list(map(lambda a:c-a,x[::-1]))
v2 = [0]+v[::-1]
lst1 = [0]*(n+1)
lst2 = [0]*(n+1)
lst1[0] = lst2[0] = (0,0)

def f(l,x,v):
    maxcal = pos = sumcal = 0
    for i in range(1,n+1):
        dist = x[i]-x[i-1]
        sumcal += v[i] - dist
        if sumcal > maxcal:
            maxcal = sumcal
            pos = x[i]
        l[i] = (maxcal,pos)

f(lst1,x1,v1)
f(lst2,x2,v2)
# print(lst1)
# print(lst2)

ans = 0
for i in range(n+1):
    ans = max(ans,lst1[i][0]+lst2[n-i][0]-min(lst1[i][1],lst2[n-i][1]))
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X = []
V = []

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

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

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

P = [0]
Q = [0]

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

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

print(ans)

Submission status: Accepted

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

L=[]
for i in range(N):
    x,y=map(int,input().split())
    L.append([x,y])
    
l=L[::-1]
L=[[0,0]]+L
R=[]

for i in range(N):
    R.append([C-l[i][0],l[i][1]])
R=[[0,0]]+R


#print(L)
#print(R)
TS=[0]
TW=[0]
RS=[0]
RW=[0]

for i in range(N):
    TS.append(TS[i]-L[i+1][0]+L[i][0]+L[i+1][1])
    TW.append(TW[i]-2*(L[i+1][0]-L[i][0])+L[i+1][1])
    RS.append(RS[i]-R[i+1][0]+R[i][0]+R[i+1][1])
    RW.append(RW[i]-2*(R[i+1][0]-R[i][0])+R[i+1][1])
    
MTS=[0]
MRS=[0]
for i in range(1,N+1):
    MTS.append(max(MTS[i-1],TS[i]))
    MRS.append(max(MRS[i-1],RS[i]))

ans=0
for i in range(N+1):
    if i>0 and L[i-1][0]*2>C:
        break
    else:
        if ans<TW[i] + MRS[N-i]:
            ans=TW[i] + MRS[N-i]
            
for i in range(N+1):
    if i>0 and R[i-1][0]*2>C:
        break
    else:
        if ans<RW[i]+MTS[N-i]:
            ans=RW[i]+MTS[N-i]
print(ans)

Submission status: Accepted

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

# counter-clockwise
xv2 = []
for x, v in xv:
    xv2.append([c - x, v])
xv2 = xv2[::-1]

ans = 0

cumsum1, cumsum1_2 = [0], [0]
pos = 0
for x, v in xv:
    tmp = cumsum1[-1] + v - (x - pos)
    cumsum1.append(tmp)
    cumsum1_2.append(tmp - x)
    pos = x
    ans = max(ans, tmp)
cumsum1, cumsum1_2 = cumsum1[1:], cumsum1_2[1:]

cumsum2, cumsum2_2 = [0], [0]
pos = 0
for x, v in xv2:
    tmp = cumsum2[-1] + v - (x - pos)
    cumsum2.append(tmp)
    cumsum2_2.append(tmp - x)
    pos = x
    ans = max(ans, tmp)
cumsum2, cumsum2_2 = cumsum2[1:][::-1], cumsum2_2[1:][::-1]

tmpmax = 0
for i in reversed(range(n)):
    ans = max(ans, cumsum1[i] + tmpmax)
    tmpmax = max(tmpmax, cumsum2_2[i])

tmpmax = 0
for i in range(n):
    ans = max(ans, cumsum2[i] + tmpmax)
    tmpmax = max(tmpmax, cumsum1_2[i])

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    #入力
    readline=stdin.readline
    n,c=map(int,readline().split())
    x=[0]*n
    v=[0]*n
    for i in range(n):
        x[i],v[i]=map(int,readline().split())

    x_rev=list(map(lambda x:c-x,reversed(x)))
    v_rev=list(reversed(v))

    dp=[0]*(n+1)
    dp_rev=[0]*(n+1)
    now=0
    tmp=0
    for i in range(n):
        dp[i+1]=max(dp[i],tmp+v[i]-x[i]+now)
        tmp+=v[i]-x[i]+now
        now=x[i]
    now=0
    tmp=0
    for i in range(n):
        dp_rev[i+1]=max(dp_rev[i],tmp+v_rev[i]-x_rev[i]+now)
        tmp+=v_rev[i]-x_rev[i]+now
        now=x_rev[i]

    ans=0
    #時計、反時計
    for i in range(n):
        tmp1=dp[i+1]
        tmp2=dp[i+1]-x[i]+dp_rev[n-i-1]
        ans=max(ans,tmp1,tmp2)

    #反時計、時計
    for i in range(n):
        tmp1=dp_rev[i+1]
        tmp2=dp_rev[i+1]-x_rev[i]+dp[n-i-1]
        ans=max(ans,tmp1,tmp2)

    print(ans)

if __name__=="__main__":
    main()

Submission status: Accepted

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

xv = [list(map(int, input().split())) for _ in range(N)]

xinc = [0] * N
xinc2 = [0] * N
xdec = [0] * N
xdec2 = [0] * N

nowx = 0
nowv = 0

nowxin = C
nowvin = 0

for i in range(N):
  xi, vi = xv[i]
  nowv = nowv - (xi-nowx) + vi
  xinc[i] = nowv
  xinc2[i] = nowv - xi
  nowx = xi
  
  xin, vin = xv[N-1-i]
  nowvin = nowvin - (nowxin-xin) + vin
  xdec[i] = nowvin
  xdec2[i] = nowvin - (C-xin)
  nowxin = xin
  
mxinc2 = [0]*N
mxdec2 = [0]*N
for i in range(1, N):
  mxinc2[i] = max(mxinc2[i-1], xinc2[i-1])
  mxdec2[i] = max(mxdec2[i-1], xdec2[i-1])
  
ans = 0
for i in range(N):
  ans = max(ans, xinc[i], xdec[i])
  ans = max(ans, mxinc2[i]+xdec[N-1-i])
  ans = max(ans, mxdec2[i]+xinc[N-1-i])

print(ans)

Submission status: Accepted

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

N,C = map(int,readline().split())
sushi = [list(map(int,readline().split())) for i in range(N)]
import copy
revsushi = copy.deepcopy(sushi)[::-1]
for i in range(len(sushi)-1, 0, -1):
  sushi[i][0] = sushi[i][0] - sushi[i - 1][0]

for i in range(len(revsushi)):
  revsushi[i][0] = C - revsushi[i][0]
for i in range(len(revsushi)-1, 0, -1):
  revsushi[i][0] = revsushi[i][0] - revsushi[i - 1][0]

# 左回り/右回りにi個食べたときの結果
# 0個のときは0を入れておく
left = [[0] * 2 for i in range(N + 1)]
right = [[0] * 2 for i in range(N + 1)]

left[0] = [0,0]
right[0] = [0,0]

# 累積ポイント, そこまでのベストポイント
for i in range(len(sushi)):
  x,v = sushi[i]
  left[i + 1][0] = left[i][0] + v - x # 摂取カロリー - 消費カロリー
  if left[i + 1][0] > left[i][1]: # 前回までのベストより優れている
    left[i + 1][1] = left[i + 1][0]
  else:
    left[i + 1][1] = left[i][1]
    
# この状態で右回りにチェックしていく
best = left[-1][1] # 左回りにすべて取った場合を最大値としてスタート
cal = 0
for i in range(len(revsushi)):
  count = i + 1 # 取る寿司の数
  lp = left[N - count][1]
  # 逆回りに取れる寿司の最大値
  x,v = revsushi[i]
  cal += (v - x * 2)
  if lp + cal > best:
    best = lp + cal

# 右回りを作る
for i in range(len(revsushi)):
  x,v = revsushi[i]
  right[i + 1][0] = right[i][0] + v - x
  if right[i + 1][0] > right[i][1]:
    right[i + 1][1] = right[i + 1][0]
  else:
    right[i + 1][1] = right[i][1]

best = max(best, right[-1][1])
cal = 0
for i in range(len(sushi)):
  count = i + 1 # 取る寿司の数
  rp = right[N - count][1]
  # 逆回りに取れる寿司の最大値
  x,v = sushi[i]
  cal += (v - x * 2)
  if rp + cal > best:
    best = rp + cal

print(best)

Submission status: Accepted

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 = [0]
Q = [0]

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

ans = 0

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

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

n, c = map(int, input().split())
xs, vs = [], []
for _ in range(n):
    x, v = map(int, input().split())
    xs.append(x)
    vs.append(v)
xs = [0] + xs + [c]
vs = [0] + vs + [0]


def maxcalrrl(xs=xs, vs=vs):
    avsr = list(accumulate(reversed(vs)))[::-1]

    calr = [a - 2 * x for x, a in zip(xs, accumulate(vs))]
    call = [a - (c - x) for x, a in zip(xs, avsr)]

    maxcalr = list(accumulate(calr, max))

    return max([
        call[i + 1] + maxcalr[i] for i in range(n + 1)
    ])


def maxcalrll(xs=xs, vs=vs):
    xsr = [c - x for x in xs][::-1]
    vsr = vs[::-1]
    return maxcalrrl(xsr, vsr)


# print(maxcalrrl())
answer = max([maxcalrrl(), maxcalrll()])
print(answer)

Submission status: Accepted

Solution code:
from itertools import *
n,c,*u=map(int,open(0).read().split());x,a=u[::2]+[c],[0]+list(accumulate(u[1::2]));ans=l=r=0
for b in range(n+1):t,d,l,r=a[n]-a[b],c-x[b],max(l,a[b]-x[b-1]),max(r,a[b]-2*x[b-1]);ans=max(ans,l+t-2*d,r+t-d)
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
n,c=map(int,input().split())
sushi=[list(map(int,input().split())) for i in range(n)]

r=[sushi[0][1]-sushi[0][0]]
for i in range(1,n):
    r.append(r[-1]+sushi[i][1]-(sushi[i][0]-sushi[i-1][0]))
l=[sushi[n-1][1]-(c-sushi[n-1][0])]
for i in range(n-2,-1,-1):
    l.append(l[-1]+sushi[i][1]-((c-sushi[i][0])-(c-sushi[i+1][0])))
r2=[sushi[0][1]-2*sushi[0][0]]
for i in range(1,n):
    r2.append(r2[-1]+sushi[i][1]-2*(sushi[i][0]-sushi[i-1][0]))
l2=[sushi[n-1][1]-2*(c-sushi[n-1][0])]
for i in range(n-2,-1,-1):
    l2.append(l2[-1]+sushi[i][1]-2*((c-sushi[i][0])-(c-sushi[i+1][0])))
r=list(accumulate(r,max))
l=list(accumulate(l,max))

cand=[l[-1],r[-1]]
for i in range(n):
    if 0<=n-i-2<=n-1:
        cand.append(l2[i]+r[n-i-2])
        cand.append(r2[i]+l[n-i-2])

print(max(max(cand),0))

Submission status: Accepted

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,jun2[i])
    jun2[i] = tmp
    
tmp = 0
for i in range(n):
    tmp = max(tmp,rev2[i])
    rev2[i] = tmp

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

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

print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, c = list(map(int, readline().split()))

    x = [0] * (n + 1)
    v = [0] * (n + 1)

    for i in range(1, n + 1):
        x[i], v[i] = map(int, readline().split())

    right_cum = [0] * (n + 1)
    left_cum = [0] * (n + 1)

    for i in range(1, n + 1):
        right_cum[i] = right_cum[i - 1] + v[i]
        left_cum[i] = left_cum[i - 1] + v[n - i + 1]

    right_nutritive = [0] * (n + 1)
    left_nutritive = [0] * (n + 1)
    right_max_cum = [0] * (n + 1)
    left_max_cum = [0] * (n + 1)

    for i in range(1, n + 1):
        right_nutritive[i] = right_cum[i] - x[i]
        left_nutritive[i] = left_cum[i] - (c - x[n - i + 1])
        right_max_cum[i] = max(right_max_cum[i - 1], right_nutritive[i])
        left_max_cum[i] = max(left_max_cum[i - 1], left_nutritive[i])

    r_temp = max(right_nutritive)
    l_temp = max(left_nutritive)
    ans = max(r_temp, l_temp)

    for i in range(1, n + 1):
        rl = right_nutritive[i] - x[i] + left_max_cum[n - i]
        lr = left_nutritive[i] - (c - x[n - i + 1]) + right_max_cum[n - i]
        ans = max(ans, rl, lr)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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
    # print(clockwise)
    # print(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_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

    
    # print(max_memo_clock_0)
    # print(max_memo_counter_clock_0)

    ans = max(max(max_memo_clock_0), max(max_memo_counter_clock_0), 0)
    # print(ans)

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

    
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


# -------------------------------------------------------------
# main
# -------------------------------------------------------------
N,C = map(int,input().split())
XV = [tuple(map(int,input().split())) for _ in range(N)]

# 順方向,逆方向の累積和
VF,VB = [0]*(N+1),[0]*(N+1)
for i in range(N):
    VF[i+1] += VF[i]+XV[i][1]
for i in range(N):
    VB[N-i-1] += VB[N-i]+XV[N-1-i][1]
# 移動距離を減算
for i in range(N):
    VF[i+1] -= XV[i][0]
for i in range(N):
    VB[N-i-1] -= (C-XV[N-1-i][0])
# 食べに行くと損する場合を除くために単調増加に
for i in range(N):
    if VF[i+1] < VF[i]:
        VF[i+1] = VF[i]
for i in range(N):
    if VB[N-1-i] < VB[N-i]:
        VB[N-1-i] = VB[N-i]
 
# 順方向,逆方向で全部食べた場合で初期化
ans = 0
ans = max(ans, VF[N], VB[0])
 
# 反転 : 順方向→逆方向
for i in range(1,N):
    ans = max(ans, VF[i], VF[i]+VB[i]-XV[i-1][0])
 
# 反転 : 逆方向→順方向
for i in range(1,N):
    ans = max(ans, VB[i], VB[i]+VF[i]-(C-XV[i][0]))
 
print(ans)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(n)]
a, b = [0] * n, [0] * n
a[0] = s[0][1] - s[0][0]
b[0] = s[n - 1][1] - (c - s[n - 1][0])
for i in range(1, n):
    a[i] = a[i - 1] + s[i][1] - (s[i][0] - s[i - 1][0])
    b[i] = b[i - 1] + s[n - 1 - i][1] - (s[n - i][0] - s[n - 1 - i][0])
maxa, maxb = [0] * n, [0] * n
maxa[0], maxb[0] = a[0], b[0]
for i in range(1, n):
    maxa[i] = max(maxa[i - 1], a[i])
    maxb[i] = max(maxb[i - 1], b[i])
ans = max(maxa[n - 1], maxb[n - 1], 0)
for i in range(n - 1):
    ans = max(ans, a[i] + maxb[n - 2 - i] - s[i][0])
    ans = max(ans, b[i] + maxa[n - 2 - i] - (c - s[n - 1 - i][0]))
print(ans)

Submission status: Accepted

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 - 1):
    result = max(result, a0[i] - x[i] + a1[N - 1 - (i + 1)])
for i in range(N - 1):
    result = max(result, a1[i] - (C - x[N - 1 - i]) + a0[N - 1 - (i + 1)])
print(result)

Submission status: Accepted

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

#print(a0)
#print(a1)
result = -1
if a0[N - 1] > result:
    #print("go a0[N-1]")
    result = a0[N - 1]
if a1[N - 1] > result:
    #print("go a1[N-1]")
    result = a1[N - 1]
for i in range(N - 1):
    t = a0[i] - x[i] + a1[N - 1 - (i + 1)]
    if t > result:
       #print("go a0[%d] and go a1[%d]: %d" % (i, N - 1 - (i + 1), t))
       result = t
for i in range(N - 1):
    t = a1[i] - (C - x[N - 1 - i]) + a0[N - 1 - (i + 1)]
    if t > result:
       #print("go a1[%d] and go a0[%d]: %d" % (i, N - 1 - (i + 1), t))
       result = t
print(result)

Submission status: Accepted

Solution code:
import heapq

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

sushi = []
for i in range(N):
    cur_sushi = list(map(int,input().split()))
    sushi.append(cur_sushi)

sum_V, sum_right = [0], [0]
for i in range(N):
    sum_V.append(sum_V[i]+sushi[i][1])
    sum_right.append(sum_V[i+1] - sushi[i][0])

sum_V, sum_left = [0], [0]
for i in range(N):
    sum_V.append(sum_V[i]+sushi[N-1-i][1])
    sum_left.append(sum_V[i+1] - (C-sushi[N-1-i][0]))

ans = max(max(sum_left), max(sum_right))

left = [0]
heapq.heapify(left)

for l in range(N):
    now = sum_right[N-l] - sushi[N-1-l][0]
    heapq.heappush(left, -sum_left[l])
    now -= left[0]
    ans = max(ans,now)

right = [0]
heapq.heapify(right)

for r in range(N):
    now = sum_left[N-r] - (C - sushi[r][0])
    heapq.heappush(right, -sum_right[r])
    now -= right[0]
    ans = max(ans,now)

print(ans)

Submission status: Accepted

Solution code:
def main():
    N, C = list(map(int, input().split(' ')))
    sushi = [list(map(int, input().split(' '))) for _ in range(N)]
    cr = [0 for _ in range(N + 1)]
    cr_rt = [0 for _ in range(N + 1)]
    for i in range(N):
        move = sushi[i][0] if i == 0 else (sushi[i][0] - sushi[i-1][0])
        cr[i+1] = cr[i] + sushi[i][1] - move
        cr_rt[i+1] = cr_rt[i] + sushi[i][1] - 2 * move
    cl = [0 for _ in range(N + 1)]
    cl_rt = [0 for _ in range(N + 1)]
    for i in range(N):
        move = (C - sushi[N-1-i][0]) if i == 0 else (sushi[N-i][0] - sushi[N-1-i][0])
        cl[i+1] = cl[i] + sushi[N-1-i][1] - move
        cl_rt[i+1] = cl_rt[i] + sushi[N-1-i][1] - 2 * move
    cr_rt_max = [0 for _ in range(N + 1)]
    cl_rt_max = [0 for _ in range(N + 1)]
    for i in range(N):
        cr_rt_max[i+1] = max([cr_rt_max[i], cr_rt[i+1]])
        cl_rt_max[i+1] = max([cl_rt_max[i], cl_rt[i+1]])
    # explore
    ans = 0
    for i in range(N+1):
        ans = max([ans, cr[i] + cl_rt_max[N-i]])
        ans = max([ans, cl[i] + cr_rt_max[N-i]])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

def main():
    N, C = map(int, readline().rstrip().split())
    pair = [tuple(map(int, readline().rstrip().split())) for _ in range(N)]
    x_acc_right = []  # 時計回り方向にi移動した時の最大の利得
    gain, max_gain = 0, 0
    for xi, vi in pair:
        gain += vi
        max_gain = max(max_gain, gain - xi)
        x_acc_right.append(max_gain)
        
    x_acc_left = []  # 反時計回り方向にi移動した時の最大の利得
    gain, max_gain = 0, 0
    for xi, vi in pair[::-1]:
        gain += vi
        max_gain = max(max_gain, gain - (C - xi))
        x_acc_left.append(max_gain)
        
    res = max(x_acc_right[-1], x_acc_left[-1])
    # 時計回りに進んだ後、原点に戻って反時計回りに進むパターン
    gain = 0
    for i in range(N-1):
        xi, vi = pair[i]
        gain += vi
        res = max(res, gain - 2 * xi + x_acc_left[N-i-2])

    # 反時計回りに進んだ後、原点に戻って時計回りに進むパターン
    gain = 0
    for i in range(N-1, 0, -1):
        xi, vi = pair[i]
        gain += vi
        res = max(res, gain - 2 * (C-xi) + x_acc_right[i-1])
        
    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
"""
寿司iまで歩いて食べに行くと、1~iまでの合計カロリー - iまでの移動距離　のカロリーを得られる。
円形なので、時計回りか反時計回りかで移動距離が変わるので、結果のカロリーも変わる。
愚直にやると、
・反時計回りの方向にL個、時計回りの方向にR個食べる
・先にLRどちらに食べに行くか
の選択があるので、N*N*2とかになり、間に合わない。
*2の部分は大したことないので、どちらを先に食べに行くかは全部やっても問題ない。
LとRの決め方について、例えばN=10として、先に左に２個食べる（L=2）とすると、Rは０～８の範囲で選べる。
入店位置から、時計回りに移動して食べて退店するまでのカロリーは、Lまで食べに行く時のカロリーと独立して考えられる。
各Lについてこれを毎回計算するのは処理が重複するので、
・入店位置からRまでのいずれかの寿司へ、時計回りに移動して食べられる時に得られる最大カロリー
を事前に計算しておいて、Lまで食べに行って戻ってきた時のカロリーと合わせればよい。
逆も同様。

これで*Nが一つ消える感じか。
"""
N,C = map(int, input().split())
clocks = [tuple(map(int, input().split())) for _ in range(N)]

antis = []
for x,v in reversed(clocks):
    antis.append((C-x, v))

accum_clocks = [0] * N
accum_clocks[0] = clocks[0][1] - clocks[0][0]
for i in range(1,N):
    accum_clocks[i] = accum_clocks[i-1] + clocks[i][1] - clocks[i][0] + clocks[i-1][0]

# 右にi個まで食べに行ける時に得られる最大カロリー
clocks_max = [0] * (N+1)

for i in range(N):
    clocks_max[i+1] = max(clocks_max[i], accum_clocks[i])

accum_antis = [0] * N
accum_antis[0] = antis[0][1] - antis[0][0]
for i in range(1,N):
    accum_antis[i] = accum_antis[i-1] + antis[i][1] - antis[i][0] + antis[i-1][0]

antis_max = [0] * (N+1)
for i in range(N):
    antis_max[i+1] = max(antis_max[i], accum_antis[i])


ans = 0
ans = max(ans, max(clocks_max), max(antis_max))

# 累積和をカロリーと距離に分けて保存しなかったために面倒になった。
accum_sushi = 0
for l in range(N):
    accum_sushi += antis[l][1]
    #print(l, antis[l][1] - 2*antis[l][0] , clocks_max[N-l-1])
    ans = max(ans, accum_sushi - 2*antis[l][0] + clocks_max[N-l-1])

accum_sushi = 0
for r in range(N):
    accum_sushi += clocks[r][1]
    #print(r, clocks[r][1] - 2*clocks[r][0] , antis_max[N-r-1])
    ans = max(ans, accum_sushi - 2*clocks[r][0] + antis_max[N-r-1])

    
print(ans)
"""
print(accum_clocks)
print(accum_antis)
print(clocks_max)
print(antis_max)
"""

Submission status: Accepted

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

l1 = 0
r1 = 0
l1_tmp = 0
l2_tmp = 0
r1_tmp = 0
r2_tmp = 0
now = 0
lil = []
lir = []
ll = []
lr = []

for x,v in xv:
    r1_tmp += v - (x - now)
    r2_tmp = r1_tmp - x
    r1 = max(r1, r1_tmp)
    lir.append(r2_tmp)
    lr.append(r1_tmp)
    now = x

xv = xv[::-1]
now = 0

for x,v in xv:
    x = c - x
    l1_tmp += v - (x - now)
    l2_tmp = l1_tmp - x
    l1 = max(l1, l1_tmp)
    lil.append(l2_tmp)
    ll.append(l1_tmp)
    now = x

max_idx = 0
lir = lir[::-1]
lir2 = []
lil2 = []
for i in range(n):
    lir2.append((lir[i], i))
for i in range(n):
    lil2.append((lil[i], n-i-1))

lir2.sort(reverse = True)
lil2.sort(reverse = True)

count = 0
ans = 0
for i in range(n-1):
    while lir2[count][1] <= i:
        count += 1
        if count > n:
            break
    ans = max(ans, ll[i]+lir2[count][0])

count = 0
for i in range(n-1):
    while lil2[count][1] <= i:
        count += 1
        if count > n:
            break
    ans = max(ans, lr[i]+lil2[count][0])

print(max(r1, l1, ans))