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())
#Aは時計回り
A,B=[],[]
allv=0
for i in range(N):
  a,b=map(int, input().split())
  A.append([a,b])
  B.append([C-a,b])
  allv+=b
A,B=sorted(A),sorted(B)
OA,OB,AS,BS=[],[],[],[]
ax,av,bx,bv=0,0,0,0
for i in range(N):
  ax,bx=A[i][0],B[i][0]
  av+=A[i][1]
  bv+=B[i][1]
  OA.append((ax,av))
  OB.append((bx,bv))
  AS.append(av-ax)
  BS.append(bv-bx)
#OA→AO→OBといくとき
d=BS[0]
e=AS[0]
BSma,ASma=[-10000]*N,[-10000]*N
for i in range(N):
  BSma[i]=max(d,BS[i])
  d=BSma[i]
  ASma[i]=max(e,AS[i])
  e=ASma[i]
  
ansa=0
for i in range(N-1):
  #iまで行く
  bma=N-i
  oa=OA[i][1]-OA[i][0]
  ao=-OA[i][0]
  ob=BSma[-2-i]
  d=max(oa,oa+ao+ob)
  ansa=max(ansa,d)
ansb=0
for i in range(N-1):
  #iまで行く
  ama=N-i
  ob=OB[i][1]-OB[i][0]
  bo=-OB[i][0]
  oa=ASma[-2-i]
  d=max(ob,ob+bo+oa)
  ansb=max(ansb,d)
print(max(ansa,ansb,allv-(C-max(OA[0][0],OB[0][0]))))

Submission status: Accepted

Solution code:
import numpy as np
import sys
input2 = sys.stdin.read

# A: Anti-clockwise, B: Clockwise, V: Values
n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    # Cumulative Values returning to Start

MA = np.zeros(n + 1, dtype=np.int64)
MB = np.zeros(n + 1, dtype=np.int64)
MRA = np.zeros(n + 1, dtype=np.int64)
MRB = np.zeros(n + 1, dtype=np.int64)


def max_mem(lis, mlis):
    for i in range(n):
        mlis[i + 1] = max(mlis[i], lis[i])


max_mem(XA, MA)
max_mem(XB, MB)
max_mem(RXA, MRA)
max_mem(RXB, MRB)

if n == 1:
    print(MA[1])
    exit()

#print(MA, MB, MRA, MRB)

res1, res2 = 0, 0
for i in range(n + 1):
    res1 = max(res1, MA[i] + MRB[n - i])
    res2 = max(res2, MB[i] + MRA[n - i])
    #print(res1, res2)

print(max(res1, res2))

Submission status: Accepted

Solution code:
import numpy as np
import sys
input2 = sys.stdin.read

# A: Anti-clockwise, B: Clockwise, V: Values
n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    # Cumulative Values returning to Start
NMA, NMB = XA.max(), XB.max()


def ind(lis, maxi):
    for i, x in enumerate(lis):
        if x == maxi:
            return i


MRA2, MRB2 = max(RXA[:-1], default=0), max(RXB[:-1], default=0)
mrai = ind(RXA, MRA2)
mrbi = ind(RXB, MRB2)

if not mrai and not mrbi:
    mrai, mrbi = 0, 0

MA2 = max(0, max(XA[:n - 1 - mrbi], default=0))
MB2 = max(0, max(XB[:n - 1 - mrai], default=0))
res = max(NMA, NMB, MA2 + MRB2, MB2 + MRA2)


for k in range(-1, -10 if n > 10 else -2, -1):
    MA3, MB3 = max(XA[:k], default=0), max(XB[:k], default=0)
    mai3 = ind(XA, MA3)
    mbi3 = ind(XB, MB3)

    if not mai3 and not mbi3:
        mai3, mbi3 = 0, 0

    MRA3 = max(0, max(RXA[:n - 1 - mbi3], default=0))
    MRB3 = max(0, max(RXB[:n - 1 - mai3], default=0))

    res = max(res, MA3 + MRB3, MB3 + MRA3)
print(res)

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
rl=[[0]*2 for _ in range(n+1)]
ls,rs=0,0
xv=[[0,0]]+[list(map(int,input().split())) for _ in range(n)]
for i in range(1,n+1):
    j,k=xv[i]
    rs+=k
    rl[i][0],rl[i][1]=max(rl[i-1][0],rs-j),max(rl[i-1][1],rs-2*j)
