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:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n,c = map(int,readline().split())
R = [0]*n
chk = []
pre_x = 0
for i in range(n):
  x,v = map(int,readline().split())
  chk.append((x,v))
  R[i] = R[i-1]-(x-pre_x)+v
  pre_x = x

L = [0]*(n+1)
nex_x = c
for i,p in enumerate(chk[::-1]):
  x,v = p
  L[n-1-i] = L[n-i]-(nex_x-x)+v
  nex_x = x
  
chk = [(0,0)]+chk
R = [0]+R
L = [0]+L

class segment_():
    def __init__(self,n,ide_ele,segfunc):
        self.ide_ele = ide_ele
        self.num = 1 << n.bit_length()
        self.seg = [self.ide_ele] * 2 * self.num
        self.segfunc = segfunc
        
    def update(self, k, r):
        k += self.num
        self.seg[k] = r
        while k:
            k >>= 1
            self.seg[k] = self.segfunc(self.seg[k*2], self.seg[k*2+1])

    def query(self, p, q):
        # qは含まない
        if q < p:
            return self.ide_ele
        p += self.num;
        q += self.num
        res = self.ide_ele
        while p < q:
            if p & 1 == 1:
                res = self.segfunc(res, self.seg[p])
                p += 1
            if q & 1 == 1:
                q -= 1
                res = self.segfunc(res, self.seg[q])
            p >>= 1;
            q >>= 1
        return res

SR = segment_(n+1,0,lambda a, b: max(a,b))
SL = segment_(n+1,0,lambda a, b: max(a,b))
for i in range(1,n+1):
  SR.update(i,R[i])
  SL.update(i,L[i])
  
ans = max(0,max(SR.query(0,n+1),SL.query(1,n+1)))
for i in range(1,n+1):
  cr = chk[i][0]
  cc = c-cr
  sr = SR.query(0,i)
  sl = SL.query(i+1,n+2)
  rr = R[i] + max(sl-cr,0)
  ll = L[i] + max(sr-cc,0)
  ans = max(ans, max(rr,ll))
  
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()


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

    """
    まず最初の観察として、行ったり来たりしながら寿司をゲットするのは非効率。
    なので移動範囲は開始位置を含む円弧になる。
    円弧の左端をA、右端をB、開始位置をOとすると、移動方法は
        OA -> AB もしくはOB -> BA
    の２通り考えられる。

    それぞれに対してはOからの得点の累積和を前計算しておけばO(N^2)で答えが求まる。
    さらに次の工夫をすることでO(N)で計算が可能になる。

    OA->ABの場合で考える。まずBの位置を一箇所固定する。
    この時最適なAの位置をO(1)で取得できれば良いので、あらかじめ
        [v1　-　x1 * 2, v1 + v2 - x2 * 2, v1 + v2 + v3 - x3 * 2, ... ]
    の中の最大値を計算しておけば良い。
    あとはこれに(vN + v(N-1) + ... + vB) - (C - xB)を加えたものが得点になる。
    """

    #累積和の前計算
    A_sum = [0] # = [0, v1, v1 + v2, v1 + v2 + v3, ... ]
    B_sum = [0] # = [0, vN, vN + v(N - 1), vN + v(N - 1) + v(N - 2), ... ]
    A_max = [(0, 0)] # A_max[i] = (i番目の寿司まで見た時に一番得点が大きい場所とその得点の組)
    B_max = [(0, 0)] # B_max[i] = (N-i番目の寿司まで見た時に一番得点が大きい場所とその得点の組)
    for x, v in sushi:
        A_sum.append(A_sum[-1] + v)
        cand = A_sum[-1] - x * 2
        A_max.append(max(A_max[-1], (cand, x)))
    for x, v in sushi[::-1]:
        B_sum.append(B_sum[-1] + v)
        cand = B_sum[-1] - (C - x) * 2
        B_max.append(max(B_max[-1], (cand, x)))
    #print("A_sum={}".format(A_sum))
    #print("B_sum={}".format(B_sum))
    #print("A_max={}".format(A_max))
    #print("B_max={}".format(B_max))

    # OA->ABの場合の最大得点
    ans1 = -10**10
    for b in range(N, 0, -1):
        val = B_sum[N-b+1] - (C - sushi[b - 1][0])
        #print("b={} -> val={}".format(b, val))
        ans1 = max(ans1, A_max[b - 1][0] + val)

    # OB->BAの場合の最大得点
    ans2 = -10**10
    for a in range(1, N + 1):
        val = A_sum[a] - sushi[a - 1][0]
        #print("a={} -> val={}".format(a, val))
        ans2 = max(ans2, B_max[N - a][0] + val)

    print(max(0, ans1, ans2))


