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 _ in range(n)]

cw = []
cw2 = [0]
v_sm = 0
for x, v in xv:
    v_sm += v
    cw.append(v_sm - x)
    cw2.append(v_sm - 2 * x)

ccw = []
ccw2 = [0]
v_sm = 0
for x, v in xv[::-1]:
    v_sm += v
    ccw.append(v_sm - (c - x))
    ccw2.append(v_sm - 2 * (c - x))

cw_mx = [0]
ccw_mx = [0]
for e in cw:
    cw_mx.append(max(cw_mx[-1], e))
for e in ccw:
    ccw_mx.append(max(ccw_mx[-1], e))

ans = 0
for i, e in enumerate(cw2):
    mx = e + ccw_mx[n-i]
    ans = max(ans, mx)

for i, e in enumerate(ccw2):
    mx = e + cw_mx[n-i]
    ans = max(ans, mx)

print(ans)

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, C = MAP()
L = [LIST() for i in range(N)]
# oa, ob
A = [0] * N
B = [0] * N

X = []
V = []
for x, v in L:
    X.append(x)
    V.append(v)

tmp_v = 0
for i in range(N):
    tmp_v += V[i]
    A[i] = tmp_v - X[i]

tmp_v = 0
for i in range(N-1, -1, -1):
    tmp_v += V[i]
    B[i] = tmp_v - (C - X[i])

gA = [0] * N
gA[0] = A[0]

for i in range(1, N):
    gA[i] = max(gA[i-1], A[i])

gB = [0] * N
gB[N-1] = B[N-1]

for i in range(N-2, -1, -1):
    gB[i] = max(gB[i+1], B[i])

a = max(A)
b = max(B)
c, d = 0, 0
if N > 1:
    c = max([A[i] - X[i] + gB[i+1] for i in range(0, N-1)])
    d = max([B[i] - (C - X[i]) + gA[i-1] for i in range(N-1, 0, -1)])    
print(max(a, b, c, d, 0))

Submission status: Accepted

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

X,V,M=[0]*(N+1),[0]*(N+1),[0]*(N+1)
for i in range(1,N+1):
  X[i],V[i]=D[i-1][0],V[i-1]+D[i-1][1]
  M[i]=M[i-1] if M[i-1]>V[i]-D[i-1][0] else V[i]-D[i-1][0]

m=0
for i in range(1,N+1):
  e=M[i-1]-(C-X[i]) if M[i-1]>C-X[i] else 0
  e+=V[N]-V[i-1]-(C-X[i])
  m=m if m>e else e

M=[0]*(N+2)
for i in range(N,0,-1):
  p=V[N]-V[i-1]-(C-X[i])
  M[i]=M[i+1] if M[i+1]>p else p

for i in range(1,N+1):
  e=M[i+1]-X[i] if M[i+1]>X[i] else 0
  e+=V[i]-X[i]
  m=m if m>e else e

print(m)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from itertools import product
INF = 10**9
MOD = 10**9 + 7

def main():
    n,c = map(int,input().split())
    sushi = [list(map(int,input().split())) for _ in range(n)]
    
    r = [0] * (n+1)
    l = [0] * (n+1)
    r_max = [0] * (n+1)
    l_max = [0] * (n+1)

    x = 0
    y = c
    for i in range(n):
        r[i+1] = r[i] + sushi[i][1] - sushi[i][0] + x
        r_max[i+1] = max(r_max[i],r[i+1])
        x = sushi[i][0]

        l[-i-2] = l[-i-1] + sushi[-i-1][1] - y + sushi[-i-1][0]
        l_max[-i-2] = max(l_max[-i-1],l[-i-2])
        y = sushi[-i-1][0]
    
    ans = max(r_max[-1], l_max[0])
    for i in range(n-1):
        tmp1 = r[i+1] + l_max[i+1] - sushi[i][0]
        tmp2 = l[i+1] + r_max[i+1] - c + sushi[i+1][0]
        ans = max (ans ,tmp1 ,tmp2 )
    
    print(ans)
  
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
xc=[tuple(map(int,input().split())) for i in range(N)]
xc.sort()
ans=0
p=0
#右を取る範囲と左を取る範囲を決めればいい
s=[0]*(N+1)#時計回り
ss=[0]*(N+1)#反時計回り
for i in range(N):
  s[i+1]=s[i]+xc[i][1]