ans=rl[n][0]
for i in range(n):
    ls+=xv[n-i][1]
    ans=max(ans,rl[n-i-1][1]+ls-(c-xv[n-i][0]),rl[n-i-1][0]+ls-(c-xv[n-i][0])*2)
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


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

    # [0, i]までで得られるカロリーの最大値
    dp_right = [0] * N
    dp_right[0] = -X[0] + V[0]
    for i in range(1, N):
        dp_right[i] = dp_right[i - 1] + V[i] - (X[i] - X[i - 1])

    # [i, n - 1] までで得られるカロリーの最大値
    dp_left = [0] * N
    dp_left[N - 1] = V[N - 1] - (C - X[N - 1])
    for i in range(N - 2, -1, -1):
        dp_left[i] = dp_left[i + 1] + V[i] - (X[i + 1] - X[i])

    # 最大値に書き換える
    for i in range(1, N):
        if dp_right[i] >= dp_right[i - 1]:
            continue
        else:
            dp_right[i] = dp_right[i - 1]

    for i in range(N - 2, -1, -1):
        if dp_left[i] >= dp_left[i + 1]:
            continue
        else:
            dp_left[i] = dp_left[i + 1]

    # 折り返さない
    ans = max(0, dp_left[0], dp_right[-1])
    # 時計周りに進んで，i個目の寿司で半時計周りに折り返す
    for i in range(N - 1):
        tmp = dp_right[i] + dp_left[i + 1] - X[i]
        if tmp > ans:
            ans = tmp

    # 最初に半時計周りに進む
    for i in range(N - 1, 0, -1):
        tmp = dp_left[i] + dp_right[i - 1] - (C - X[i])
        if tmp > ans:
            ans = tmp

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,c = map(int,input().split())

x = []
v = []
array1 = []
array2 = []

for i in range(n):
  a,b = map(int, input().split())
  x.append(a)
  v.append(b)
  
rx = []
rv = []
for i in reversed(range(len(x))):
  rx.append(c-x[i])
  rv.append(v[i])
  
count = x[0]
array1.append(v[0] - x[0])
for i in range(1,n):
  array1.append(v[i]-x[i]+array1[i-1]+count)
  count = x[i]
  
count = rx[0]
array2.append(rv[0] - rx[0])
for i in range(1,n):
  array2.append(rv[i]-rx[i]+array2[i-1]+count)
  count = rx[i]

num = 0
max_array = []
for i in range(len(array1)-1):
  num = max(num, array1[i])
  max_array.append(num)

max_array = list(reversed(max_array))

num = 0
rmax_array = []
for i in range(len(array2)-1):
  num = max(num, array2[i])
  rmax_array.append(num)
  
rmax_array = list(reversed(rmax_array))
  
  
ans = 0
for i in range(n):
  if i != n-1:
    tmp = max(array1[i], array1[i]-x[i]+rmax_array[i])
    ans = max(ans, tmp)
  else:
    ans = max(ans, array1[i])
  
for i in range(n):
  if i != n-1:
    tmp = max(array2[i], array2[i]-rx[i]+max_array[i])
    ans = max(ans, tmp)
  else:
    ans = max(ans, array2[i])
    
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read

N,C, *XV = map(int, read().split())#全部
X=XV[::2]
V=XV[1::2]

m1=[0]
m2=[0]

s=0
ans=0
for x,v in zip(X,V):
    s+=v
    ans=max(ans,s-x)
    m1.append(max(m1[-1],s-x))
    m2.append(max(m2[-1],s-2*x))
s=0
i=0
for x,v in reversed(list(zip(X,V))):
    s+=v
    x=C-x
    ans=max(ans,s-2*x+m1[-2-i],s-x+m2[-2-i])
    i+=1
print(ans)

Submission status: Accepted

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

rcur = 0
lcur = 0
rmax = 0
lmax = 0
r = [[0,0]]
for i in range(n):
    a,b = x[i]
    rcur += b
    lcur = a
    if rmax < rcur-lcur:
        rmax = rcur-lcur
        lmax = lcur
    r.append([rmax,lmax])