if __name__ == "__main__":
    main()

Submission status: Accepted

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

xv=[]
xv_rev=[]

for _ in range(n):
    x,v=map(int,input().split())
    xv.append((x,v))
    xv_rev.append((c-x,v))

xv_rev=xv_rev[::-1]

#(最大価値,その時の距離,累積価値合計,累積距離)

ittekoi=[0]*n
itte=[0]*n

sumv=0
#時計回り
for i,(x,v) in enumerate(xv):
    if i==0:
        sumv=v
        itte[i]=max(0,sumv-x)
        ittekoi[i]=max(0,sumv-2*x)
    else:
        sumv+=v
        itte[i]=max(itte[i-1],sumv-x)
        ittekoi[i]=max(ittekoi[i-1],sumv-2*x)    

sumv=0
ittekoi2=[0]*n
itte2=[0]*n

#班時計周り
for i,(x,v) in enumerate(xv_rev):
    if i==0:
        sumv=v
        itte2[i]=max(0,sumv-x)
        ittekoi2[i]=max(0,sumv-2*x)
    else:
        sumv+=v
        itte2[i]=max(itte2[i-1],sumv-x)
        ittekoi2[i]=max(ittekoi2[i],sumv-2*x)    

#print(itte,ittekoi)
#print(itte2,ittekoi2)

ans=0
for i in range(n):
    if i==n-1:
        ans=max(ans,itte[i])
        ans=max(ans,itte2[i])
    else:
        ans=max(ans,itte[i]+ittekoi2[n-i-2])
        ans=max(ans,itte2[i]+ittekoi[n-i-2])

print(ans)

Submission status: Accepted

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

N, C = mapint()
xv = [list(mapint()) for _ in range(N)]
righthand = [0]*N
lefthand = [0]*N
nowv = 0
maxv = -10**18
for i, (x, v) in enumerate(xv):
    nowv += v
    maxv = max(maxv, nowv-x)
    righthand[i] = maxv
nowv = 0
maxv = -10**18
for i, (x, v) in enumerate(xv[::-1]):
    nowv += v
    maxv = max(maxv, nowv-(C-x))
    lefthand[i] = maxv
 
xv = [(0, 0)] + xv +[(C, 0)]
righthand = [0]+righthand
lefthand = [0]+lefthand
rmax = 0
for i in range(N+1):
    rmax = max(rmax, righthand[i]-xv[i][0]+lefthand[N-i])
lmax = 0
for i in range(N):
    lmax = max(lmax, lefthand[i]-(C-xv[-i-1][0])+righthand[N-i])
print(max(rmax, lmax))

Submission status: Accepted

Solution code:
import heapq
N,C = map(int,input().split())
X = [list(map(int,input().split())) for _ in range(N)]
X.insert(0,[0,0])
A = [0 for _ in range(N+1)]
for i in range(1,N+1):
    A[i] = A[i-1]+X[i][1]
A = [A[i]-X[i][0] for i in range(N+1)]
B = [0 for _ in range(N+1)]
B[N] = X[N][1]
for i in range(N-1,0,-1):
    B[i] = B[i+1]+X[i][1]
B = [B[i]-(C-X[i][0]) for i in range(N+1)]
heap = []
for i in range(1,N+1):
    heapq.heappush(heap,(-B[i],i))
vmax = 0
for i in range(1,N):
    cnt = A[i]
    vmax = max(vmax,cnt)
    cnt -= X[i][0]
    b,j = heap[0]
    while heap and j<=i:
        heapq.heappop(heap)
        if heap:
            b,j = heap[0]
    b = -b
    cnt += b
    vmax = max(vmax,cnt)
vmax = max(vmax,A[N])
heap = []
for i in range(1,N+1):
    heapq.heappush(heap,(-A[i],i))
for i in range(N,1,-1):
    cnt = B[i]
    vmax = max(vmax,cnt)
    cnt -= (C-X[i][0])
    b,j = heap[0]
    while heap and j>=i:
        heapq.heappop(heap)
        if heap:
            b,j = heap[0]
    b = -b
    cnt += b
    vmax = max(vmax,cnt)
vmax = max(vmax,B[1])
print(vmax)

Submission status: Accepted

Solution code:
n,c,*t=map(int,open(0).read().split())
X=t[::2];V=t[1::2]
def s(X,v):
 V=[0];X=[0]+X;r=[0];l=[0]*-~n
 for i in v:V+=V[-1]+i,
 for i in range(n):r+=V[i+1]-2*X[i+1],;l[n-i-1]=max(l[n-i],V[n]-V[n-i-1]-(c-X[n-i]))
 return [i+j for i,j in zip(r,l)]