for i in range(N):
  ss[i+1]=ss[i]+xc[N-1-i][1]
maxs=[0]*(N+1)
maxss=[0]*(N+1)
for i in range(N):
  s[i+1]=s[i+1]-xc[i][0]
  ss[i+1]=ss[i+1]-(C-xc[N-1-i][0])
  maxs[i+1]=max(maxs[i],s[i+1])
  maxss[i+1]=max(maxss[i],ss[i+1])
ans=max(0,maxs[-1])
ans=max(ans,maxss[-1])
for i in range(N):
  if s[i+1]>xc[i][0]:
    ans=max(ans,maxss[N-i-1]+(s[i+1]-xc[i][0]))
  if ss[i+1]>(C-xc[N-1-i][0]):
    ans=max(ans,maxs[N-i-1]+(ss[i+1]-(C-xc[N-1-i][0])))
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())

lcal = [0] * N
lmax = [0] * N
rcal = [0] * N
rmax = [0] * N

rcal[0] = v[0]-x[0]
rmax[0] = rcal[0]
for i in range(1,N):
    rcal[i] = rcal[i-1] + v[i] - x[i] + x[i-1]
    rmax[i] = max(rmax[i-1],rcal[i])

lcal[0] = v[N-1] - (C - x[N-1])
lmax[0] = lcal[0]

for i in range(1,N):
    lcal[i] = lcal[i-1] + v[N-i-1] + x[N-i-1] -x[N-i]
    lmax[i] = max(lmax[i-1],lcal[i])

#print(rmax)
#print(lmax)

ans = 0

for i in range(N-1):
    ans = max(ans,rcal[i],rcal[i]+lmax[N-i-2]-x[i])
    #print(i,ans)

ans = max(ans,rcal[N-1])

for i in range(N-1):
    ans = max(ans,lcal[i],lcal[i]+rmax[N-i-2]-(C-x[N-i-1]))
    #print(i,ans)

ans = max(ans,lcal[N-1])



print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
N, C, *L = map(int, open(0).read().split())
hq1 = []
hq2 = []
sushi = []
for x,y in zip(*[iter(L)]*2):
  sushi += [(x,y)]
sushi.sort()
x = 0
y = 0
for i in range(N-1,-1,-1):
  p,q = sushi[i]
  x += q
  heappush(hq1,(-x+(C-p),i))
  p,q = sushi[N-1-i]
  y += q
  heappush(hq2,(-y+p,N-1-i))
m = 0
ans1 = 0
for i in range(N):
  x,y = sushi[i]
  m += y
  n = m-x
  while hq1 and hq1[0][1]<=i:
    heappop(hq1)
  if hq1 and hq1[0][0]<-x:
    ans1 = max(ans1, n-hq1[0][0]-x)
  else:
    ans1 = max(ans1,n)
    

m = 0
ans2 = 0
for i in range(N-1,-1,-1):
  x,y = sushi[i]
  m += y
  n = m-(C-x)
  while hq2 and hq2[0][1]>=i:
    heappop(hq2)
  if hq2 and hq2[0][0]<-(C-x):
    ans2 = max(ans2, n-hq2[0][0]-(C-x))
  else:
    ans2 = max(ans2, n)
print(max(ans1,ans2))

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
acumr=[0,arr[0][1]-arr[0][0]]
acuml=[0,arr[-1][1]-(c-arr[-1][0])]
for i in range(1,n):
  acumr.append(acumr[-1]+arr[i][1]-(arr[i][0]-arr[i-1][0]))
  acuml.append(acuml[-1]+arr[-(i+1)][1]-(arr[-i][0]-arr[-(i+1)][0]))