rcur = 0
lcur = 0
rmax = 0
lmax = 0
l = [[0,0] for i in range(n+1)]
for i in range(1,n+1):
    a,b = x[-i]
    rcur += b
    lcur = c-a
    if rmax < rcur-lcur:
        rmax = rcur-lcur
        lmax = lcur
    l[-1-i] = [rmax,lmax]


ans = 0

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

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,C = LI()
    a = [LI() for _ in range(n)]
    u = [_[0] for _ in a]
    x = [_[1] for _ in a]
    b = [0] * n
    c = [0] * n
    d = [0] * n
    e = [0] * n
    b[0] = x[0]
    c[-1] = x[-1]
    for i in range(1, n):
        b[i] = b[i-1] + x[i]
    for i in range(n-2, -1, -1):
        c[i] = c[i+1] + x[i]
    d[0] = x[0] - u[0]
    e[-1] = x[-1] - (C-u[-1])
    for i in range(1, n):
        d[i] = max(b[i]-u[i], d[i-1])
    for i in range(n-2, -1, -1):
        e[i] = max(c[i]-(C-u[i]), e[i+1])

    r = max(d[-1], e[0], 0)
    for i in range(n):
        if i < n-1 and r < b[i] - u[i] * 2 + e[i+1]:
            r = b[i] - u[i] * 2 + e[i+1]
        if i > 0 and r < c[i] - (C-u[i]) * 2 + d[i-1]:
            r = c[i] - (C-u[i]) * 2 + d[i-1]


    return r



print(main())

###

Submission status: Accepted

Solution code:
#!python3

# input
N, C = list(map(int, input().split()))
X, V = [0] * (N + 1), [None] * N
for i in range(N):
    X[i + 1], V[i] = list(map(int, input().split()))


def main():
    Vsum = [0] * (N + 1)
    for i in range(N):
        Vsum[i + 1] = Vsum[i] + V[i]
    
    A, B = [0] * (N + 1), [0] * (N + 1)
    for i in range(1, N + 1):
        A[i] = max(A[i - 1], Vsum[i] - X[i])
        B[i] = max(B[i - 1], Vsum[-1] - Vsum[-1 - i] - (C - X[-i]))
    
    ans = 0
    for i in range(1, N):
        ans = max(ans, A[i] + B[N - i] - X[i])
    for i in range(1, N):
        ans = max(ans, B[i] + A[N - i] - (C - X[-i]))
    ans = max(ans, A[N])
    ans = max(ans, B[N])

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, C = list(map(int, sys.stdin.buffer.readline().split()))
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]

XY.sort()
XY = np.array(XY, dtype=int)
X = XY[:, 0]
Y = XY[:, 1]

# 右に行ってから左に行けるだけ行く
lefts = np.zeros(N + 1, dtype=int)
rights = np.zeros(N + 1, dtype=int)
lefts[1:] = np.maximum.accumulate(Y.cumsum() - X)
rights[1:] = Y[::-1].cumsum() - (C - X[::-1]) * 2
ans1 = max(lefts + rights[::-1])

# 左に行ってから右に行けるだけ行く
lefts = np.zeros(N + 1, dtype=int)
rights = np.zeros(N + 1, dtype=int)
lefts[1:] = Y.cumsum() - X * 2
rights[1:] = np.maximum.accumulate(Y[::-1].cumsum() - (C - X[::-1]))
ans2 = max(lefts + rights[::-1])

ans = max(ans1, ans2, 0)
print(ans)

Submission status: Accepted

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

go = [[0] * (n+1) for _ in range(2)]
turn = [[0] * (n+1) for _ in range(2)]

tmp = 0
g_max = 0
t_max = 0
for i in range(1,n+1):
    tmp += xv[i-1][1]
    go[0][i] = g_max = max(tmp - xv[i-1][0], g_max)
    turn[0][i] = t_max = max(tmp - xv[i-1][0] * 2, t_max)
    
tmp = 0
g_max = 0
t_max = 0
for i in range(n, 0, -1):
    tmp += xv[i-1][1]
    go[1][i] = g_max = max(tmp - (c - xv[i-1][0]), g_max)
    turn[1][i] = t_max = max(tmp - (c - xv[i-1][0]) * 2, t_max)

ans = 0
for i in range(1, n+1):
    ans = max(go[0][i] + turn[1][(i+1)%(n+1)], ans)
    ans = max(go[1][i] + turn[0][i-1], ans)
    