print(max(s([c-i for i in X[::-1]],V[::-1])+s(X,V)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,C = map(int,input().split())
XV = [tuple(map(int,input().split())) for i in range(N)]

rcum1 = [0]
rcum2 = [0]
rcummx = [0]
px = 0
for x,v in XV:
    d = x - px
    rcum1.append(rcum1[-1] + v - d)
    rcum2.append(rcum2[-1] + v - 2*d)
    rcummx.append(max(rcummx[-1], rcum1[-1]))
    px = x

lcum1 = [0]
lcum2 = [0]
lcummx = [0]
px = C
for x,v in reversed(XV):
    d = px - x
    lcum1.append(lcum1[-1] + v - d)
    lcum2.append(lcum2[-1] + v - 2*d)
    lcummx.append(max(lcummx[-1], lcum1[-1]))
    px = x
lcum1.reverse()
lcum2.reverse()
lcummx.reverse()

ans = max(rcummx[-1], lcummx[0])
for i in range(N+1):
    a = rcum2[i] + lcummx[i]
    b = lcum2[i] + rcummx[i]
    ans = max(ans, a, b)
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7


#############
# Main Code #
#############

N, C = getNM()
query = [getList() for i in range(N)]

query_alta = copy.deepcopy(query)
query_alta.sort(reverse = True)

imos_fore = [0]
imos_back = [0]
for i in range(N):
    # 右回り
    imos_fore.append(imos_fore[i] + query[i][1])
    # 左周り
    imos_back.append(imos_back[i] + query_alta[i][1])

imos_fore_back = copy.deepcopy(imos_back)
imos_back_back = copy.deepcopy(imos_fore)

for i in range(1, N + 1):
    imos_fore[i] -= query[i - 1][0]
    imos_back_back[i] -= 2 * query[i - 1][0]
    imos_back[i] -= (C - query_alta[i - 1][0])
    imos_fore_back[i] -= 2 * (C - query_alta[i - 1][0])

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

fore_ans = 0
for i in range(N + 1):
    opt = imos_fore[i] + imos_fore_back[N - i]
    fore_ans = max(fore_ans, opt)

back_ans = 0
for i in range(N + 1):
    opt = imos_back[i] + imos_back_back[N - i]
    back_ans = max(back_ans, opt)

print(max(fore_ans, back_ans))

Submission status: Accepted

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

xv = [(0, 0)]
for i in range(N):
    x, v = map(float, input().split())
    xv.append((x, v))

sumA = np.zeros(N+2, dtype=float)
sumB = np.zeros(N+2, dtype=float)

xv.sort(key=lambda tup:tup[0])
xv.append((C,0))

for i in range(N+1):
    sumA[i+1] = sumA[i] + xv[i+1][1]
    sumB[i+1] = sumB[i] + xv[N-i][1]

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

    maxA[i + 1] = maxA[i]
    if sumA[i+1] > maxA[i]:
        maxA[i+1] = sumA[i+1]
    maxB[i + 1] = maxB[i]
    if sumB[i+1] > maxB[i]:
        maxB[i+1] = sumB[i+1]

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

    #when to turn back?
    valA = -C+xv[N-i+1][0] + maxA[N-i]
    if valA < 0:
        ans = max(ans, sumB[i])
    else:
        ans = max(ans, sumB[i] + valA)

print(int(ans))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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

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

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

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

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

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

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

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

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,c=MI()
cal1=[]
dis1=[]
for i in range(n):
    a,b=MI()
    cal1.append(b)
    dis1.append(a)
cal2=list(reversed(cal1))
dis2=[0 for i in range(n)]
for i in range(n):
    dis2[i]=c-dis1[i]
dis2=list(reversed(dis2))
#print(cal1)
#print(dis1)
#print(cal2)
#print(dis2)
u1=list(accumulate(cal1))
v1=list(accumulate(cal1))
u2=list(accumulate(cal2))
v2=list(accumulate(cal2))
for i in range(n):
    u1[i]-=dis1[i]
    v1[i]-=2*dis1[i]
    u2[i]-=dis2[i]
    v2[i]-=2*dis2[i]
'''print("u1")
print(u1)
print("u2")
print(u2)
print("v1")
print(v1)
print("v2")
print(v2)'''
ans=[]
ans.append(max(u1))
ans.append(max(u2))
#print(ans)
mxv1=[0 for i in range(n)]
mxv2=[0 for i in range(n)]
mxv1[0]=max(0,v1[0])
mxv2[0]=max(0,v2[0])
for i in range(n-1):
    mxv1[i+1]=max(v1[i+1],mxv1[i])
    mxv2[i+1]=max(v2[i+1],mxv2[i])
'''print("mxv1")
print(mxv1)
print("mxv2")
print(mxv2)'''
mxa=0
for i in range(n-1):
    sm=u1[i]+mxv2[n-i-2]
    #print(sm)
    if sm>mxa:
        mxa=sm
ans.append(mxa)
mxb=0
for i in range(n-1):
    sm=u2[i]+mxv1[n-i-2]
    #print(sm)
    if sm>mxb:
        mxb=sm
ans.append(mxb)
#print(ans)
print(max(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for _ in range(n)]
max_right=[]
max_left=[]
right=0
left=0
tmp=0
pre=0
for i in range(n):
  x,v=xv[i]
  tmp+=v
  tmp-=x-pre
  right=max(right,tmp)
  max_right.append(right)
  pre=x
pre=0
tmp=0
for i in range(n):
  x,v=xv[-i-1]
  x=c-x
  tmp+=v
  tmp-=x-pre
  left=max(left,tmp)
  max_left.append(left)
  pre=x

ans=max(max_right[-1],max_left[-1])
sv=0
for i in range(n-1):
  x,v=xv[i]
  sv+=v
  ans=max(ans,max_left[n-i-2]+sv-2*x)
sv=0
for i in range(n-1):
  x,v=xv[-i-1]
  x=c-x
  sv+=v
  ans=max(ans,max_right[n-i-2]+sv-2*x)
print(ans)

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,L = IL()
XA = [0]
C = []
for _ in range(N):
  x,c = IL()
  XA.append(x)
  C.append(c)
XB = [0]
for x in XA[:0:-1]:
  XB.append(L-x)
CA = [0]
CB = [0]
for c in C:
  CA.append(CA[-1]+c)
for c in C[::-1]:
  CB.append(CB[-1]+c)

A = [0]
AA = [0]
B = [0]
BB = [0]
for i in range(1,N+1):
  A.append(CA[i]-XA[i])
  AA.append(CA[i]-XA[i]*2)
for i in range(1,N+1):
  B.append(CB[i]-XB[i])
  BB.append(CB[i]-XB[i]*2)
  
MAXA = []
MAX = 0
for a in A:
  MAX = max(MAX,a)
  MAXA.append(MAX)
MAXB = []
MAX = 0
for b in B:
  MAX = max(MAX,b)
  MAXB.append(MAX)

  
  
MAX = 0
for i in range(N+1):
  MAX = max(MAX,AA[i]+MAXB[N-i])
for i in range(N+1):
  MAX = max(MAX,BB[i]+MAXA[N-i])

print(MAX)

Submission status: Accepted

Solution code:
n,c = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
now = 0
s = []
t = []
for i in range(n):
    now += a[i][1]
    s.append(now)
    #if (now-a[i][0] > ans):
        #ans = now-a[i][0]
#print(ans)
now = 0
for i in range(n):
    now += a[n-1-i][1]
    t.append(now)
    #if (now-(c-a[n-1-i][0]) > ans):
        #ans = now-(c-a[n-1-i][0])
#print(ans)
back = 0
ans = max(ans, s[-1]-a[-1][0])
for i in range(n-2,-1,-1):            
    back = max(back, t[n-2-i]-2*(c-a[i+1][0]))
    ans = max(ans,s[i]-a[i][0]+back)
    
back = 0
ans = max(ans, t[-1]-(c-a[0][0]))
for i in range(n-2,-1,-1):
    back = max(back, s[n-2-i]-2*a[n-2-i][0])
    ans = max(ans, t[i]-(c-a[n-i-1][0])+back)
print(ans)

Submission status: Accepted

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

sumv = [0]*(N+1)
for i in range(1,N+1):
    sumv[i] = sumv[i-1] + v[i-1]
csumv = [0]*(N+1)
for i in range(1,N+1):
    csumv[i] = csumv[i-1] + v[N-i]

sclo = [0]*(N+1)
for i in range(1,N+1):
    sclo[i] = sumv[i] - x[i-1]
scclo = [0]*(N+1)
for i in range(1,N+1):
    scclo[i] = csumv[i] - (C-x[N-i])

#print(sumv,sclo)
#print(csumv,scclo)

# まず反時計に行くとき
max_point = [0]*(N+1)
M = -1
for i in range(N+1):
    M = max(M,sclo[i])
    max_point[N-i] = M

point = [0]*(N+1)
for i in range(N+1):
    point[i] = scclo[i]-(C-x[N-i]) + max_point[i]

ans = max(point)

# まず時計に行くとき
max_point2 = [0]*(N+1)
M2 = -1
for i in range(N+1):
    M2 = max(M2,scclo[i])
    max_point2[N-i] = M2

point2 = [0]*(N+1)
x.insert(0,0)
for i in range(N+1):
    point2[i] = sclo[i]-(x[i]) + max_point2[i]

ans2 = max(point2)

ans3 = max(sclo)
ans4 = max(scclo)
print(max(ans,ans2,ans3,ans4))

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n,c = map(int,ipt().split())
    stt = [tuple(map(int,ipt().split())) for _ in range(n)]

    rw = [0]*(n+1)
    rh = [0]*(n+1)
    lw = [0]*(n+1)
    lh = [0]*(n+1)
    nr = 0
    for i,si in enumerate(stt):
        nr += si[1]
        rw[i+1] = nr-si[0]*2 if rw[i]<nr-si[0]*2 else rw[i]
        rh[i+1] = nr-si[0] if rh[i]<nr-si[0] else rh[i]
    nl = 0
    for i,si in enumerate(stt[::-1]):
        nl += si[1]
        lw[i+1] = nl-(c-si[0])*2 if lw[i]<nl-(c-si[0])*2 else lw[i]
        lh[i+1] = nl-(c-si[0]) if lh[i]<nl-(c-si[0]) else lh[i]

    ma = 0
    for i in range(n):
        if ma < rw[i]+lh[n-i]:
            ma = rw[i]+lh[n-i]
        if ma < lw[i]+rh[n-i]:
            ma = lw[i]+rh[n-i]
    print(ma)
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

m1 = []
v1 = []
v_cum = 0
tmp = 0

for x, v in xv:
    v_cum += v
    tmp = max(tmp, v_cum - x)
    v1.append(v_cum - x)
    m1.append(tmp)

m2 = []
v2 = []
v_cum = 0
tmp = 0

for x, v in xv[::-1]:
    v_cum += v
    tmp = max(tmp, v_cum + x - c)
    v2.append(v_cum + x - c)
    m2.append(tmp)

ans = max((0, m1[-1], m2[-1]))

for i in range(n-1):
    ans = max((
        ans,
        v1[i] + m2[-i-2] - xv[i][0],
        v2[i] + m1[-i-2] + xv[-i-1][0] - c
    ))

print(ans)

Submission status: Accepted

Solution code:
import bisect
from collections import OrderedDict
def resolve():
    N, C = list(map(int, input().split()))
    P = []
    cal = [0]
    for i in range(N):
        x, v = list(map(int, input().split()))
        P.append(x)
        cal.append(cal[i]+v)
    
    to_right = [0]
    for i in range(N):
        to_right.append(max(to_right[i], cal[i+1]-P[i]))
    to_left = [0]
    for i in range(N):
        to_left.append(max(to_left[i], cal[N]-cal[N-i-1]-(C-P[-i-1])))
    right_left = 0
    for i in range(N-1):
        right_left = max(right_left, cal[i+1]+to_left[N-i-1]-2*P[i])
    left_right = 0
    for i in range(N-1):
        left_right = max(left_right, cal[N]-cal[N-i-1]+to_right[N-i-1]-2*(C-P[-i-1]))
    print(max(to_right+to_left+[right_left, left_right]))

    
if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for _ in range(n)]
l,r,lret,rret=[],[],[],[]
sl,sr=0,0
for i in range(n):
    sl+=xv[i][1]
    sr+=xv[n-i-1][1]
    l.append(sl-xv[i][0])
    lret.append(sl-2*xv[i][0])
    r.append(sr-(c-xv[n-i-1][0]))
    rret.append(sr-2*(c-xv[n-i-1][0]))
for i in range(1,n):
    lret[i]=max(lret[i],lret[i-1])
    rret[i]=max(rret[i],rret[i-1])
ans=max(0,max(l),max(r))
#print(l)
#print(r)
#print(lret)
#print(rret)
for i in range(n-1):
    ans=max(ans,l[i]+rret[n-i-2],r[i]+lret[n-i-2])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xv=[list(map(int,input().split()))for _ in range(n)]
l=[0]
s=0
for x,v in xv:
	s+=v
	l.append(max(l[-1],s-x))
r=[0]
s=0
for x,v in xv[::-1]:
	s+=v
	r.append(max(r[-1],s-(c-x)))
ans=max(l+r)
s=0
for i in range(n):
	s+=xv[i][1]
	ans=max(ans,s-2*xv[i][0]+r[n-i-1])
s=0
for i in range(n-1,-1,-1):
	s+=xv[i][1]
	ans=max(ans,s-2*(c-xv[i][0])+l[i])
print(ans)