maxr=[0]
maxl=[0]
for i in range(1,n+1):
  maxr.append(max(maxr[-1],acumr[i]))
  maxl.append(max(maxl[-1],acuml[i]))
ans=0
for i in range(1,n+1):
  tmp1=acumr[i]
  tmp2=acuml[i]
  if arr[i-1][0]<maxl[n-i]:
    tmp1+=maxl[n-i]-arr[i-1][0]
  if c-arr[-i][0]<maxr[n-i]:
    tmp2+=maxr[n-i]-(c-arr[-i][0])
  ans=max(ans,tmp1)
  ans=max(ans,tmp2)
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
S = [list(map(int, input().split())) for _ in range(N)]
SV = [0]
for x, v in S:
    SV.append(v+SV[-1])
left = [0]
leftturn = [0]
for i in range(N):
    left.append(SV[i+1]-S[i][0])
    leftturn.append(SV[i+1]-S[i][0]*2)
S.reverse()
SV = [0]
for x, v in S:
    SV.append(v+SV[-1])
right = [0]
rightturn = [0]
for i in range(N):
    right.append(SV[i+1]-(C-S[i][0]))
    rightturn.append(SV[i+1]-(C-S[i][0])*2)
ml = [0]
mr = [0]
mlt = [0]
mrt = [0]
for i in range(N):
    ml.append(max(left[i+1], ml[-1]))
    mr.append(max(right[i+1], mr[-1]))
    mlt.append(max(leftturn[i+1], mlt[-1]))
    mrt.append(max(rightturn[i+1], mrt[-1]))
res = 0
for i in range(N+1):
    res = max(res, ml[i]+mrt[N-i], mr[i]+mlt[N-i])
print(res)

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    sushi = [None]*n
    for i in range(n):
        sushi[i] = list(map(int, input().split()))
    cal_r = [None] * n
    cal_l = [None] * n
    max_r = [None] * n
    max_l = [None] * n
    cal_r[0] = sushi[0][1] - sushi[0][0]
    max_r[0] = cal_r[0]
    for i in range(1, n):
        cal_r[i] = cal_r[i-1] + sushi[i][1] - (sushi[i][0] - sushi[i-1][0])
        max_r[i] = max(max_r[i-1], cal_r[i])
    cal_l[n-1] = sushi[n-1][1] - (c - sushi[n-1][0])
    max_l[n-1] = cal_l[n-1]
    for i in reversed(range(n-1)):
        cal_l[i] = cal_l[i+1] + sushi[i][1] - (sushi[i+1][0] - sushi[i][0])
        max_l[i] = max(max_l[i+1], cal_l[i])
    max_r_1 = max(max_r)
    max_l_1 = max(max_l)
    ans = max(0, max_r_1, max_l_1)
    cal_r_2 = [None] * n
    cal_l_2 = [None] * n
    cal_r_2[n-1] = 0
    cal_l_2[0] = 0
    for i in range(n-1):
        cal_r_2[i] = cal_r[i] - sushi[i][0] + max_l[i+1]
    for i in reversed(range(1, n)):
        cal_l_2[i] = cal_l[i] - (c - sushi[i][0]) + max_r[i-1]
    max_r_2 = max(cal_r_2)
    max_l_2 = max(cal_l_2)
    ans = max(ans, max_l_2, max_r_2)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#from collections import *
#from itertools import *
#from bisect import *
from heapq import *
#import copy
#N=int(input())
#X,Y=map(int,input().split())
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N,C=map(int,input().split())
XV=[list(map(int,input().split())) for i in range(N)]
XVR=list(reversed(XV))
value=0
tempvalue=0
csXV=[[0,0] for i in range(N)]
csXVR=[[0,0] for i in range(N)]
csXV[0][0]=XV[0][0]
csXV[0][1]=XV[0][1]
csXVR[0][0]=XV[-1][0]
csXVR[0][1]=XV[-1][1]
csXVR[0][0]=C-csXVR[0][0]
for i in range(1,N):
    csXV[i][0] =XV[i][0]
    csXV[i][1] =XV[i][1]+csXV[i-1][1]
    csXVR[i][0]=C-XV[N-1-i][0]
    csXVR[i][1]=XVR[i][1]+csXVR[i-1][1]