print(ans)

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for i in range(n)]
fa=[0]*(n+1)
ga=[0]*(n+1)
fb=[0]*(n+1)
gb=[0]*(n+1)
ans1=0
ans2=0
fa[1]=xv[0][1]-xv[0][0]
ga[1]=max(fa[1],fa[0])
fb[1]=xv[-1][1]-(c-xv[-1][0])
gb[1]=max(fb[0],fb[1])
for i in range(1,n):
  fa[i+1]=fa[i]+xv[i][1]-(xv[i][0]-xv[i-1][0])
  ga[i+1]=max(ga[i],fa[i+1])
  fb[i+1]=fb[i]+xv[-i-1][1]-(xv[-i][0]-xv[-i-1][0])
  gb[i+1]=max(gb[i],fb[i+1])
ans1=ga[n]
ans2=gb[n]
for i in range(0,n):
  ans1=max(ans1,ga[i]+fb[n-i]-(c-xv[-n+i][0]))
  ans2=max(ans2,gb[i]+fa[n-i]-xv[n-i-1][0])
print(max(ans1,ans2))

Submission status: Accepted

Solution code:

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

xv = []

for i in range(N):

    x,v = map(int,input().split())
    xv.append([x,v])

xv.sort()

ldis = [0]
lcal = [0]

for i in range(N):

    ldis.append(xv[i][0])
    lcal.append(lcal[-1] + xv[i][1])

lmax = [0]
for i in range(N):
    i += 1
    lmax.append( max(lmax[-1] , lcal[i] - ldis[i]) )

rdis = [0]
rcal = [0]

for i in range(N):
    i = N-1-i
    rdis.append(C - xv[i][0])
    rcal.append(rcal[-1] + xv[i][1])

rmax = [0]
for i in range(N):
    i += 1
    rmax.append ( max(rmax[-1] , rcal[i] - rdis[i]) )

lmax2 = [0]
for i in range(N):
    i += 1
    lmax2.append( max(lmax2[-1] , lcal[i] - ldis[i] * 2) )
rmax2 = [0]
for i in range(N):
    i += 1
    rmax2.append ( max(rmax2[-1] , rcal[i] - rdis[i] * 2) )

ans = 0
for i in range(N+1):

    if i != N-i:
        ans = max(ans,lmax[i] + rmax2[N-i],lmax2[i] + rmax[N-i])