csXV[0].append(csXV[0][1]-csXV[0][0])
csXVR[0].append(csXVR[0][1]-csXVR[0][0])

for i in range(1,N):
    csXV[i].append(csXV[i][1]-csXV[i][0])
    csXVR[i].append(csXVR[i][1]-csXVR[i][0])

csXV[0].append(csXV[0][2])
csXVR[0].append(csXVR[0][2])



for i in range(1,N):
    csXV[i].append(max(csXV[i][2],csXV[i-1][3]))
    csXVR[i].append(max(csXVR[i][2],csXVR[i-1][3]))

#距離、価値、累積価値ー距離、３の累積最大値

value=0
for i in range(N-1):
    B=N-1 -i-1
    tempvalue=csXV[i][2]-csXV[i][0]+csXVR[B][3]
    value=max(tempvalue,value,csXV[i][3])

for i in range(N-1):
    B=N-1 -i-1
    tempvalue=csXVR[i][2]-csXVR[i][0]+csXV[B][3]
    value=max(tempvalue,value,csXV[i][3])

value=max(value,csXV[-1][3],csXVR[-1][3])

print(value)

Submission status: Accepted

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

LR=copy.deepcopy(L)
L=[[0,0]]+L
#print(L)
LR=LR[::-1]

for i in range(N):
    LR[i][0]=C-LR[i][0]
LR=[[0,0]]+LR
#print(LR)
Lr=[0]
S=0
for i in range(1,N+1):
    S+=L[i][1]
    Lr.append(S-L[i][0])
#print(Lr)
LC=[0]

for i in range(1,N+1):
    LC.append(max(LC[-1],Lr[i]))
#print(LC)

LRr=[0]
S=0
for i in range(1,N+1):
    S+=LR[i][1]
    LRr.append(S-LR[i][0])
#print(LRr)
LRC=[0]
for i in range(1,N+1):
    LRC.append(max(LRC[-1],LRr[i]))
#print(LRC)

ans=0
for i in range(N+1):
    cnt=LC[i]-L[i][0]+LRC[N-i]
    ans=max(ans,cnt)
for i in range(N+1):
    cnt=LRC[i]-LR[i][0]+LC[N-i]
    ans=max(ans,cnt)
print(ans)

Submission status: Accepted

Solution code:
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)])
Sushi = XV[:, 1]
Sushi_rev = Sushi[::-1]
dis = XV[:, 0]
dis_rev = C - dis[::-1]
Sushi_cum = Sushi.cumsum()
Sushi_rev_cum = Sushi_rev.cumsum()
Sushi_cum -= dis
Sushi_rev_cum -= dis_rev
Sushi_max = np.maximum.accumulate(Sushi_cum)
Sushi_max_rev = np.maximum.accumulate(Sushi_rev_cum)
answer = max(0, Sushi_max[-1], Sushi_max_rev[-1])

for i in range(N-1):
    cal = Sushi_cum[i] - dis[i] + Sushi_max_rev[N-2-i]
    cal2 = Sushi_rev_cum[i] - dis_rev[i] + Sushi_max[N-2-i]
    cal = max(cal, cal2)
    if cal > answer:
        answer = cal

print(answer)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

INF = -(2 ** 31)

N, C = [int(_) for _ in input().split()]
X = [[int(x) for x in input().split()] for _ in range(N)]


def spam():
    L = [0] * N
    pre = 0
    pre_max = -(2 ** 31)
    for i in range(N):
        x, v = X[-i - 1]
        L[i] = max(pre_max, pre + v - (C - x))
        pre += v
        pre_max = L[i]

    ans = max(pre_max, 0)
    pre = 0
    for i in range(N):
        x, v = X[i]
        tmp = pre + v - x

        if i < N - 1:
            tmp2 = max(L[N - i - 2] - x, 0)
        else:
            tmp2 = 0
        ans = max(ans, tmp + tmp2)
        pre += v
    return ans


def main():
    global X
    ans = spam()
    X = X[::-1]
    for i in range(N):
        X[i][0] = C - X[i][0]
    ans = max(ans, spam())
    print(ans)


main()

Submission status: Accepted

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

def main():
    N,C = map(int,input().split())
    susi = [tuple(map(int,input().split())) for _ in range(N)]
    csusi = list(reversed(susi))
    
    cal,ccal = 0,0
    now,cnow = 0,0
    eat,ceat = [(0,0)],[(0,0)]
    for i,j in zip(susi,csusi):
        x,v = i
        cal += v
        if cal-x > eat[-1][0]:
            now = x
            eat.append((cal-x,now))
        else:
            eat.append((eat[-1][0],now))
        cx,cv = j
        ccal += cv
        if ccal-(C-cx) > ceat[-1][0]:
            cnow = C-cx
            ceat.append((ccal-(C-cx),cnow))
        else:
            ceat.append((ceat[-1][0],cnow))
    
    ceat.reverse()
    ans = 0
    for i,j in zip(eat,ceat):
        eat,x = i
        ceat,cx = j
        ans = max(ans,eat+ceat-min(x,cx))

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

right1 = []
right2 = []
tmp = 0
for i in range(n):
  s,v = sushi[i]
  tmp += v
  right1.append([tmp-s,s])
  right2.append([tmp-2*s,s])
left1 = []
left2 = []
tmp = 0
for i in range(n)[::-1]:
  s,v = sushi[i]
  tmp += v
  left1.append([tmp-(c-s),c-s])
  left2.append([tmp-2*(c-s),c-s])
right1.sort()
left1.sort()
#print(right1)
#print(left1)

can.append(0)
can.append(right1[-1][0])
can.append(left1[-1][0])
#print(can)
for i in range(n):
  energy,s = right2[i]
  while left1[-1][1] + s >= c:
    left1.pop()
    if left1 == []:
      break
  else:
    can.append(energy + left1[-1][0])
    #print(s,left1[-1][1],left1)
    continue
  break
#print(can)
for i in range(n):
  energy,s = left2[i]
  while right1[-1][1] + s >= c:
    right1.pop()
    if right1 == []:
      break
  else:
    can.append(energy + right1[-1][0])
    #print(s,right1[-1][1],right1)
    continue
  break
print(max(can))
#print(can)

Submission status: Accepted

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

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

for i in range(N):
    xv[i][0],xv[i][1]=map(int,input().split())
    
xv.sort()

S=[0]*(N+1)
ans=0
r=[0]*N#止まる場所候補，時計回り
l=[0]*N#反時計

ma=0
ma_i=0
for i in range(N):
    S[i+1]=S[i]+xv[i][1]
    a=S[i+1]-xv[i][0]
    if a>ma:
        ma=a
        ma_i=i
    r[i]=ma_i
        
        
ma=0
ma_i=N-1      
for i in range(N):
    a=(S[-1]-S[N-i-1])-(C-xv[N-i-1][0])
    if a>ma:
        ma=a
        ma_i=N-i-1
    l[N-i-1]=ma_i
    
    
for i in range(N):#時計回りにiまで．
    temp1=S[i+1]-xv[i][0]#行ったきり
    temp2=temp1-xv[i][0]#逆回りも
    if i!=N-1:
        temp2+=(S[-1]-S[l[i+1]]) - (C-xv[l[i+1]][0])
    ans=max(ans,temp1,temp2)
      

for i in range(N):
    temp1=(S[-1]-S[i])-(C-xv[i][0])#行ったきり
    temp2=temp1-(C-xv[i][0])#逆回りも
    if i!=0:
        temp2+=S[r[i-1]+1] -xv[r[i-1]][0]
    ans=max(ans,temp1,temp2)
    
    
print(ans)

Submission status: Accepted