#print (lmax,lmax2,rmax,rmax2)
print (ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
N, C = map(int, input().split())
xs = [0]
ys = [0]
vs = [0]
us = [0]
ws = [0]
for i in range(N):
    x, v = map(int, input().split())
    us.append(us[-1]+v-x+xs[-1])
    vs.append(v)
    xs.append(x)
for i in range(N, 0, -1):
    y = C-xs[i]
    ws.append(ws[-1]+vs[i]-y+ys[-1])
    ys.append(y)
#vs = list(accumulate(vs))
#ws = list(accumulate(ws))
zs = [0] * (N+1)
c = 0
r = 0
for i, u in enumerate(us):
    if c <= u:
        c, ci = u, i
        r = max(r, c)
    zs[i] = (c, ci)
zs2 = [0] * (N+1)
c = 0
for i, u in enumerate(ws):
    if c <= u:
        c, ci = u, i
        r = max(r, c)
    zs2[i] = (c, ci)
for z, zi in zs:
    #print(z, zi, zs2[N-zi])
    c = z+zs2[N-zi][0]-xs[zi]
    r = max(r, c)
for z, zi in zs2:
    #print(z, zi, zs2[N-zi])
    c = z+zs[N-zi][0]-ys[zi]
    r = max(r, c)
#print(us, ws, zs, zs2, ys, sep="\n")
print(r)
#print(6500000000)

Submission status: Accepted

Solution code:
import copy

N, C= map(int,input().split())
XV = sorted([list(map(int,input().split())) for _ in range(N)])
acmXV = []
dbl_acmXV = []

for i, xv in enumerate(XV):
  x,v = xv
  if i == 0:
    acmXV.append(v-x)
    dbl_acmXV.append(v-x*2)
  else:
    acmXV.append(v-(x-XV[i-1][0])+acmXV[i-1])
    dbl_acmXV.append(v-(x-XV[i-1][0])*2+dbl_acmXV[i-1])

acmXV_rev = [0 for _ in range(N)]
dbl_acmXV_rev = [0 for _ in range(N)]
for i in range(N-1, -1, -1):
  x,v = XV[i]
  if i == N-1:
    acmXV_rev[i] = v-(C-x)
    dbl_acmXV_rev[i] = v-(C-x)*2
  else:
    acmXV_rev[i] = (v-(XV[i+1][0]-XV[i][0])+acmXV_rev[i+1])
    dbl_acmXV_rev[i] = (v-(XV[i+1][0]-XV[i][0])*2+dbl_acmXV_rev[i+1])


max_acmXV_rev = copy.deepcopy(acmXV_rev)
max_dbl_acmXV_rev = copy.deepcopy(dbl_acmXV_rev)
for i in range(N-2,-1,-1):
  max_acmXV_rev[i] = max(max_acmXV_rev[i], max_acmXV_rev[i+1])
  max_dbl_acmXV_rev[i] = max(max_dbl_acmXV_rev[i],max_dbl_acmXV_rev[i+1])

ans = max(0,max(acmXV),max(acmXV_rev))
for i in range(N-1):
  ans = max(ans, dbl_acmXV[i]+max_acmXV_rev[i+1], acmXV[i]+max_dbl_acmXV_rev[i+1]) 
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
import sys
input = sys.stdin.buffer.readline
N,C= map(int,input().split())
x, v = np.array([list(map(int,input().split())) for i in [0]*N]).T.astype(np.int64)
INF = 10**15

rx = C - x[::-1]
dx = np.zeros(N+2).astype(np.int64)
dx[N+1] = C
dx[1:-1] = x
dx = np.diff(dx)

cand = []

# not turnaround 
rv = v - dx[:-1]
rc = np.maximum.accumulate(np.cumsum(rv))
best = rc[-1]
cand.append(best)

lv = v[::-1] - dx[::-1][:-1]
lc = np.maximum.accumulate(np.cumsum(lv))
best = lc[-1]
cand.append(best)

# turnaround
first = (rc-x)[:-1] # ->,<-
second = lc[:-1][::-1] # <-
if first.size:
    cand.append(np.max(first+second))

first = (lc-rx)[:-1]
second = rc[:-1][::-1]
if first.size:
    cand.append(np.max(first+second))

cand.append(0)
print(max(cand))

Submission status: Accepted

Solution code:

import sys
def input():
	return sys.stdin.readline().strip()

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

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


right_max = 0
right_list = []
left_max = 0
left_list = []
for i in range(N):
	if right_max < sushi_sum[i + 1] - sushi[i][0]:
		right_max = sushi_sum[i + 1] - sushi[i][0]
	right_list.append(sushi_sum[i + 1] - sushi[i][0])
	if left_max < sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0]):
		left_max = sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0])
	left_list.append(sushi_sum[-1] - sushi_sum[i] - (C - sushi[i][0]))

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

right_left_max = 0
for i in range(N - 1):
	right_left_max = max(right_left_max, sushi_sum[i + 1] - 2*sushi[i][0] + left_list[i + 1])

left_right_max = 0
for i in range(1, N):
	left_right_max = max(left_right_max, sushi_sum[-1] - sushi_sum[i] - 2*(C - sushi[i][0]) + right_list[i - 1])

print(max(right_max, left_max, right_left_max, left_right_max))

Submission status: Accepted

Solution code:
from itertools import accumulate

N, C, *XV = map(int, open(0).read().split())

X = XV[::2]
V = XV[1::2]

A = [0] + list(accumulate(V))

ans = m0 = m1 = 0
for i in reversed(range(N)):
    a = A[i + 1] - X[i]
    ans = max(ans, a + m0, a - X[i] + m1)

    c = C - X[i]
    m = A[N] - A[i] - c
    m0 = max(m0, m - c)
    m1 = max(m1, m)

print(max(ans, m1))

Submission status: Accepted

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