Solution code:
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,c = inm()
x = []
v = []
for i in range(n):
    xx,vv = inm()
    x.append(xx)
    v.append(vv)
l1 = [0]*n
l2 = [0]*n
r1 = [0]*n
r2 = [0]*n
acc = 0
for i in range(n):
    acc += v[i]
    l1[i] = max(l1[i-1], acc-x[i])
    l2[i] = max(l2[i-1], acc-2*x[i])
acc = 0
for i in range(n-1,-1,-1):
    acc += v[i]
    r1[i] = max(r1[(i+1)%n], acc-(c-x[i]))
    r2[i] = max(r2[(i+1)%n], acc-2*(c-x[i]))

ddprint(l1)
ddprint(l2)
ddprint(r1)
ddprint(r2)
mx = 0
for i in range(n):
    mx = max([mx, l1[i]+(r2[i+1] if i<n-1 else 0), \
                  r1[i]+(l2[i-1] if i>0 else 0)])
print(mx)

Submission status: Accepted

Solution code:
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue
#import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): #startline--------------------------------------------
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        ans = max(ans,max(r2[i]+l1[n-i],l2[i]+r1[n-i]))
    print(ans)

if __name__ == "__main__":
    main() #endline===============================================

Submission status: Accepted

Solution code:
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue
#import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): #startline--------------------------------------------
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        ans = max(ans,max(r2[i]+l1[n-i],l2[i]+r1[n-i]))
    print(ans)
if __name__ == "__main__":
    main() #endline===============================================

Submission status: Accepted

Solution code:
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue
#import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): #startline--------------------------------------------
    n,c = map(int,input().split())
    xv = [list(map(int,input().split())) for i in range(n)]
    x = [xv[i][0] for i in range(n)]
    v = [xv[i][1] for i in range(n)]
    r1,r2,l1,l2 = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
    ans = 0
    dis = 0
    for i in range(n):
        r1[i+1] = r1[i]+v[i]-(x[i]-dis)
        r2[i+1] = r2[i]+v[i]-2*(x[i]-dis)
        dis = x[i]
    dis = c
    for i in reversed(range(n)):
        l1[n-i] = l1[n-i-1]+v[i]-(dis-x[i])
        l2[n-i] = l2[n-i-1]+v[i]-2*(dis-x[i])
        dis = x[i]
    for i in range(n):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(n+1):
        subans = max(r2[i]+l1[n-i],l2[i]+r1[n-i])
        ans = max(ans,subans)
    print(ans)
if __name__ == "__main__":
    main() #endline===============================================

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())
  
# 右にいくつ、左にいくつ、を探索する方法はO(N**10)でNG
# 片方の寿司さけを固定することを考える。
# 残りの寿司を左回りにどこまで取るかは
# 「X個まで選べるとき価値が最大になるのはどの寿司か」をあらかじめ線形で計算しておく
# 引き返す場合の引き返さない場合の両パターン
# 逆回りでこれをやっておいたほうがあとあと楽っぽい。

best_sushi_noturn=[0]*(N+1) # 寿司を取らない場合もあるのでN+1
best_sushi_turn=[0]*(N+1) # 同上
bestval_noturn=0 # 引き返さない場合の最大価値
bestval_turn=0 # 引き返す場合の最大価値
valsum=0 # そこまでの累計価値
for i in range(1,N+1):
  # i個寿司を取るのときの最適な選択を返す
  # i=0のときは寿司を取らないとき
  # i=1個目の寿司にはX[N-1]を入れたい
  dist=C-X[N-i]
  valsum+=V[N-i]
  if valsum-dist>bestval_noturn:
    bestval_noturn=valsum-dist
    best_sushi_noturn[i]=bestval_noturn
  else:
    best_sushi_noturn[i]=best_sushi_noturn[i-1] # 改善しない場合はその前の値を返す
  if valsum-dist*2>bestval_turn:
    bestval_turn=valsum-dist*2
    best_sushi_turn[i]=bestval_turn
  else:
    best_sushi_turn[i]=best_sushi_turn[i-1] # 改善しない場合はその前の値を返す