def main():
    N,C = map(int, input().split())
    X = []
    for _ in range(N):
        X.append(list(map(int, input().split())))
    
    cw = [0] # 時計回りに数えて i 番目までを食べた時に摂取できるカロリー
    ccw = [0] # 反時計回り
    for i in range(N):
        cw.append(cw[i] + X[i][1])
        ccw.append(ccw[i] + X[N-1-i][1])
    for i in range(N):
        cw[i+1] -= X[i][0]
        ccw[i+1] -= C - X[N-1-i][0]

    ma = 0
    ga = []
    for i in range(0, N+1):
        ma = max(ma, cw[i])
        ga.append(ma)
    ma = 0
    gb = []
    for i in range(0, N+1):
        ma = max(ma, ccw[i])
        gb.append(ma)

    ans = 0
    for bi in range(N+1):
        tmp = ccw[bi] + ga[N-bi]
        if bi > 0:
            tmp -= C - X[N-bi][0]
        ans = max(ans, tmp)

    for ai in range(N+1):
        tmp = cw[ai] + gb[N-ai]
        if ai > 0:
            tmp -= X[ai-1][0]
        ans = max(ans, tmp)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,c = map(int,input().split())

cp = [0]*n
cp_rev = [0]*n
d = [0]*n

for i in range(n):
    x,v = map(int,input().split())
    d[i] = x
    cp[i] = v
    cp_rev[n-1-i] = v

sm = [0]*n
sm_rev = [0]*n
max_sm = [0]*n
max_sm_rev = [0]*n

sm[0] = cp[0] - d[0]
sm_rev[0] = cp_rev[0] - (c - d[n-1])
max_sm[0] = sm[0]
max_sm_rev[0] = sm_rev[0]

for i in range(1,n):
    sm[i] = sm[i-1] + cp[i] - d[i] + d[i-1]
    sm_rev[i] = sm_rev[i-1] + cp_rev[i] - (c - d[n-1-i]) + c - d[n-i]
    max_sm[i] = max(max_sm[i-1],sm[i])
    max_sm_rev[i] = max(max_sm_rev[i-1],sm_rev[i])

ret_ind = sm.index(max(sm))
ret_ind_rev = sm_rev.index(max(sm_rev)) 

ans = 0

for i in range(ret_ind + 1):
    ans = max(ans, sm[i])
    if n-i-2 >= 0:
        ans = max(ans, sm[i] - d[i] + max_sm_rev[n-i-2])

for i in range(ret_ind_rev + 1):
    ans = max(ans, sm_rev[i])
    if n-i-2 >= 0:
        ans = max(ans,sm_rev[i] - (c - d[n-1-i]) + max_sm[n-i-2])

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

N, C = map(int, input().split())
x, v = (
    zip(*(map(int, input().split()) for _ in range(N))) if N else
    ((), ())
)

# 初期位置から時計回り／反時計回りに移動したときの利益の最大値に関する累積値を前計算しておく
acc_l = list(
    accumulate(
        (
            V - X
            for X, V in zip(
                [0] + [C - X for X in x[::-1]],
                accumulate((0,) + v[::-1])
            )
        ),
        max
    )
)
acc_r = list(
    accumulate(
        (
            V - X
            for X, V in zip(
                (0,) + x,
                accumulate((0,) + v)
            )
        ),
        max
    )
)
# 時計回りに移動した後に、反時計回りに移動 または
# 反時計回りに移動した後に、時計回りに移動 のどちらかの戦略に限ってよい
ans = max(
    max(
        V - 2 * X + acc_l[N - i]
        for i, X, V in zip(
            range(N + 1),
            (0,) + x,
            accumulate((0,) + v)
        )
    ),
    max(
        V - 2 * X + acc_r[N - i]
        for i, X, V in zip(
            range(N + 1),
            [0] + [C - X for X in x[::-1]],
            accumulate((0,) + v[::-1])
        )
    )
)

print(ans)

Submission status: Accepted

Solution code:


class SegmentTree:
    def __init__(self, L, op, ide):
        self.op = op
        self.ide = ide
        self.sz = len(L)
        self.n = 1
        self.s = 1
        for i in range(1000):
            self.n *= 2
            self.s += 1
            if self.n >= self.sz:
                break
        self.node = [self.ide]*(2*self.n-1)

        for i in range(self.sz):
            self.node[i+self.n-1] = L[i]

        for i in range(self.n-2,-1,-1):
            self.node[i] = self.op(self.node[i*2+1],self.node[i*2+2])
    
    def add(self, a, x):
        k = a+self.n-1
        self.node[k] += x
        for i in range(1000):
            k = (k-1)//2
            self.node[k] = self.op(self.node[2*k+1], self.node[2*k+2])
            if k <= 0:
                break
    
    def substitute(self, a, x):
        k = a+self.n-1
        self.node[k] = x
        for i in range(1000):
            k = (k-1)//2
            self.node[k] = self.op(self.node[2*k+1], self.node[2*k+2])
            if k <= 0:
                break

    def get_one(self, a):
        k = a+self.n-1
        return self.node[k]
    
    def get(self, l, r):
        res = self.ide
        n = self.n
        if self.sz <= r or 0 > l:
            print("ERROR: the indice are wrong.")
            return False

        for i in range(self.s):
            count = 2**i-1
            a = (r+1)//n
            b = (l-1)//n
            if a-b == 3:
                res = self.op(self.node[count+b+1],res)
                res = self.op(self.node[count+b+2],res)
                right = a*n
                left = (b+1)*n-1
                break
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                right = a*n
                left = (b+1)*n-1
                break
            n = n//2

        #left
        n1 = n//2        
        for j in range(i+1,self.s):
            count = 2**j-1 
            a = (left+1)//n1
            b = (l-1)//n1
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                left = (b+1)*n1-1                
            n1 = n1//2

        #right
        n1 = n//2        
        for j in range(i+1,self.s):
            count = 2**j-1 
            a = (r+1)//n1
            b = (right-1)//n1
            if a-b == 2:
                res = self.op(self.node[count+b+1],res)
                right = a*n1                
            n1 = n1//2
        return res

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

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

R1 = [0]
R2 = [0]
r1,r2 = 0,0

prev = 0

for x in X:
    r1+=x[1]-(x[0]-prev)
    r2+=x[1]-2*(x[0]-prev)
    R1.append(r1)
    R2.append(r2)
    prev = x[0]

L1 = [0]
L2 = [0]
l1,l2 = 0,0

X = X[::-1]

prev = C

for x in X:
    l1+=x[1]-((C-x[0])-(C-prev))
    l2+=x[1]-2*((C-x[0])-(C-prev))
    L1.append(l1)
    L2.append(l2)
    prev = x[0]

STR1 = SegmentTree(R1,max,-10**27)
STR2 = SegmentTree(R2,max,-10**27)
STL1 = SegmentTree(L1,max,-10**27)
STL2 = SegmentTree(L2,max,-10**27)
max_score = 0
for i in range(N+1):
    max_score = max(STR1.get(0,N-i)+STL2.get(0,i),STR2.get(0,N-i)+STL1.get(0,i),max_score)

print(max_score)

Submission status: Accepted

Solution code:
n, c = list(map(int, input().split()))

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

# 左のある箇所まで行ってから、右のある箇所まで行って終了
# 右のある箇所まで行ってから、左のある箇所まで行って終了
# のどっちか。「最初から右／左の一方向だけ行って終了」もあるが、上記2つの特殊パターンとして扱えることに解説を読んで気づいた。
value_sum = [0] * (n+1)
for i in range(n):
	value_sum[i+1] = value_sum[i] + sushi[i][1]
value_sum_inv = [0] * (n+1)
for i in range(n):
	value_sum_inv[i+1] = value_sum_inv[i] + sushi[n-1 - i][1]

max_arr = [0] * (n+1)
# max_arr = 始点からsushi[n]まで時計回りに進んでよい（その前に止まっても良い）ときの最適スコア
# [0, s[0]まで、s[1]まで、……]
for i in range(n):
	max_arr[i+1] = max(max_arr[i], value_sum[i+1] - sushi[i][0])

max_arr_inv = [0] * (n+1)
# max_arr_inv = 始点からsushi[n-1 - i]まで反時計回りに進んでよい（その前に止まっても良い）ときの最適スコア
# [0, s[n-1]まで、s[n-2]まで、……]
for i in range(n):
	max_arr_inv[i+1] = max(max_arr_inv[i], value_sum_inv[i+1] - (c - sushi[n-1 - i][0]) )

"""print(max_arr)
print(max_arr_inv)
"""
ans = 0 #移動なし

now = max_arr[n]
ans = max(ans, now)

for i in range(n-1, -1, -1): #最初に左に行くときの到達点
	now = value_sum_inv[n - i] - 2 * (c - sushi[i][0]) + max_arr[i]
	ans = max(ans, now)