# 逆回りの場合の最大価値を表す配列ができたので、正順で取る個数を決め打ちして最大価値を算出
valsum=0
# 正順で一つも取らない場合の最大価値を算出しておく
ans=best_sushi_noturn[N]
for i in range(N):
  valsum+=V[i]
  cost=X[i]
  # 正順で引き返す場合
  if valsum-cost*2+best_sushi_noturn[N-(i+1)]>ans:
    ans=valsum-cost*2+best_sushi_noturn[N-(i+1)]
  # 逆順で引き返す場合
  if valsum-cost+best_sushi_turn[N-(i+1)]>ans:
    ans=valsum-cost+best_sushi_turn[N-(i+1)]

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

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())
clockwise = list(accumulate(v))
counterclockwise = list(accumulate(v[::-1]))[::-1]
for i in range(N):
    clockwise[i] -= x[i]
    counterclockwise[i] -= C-x[i]
clockwise_max = [0] * N
for i in range(1, N):
    clockwise_max[i] = max(clockwise_max[i-1], clockwise[i-1])
counterclockwise_max = [0] * N
for i in range(N-1)[::-1]:
    counterclockwise_max[i] = max(counterclockwise_max[i+1], counterclockwise[i+1])
ans = 0
for i in range(N):
    ans = max(ans, clockwise[i])
    ans = max(ans, clockwise[i]-x[i]+counterclockwise_max[i])
for i in range(N)[::-1]:
    ans = max(ans, counterclockwise[i])
    ans = max(ans, counterclockwise[i]-(C-x[i])+clockwise_max[i])
print(ans)

Submission status: Accepted

Solution code:
n,c=map(int, input().split())
a = [[0,0]]+[list(map(int, input().split())) for i in range(n)]
l=[[0,0] for i in range(n+1)]
r=[[0,0] for i in range(n+1)]
b = 0
b1 = 0
# 最大値を格納
x=[0]*(n+1)
y=[0]*(n+1)
ans=0
ansl=0
ansr=0

#  時計周りで累積和を取る。折り返しがない時の最大値を探す。
ans1=-10**20
ans2=-10**20
for i in range(n+1):
    b+=a[i][1]
    l[i][0]=a[i][0]
    l[i][1]=b
    if b-l[i][0]>ans1:
        ans1=b-a[i][0]
        x[i]=ans1
    else:
        x[i]=x[i-1]

for i in range(n+1):
    b1+=a[-i][1]
    r[i][0]=c-a[-i][0]
    r[i][1]=b1
    if b1-r[i][0]>ans2:
        ans2=b1-r[i][0]
        y[i]=ans2
    else:
        y[i]=y[i-1]
r[0][0]=0
y[0]=0


# 反時計周りで折り返して時計周りへ進む
for i in range(n):
    cnt=x[n-i]+r[i][1]-2*r[i][0]
    ansr=max(cnt,ansr)

# 時計周りで折り返して反時計周りへ進む
for i in range(n):
    cnt=y[n-i]+l[i][1]-2*l[i][0]
    ansl=max(cnt,ansl)
print(max(ansr,ansl))

Submission status: Accepted

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

F = [0 for _ in range(N+1)]
F[N] = A[N][1]-(C-A[N][0])
for i in range(N-1,0,-1):
    F[i] = F[i+1]+A[i][1]-(A[i+1][0]-A[i][0])
G = [0 for _ in range(N+1)]
for i in range(1,N+1):
    G[i] = G[i-1]+A[i][1]-(A[i][0]-A[i-1][0])
cmax = max(max(F),max(G))
dmax = 0
for i in range(N-1,0,-1):
    dmax = max(dmax,F[i+1])
    cmax = max(cmax,dmax+G[i]-A[i][0])
emax = 0
for i in range(2,N+1):
    emax = max(emax,G[i-1])
    cmax = max(cmax,emax+F[i]-(C-A[i][0]))
print(cmax)