now = max_arr_inv[n]
ans = max(ans, now)

for i in range(n): #最初に右に行くときの到達点
	now = value_sum[i+1] - 2 * (sushi[i][0]) + max_arr_inv[n-1 - i]
	ans = max(ans, now)
"""	print(now)
	print( value_sum[i+1] , (sushi[i][0]) , max_arr_inv[n-1 - i])
"""
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
inpl = lambda: tuple(map(int,input().split()))

N, C = inpl()
xv = [None]*N
for i in range(N):
    xv[i] = inpl()
xv.sort()

Rs = [0]*(N+1)
Ls = [0]*(N+1)
Rd = [0]*(N+1)
Ld = [0]*(N+1)
RsMax = LsMax = RdMax = LdMax = 0
RvSum = LvSum = 0
RsCur = LsCur = RdCur = LdCur = 0
for i in range(1,N+1):
    RvSum += xv[i-1][1]
    LvSum += xv[N-i][1]
    RsCur = RvSum - xv[i-1][0]
    RdCur = RvSum - xv[i-1][0]*2
    LsCur = LvSum - (C-xv[N-i][0])
    LdCur = LvSum - (C-xv[N-i][0])*2
    Rs[i] = max(Rs[i-1],RsCur)
    Rd[i] = max(Rd[i-1],RdCur)
    Ls[i] = max(Ls[i-1],LsCur)
    Ld[i] = max(Ld[i-1],LdCur)
Rans = max(Rs[i]+Ld[N-i] for i in range(N+1))
Lans = max(Ls[i]+Rd[N-i] for i in range(N+1))
ans = max(Rans,Lans)
print(ans)

Submission status: Accepted

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

right_turn_sum = [0]
for i in range(N):
    right_turn_sum.append(sushi[i][1]+right_turn_sum[i])
for i in range(N):
    right_turn_sum[i+1] -= sushi[i][0]
right_turn_to_zero = [0]
for i in range(N):
    right_turn_to_zero.append(right_turn_sum[i+1]-sushi[i][0])

left_turn_sum = [0]
for i in range(N):
    left_turn_sum.append(sushi[-1-i][1]+left_turn_sum[i])
for i in range(N):
    left_turn_sum[i+1] -= (C - sushi[-1-i][0])
left_turn_to_zero = [0]
for i in range(N):
    left_turn_to_zero.append(left_turn_sum[i+1]-(C-sushi[-1-i][0]))


ans = max(right_turn_sum)
ans = max(left_turn_sum+[ans])

maxi = 0
for i in range(N+1):
    if maxi < right_turn_sum[i]:
        maxi = right_turn_sum[i]
    right_turn_sum[i] = max(maxi, right_turn_sum[i])

maxi = 0
for i in range(N+1):
    if maxi < right_turn_to_zero[i]:
        maxi = right_turn_to_zero[i]
    right_turn_to_zero[i] = max(maxi, right_turn_to_zero[i])

maxi = 0
for i in range(N+1):
    if maxi < left_turn_sum[i]:
        maxi = left_turn_sum[i]
    left_turn_sum[i] = max(maxi, left_turn_sum[i])

maxi = 0
for i in range(N+1):
    if maxi < left_turn_to_zero[i]:
        maxi = left_turn_to_zero[i]
    left_turn_to_zero[i] = max(maxi, left_turn_to_zero[i])


for i in range(N+1):
    ans = max(ans, right_turn_to_zero[i]+left_turn_sum[N-i])

for i in range(N+1):
    ans = max(ans, left_turn_to_zero[i]+right_turn_sum[N-i])
print(ans)

Submission status: Accepted

Solution code:
from itertools import*
from numpy import array
n,c=map(int,input().split())

l1=[]
l2=[]
for i in range(n):
    x,v=map(int,input().split())
    l1.append(x)
    l2.append(v)
#print(l1,l2)

ll=array([0]+l1)
lll=array([0]+list(accumulate(l2)))
lr=array([0]+[c-i for i in l1][::-1])
llr=array([0]+list(accumulate(l2[::-1])))
x=lll-ll
y=llr-lr
for i in range(1,n+1):
    x[i]=max(x[i-1],x[i])
    y[i]=max(y[i-1],y[i])
z=array([min(ll[::-1][i],lr[i])for i in range(n+1)])
print(max(x[::-1]+y-z))