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
from collections import deque
from functools import lru_cache
import bisect
import copy
import heapq
import itertools
import math
import random
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N, C = read_values()
    D = read_lists(N)
    A = [0] * (N + 1)
    A2 = [0] * (N + 1)
    V = 0
    res = 0
    for i, (X, v) in enumerate(D):
        V += v
        A[i + 1] = max(A[i], V - X)
        A2[i + 1] = max(A2[i], V - 2 * X)
        res = max(res, A[i + 1], A2[i + 1])

    V = 0
    for b in range(N - 1, -1, -1):
        x, v = D[b]
        X = C - x
        V += v
        res = max(res, V - 2 * X + A[b], V - X + A2[b])

    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

def solve(xv):
    lis = [0] * n # best score in x sushi
    now_v=0
    best=0

    for i in range(n):
        x,v = xv[i]
        now_v+=v
        best=max(best,now_v - x)
        lis[i] = best

    lis.insert(0,0)
    ans=max(lis)

    now_v=0
    for i in reversed(range(n)):
        x,v = xv[i]
        now_v+=v
        ans=max(ans,now_v-2*(c-x) + lis[i])

    return ans


xv2 = []
for i in reversed(range(n)):
    x,v = xv[i]
    x=c-x
    xv2.append([x,v])

ans = max(solve(xv),solve(xv2))

print(ans)

Submission status: Accepted

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

# x = 0 に v = 0 の寿司があると考える
X = [0]
V = [0]

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

# 0, v_1, v_1+v_2, v_1+v_2+v_3, ...
cumsum1 = [0]
for i in range(1, N + 1):
    cumsum1.append(cumsum1[-1] + V[i])

# 0, v_N, v_N+v_N-1, v_N+v_N-1+v_N-2, ...
cumsum2 = [0]
for i in range(N, 0, -1):
    cumsum2.append(cumsum2[-1] + V[i])

# 歩く範囲を弧ABと考える(A<=B)
# x_A = 0, x_1, x_2, ..., x_N
# x_B = x_A, ..., x_N

# 0, v_1-x_1, v_1+v_2-x_2, v_1+v_2+v_3-x_3, ...
f1 = [0]
# 0, v_1-2*x_1, v_1+v_2-2*x_2, v_1+v_2+v_3-2*x_3, ...
f2 = [0]
for i in range(1, N + 1):
    f1.append(cumsum1[i] - X[i])
    f2.append(cumsum1[i] - 2 * X[i])

f1_max = [0]
for i in range(1, N + 1):
    f1_max.append(max(f1_max[-1], f1[i]))
f2_max = [0]
for i in range(1, N + 1):
    f2_max.append(max(f2_max[-1], f2[i]))

ans = 0
# Bを全探索（固定する）
for i in range(N + 1):
    if i == 0:
        continue
    else:
        # 0 -> B(反時計回り、反転なし)
        ans = max(ans, cumsum1[i] - X[i])
        # 0 -> B(時計回り、反転なし)
        ans = max(ans, cumsum2[N + 1 - i] - (C - X[i]))
        # 0 -> A -> B(反転)
        ans = max(ans, f2_max[i - 1] + cumsum2[N + 1 - i] - (C - X[i]))
        # 0 -> B -> A(反転)
        ans = max(ans, f1_max[i - 1] + cumsum2[N + 1 - i] - 2 * (C - X[i]))

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
N,C = map(int,input().split())
xs = []
vs = []
for _ in range(N):
    x,v = map(int,input().split())
    xs.append(x)
    vs.append(v)
vacc = [0]+list(accumulate(vs, lambda x,y:x+y))
lacc = [0]+[vacc[i+1]-xs[i] for i in range(N)]
racc = [vacc[-1]-vacc[i]-C+xs[i] for i in range(N)]+[0]
for i in range(1, N):
    lacc[i] = max(lacc[i], lacc[i-1])
racc[-1] = (racc[-1], 0)
for i in range(N, 0, -1):
    if racc[i-1] > racc[i][0]:
        racc[i-1] = (racc[i-1], C-xs[i-1])
    else:
        racc[i-1] = racc[i]
xs = [0]+xs
ans = 0
for i in range(N+1):
    l = lacc[i]
    r, d = racc[i]
    ans = max(ans, l+r-xs[i], l+r-d, l, r)
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate


N, C, *xv = map(int, open(0).read().split())
xv = [(x, v) for x, v in zip(*[iter(xv)] * 2)]

cw_acc = [0] * (N + 1)
ccw_acc = [0] * (N + 1)
cw_prev = 0
ccw_prev = C
for i in range(N):
    k = N - i - 1
    cw_acc[i + 1] = cw_acc[i] + xv[i][1] - (xv[i][0] - cw_prev)
    cw_prev = xv[i][0]
    ccw_acc[i + 1] = ccw_acc[i] + xv[k][1] - (ccw_prev - xv[k][0])
    ccw_prev = xv[k][0]

cw_acc = list(accumulate(cw_acc, max))
ccw_acc = list(accumulate(ccw_acc, max))
ans = 0
for i in range(N):
    k = N - i - 1
    ans = max(
        ans,
        cw_acc[i + 1],
        cw_acc[i + 1] - xv[i][0] + ccw_acc[k],
        ccw_acc[i + 1],
        ccw_acc[i + 1] - (C - xv[k][0]) + cw_acc[k],
    )
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class SegmentTree:
    def __init__(self, array, operator, identity_element):
        _len = len(array)
        self.__op = operator
        self.__size = 1 << (_len - 1).bit_length()
        self.__tree = [identity_element] * self.__size + \
            array + [identity_element] * (self.__size - _len)
        self.__ie = identity_element

        for i in range(self.__size - 1, 0, -1):
            self.__tree[i] = operator(
                self.__tree[i * 2], self.__tree[i * 2 + 1])

    def update(self, i, v):
        i += self.__size
        self.__tree[i] = v
        while i:
            i //= 2
            self.__tree[i] = self.__op(
                self.__tree[i * 2], self.__tree[i * 2 + 1])

    def query(self, l, r):
        """[l, r)
        """
        l += self.__size
        r += self.__size
        ret = self.__ie
        while l < r:
            if l & 1:
                ret = self.__op(ret, self.__tree[l])
                l += 1
            if r & 1:
                r -= 1
                ret = self.__op(ret, self.__tree[r])
            l //= 2
            r //= 2
        return ret

    def __getitem__(self, key):
        return self.__tree[key + self.__size]


@mt
def slv(N, C, XV):
    XV.sort()
    ans = 0
    sf = [(0, 0)]
    stf = SegmentTree([-INF]*N, max, -INF)
    c = 0
    for i, (x, v) in enumerate(XV):
        v = sf[-1][0]+v-(x-c)
        sf.append((v, x))
        stf.update(i, v)
        c = x


    str_ = SegmentTree([-INF]*N, max, -INF)
    sr = [(0, 0)]
    c = 0
    for i, (x, v) in enumerate(reversed(XV)):
        x = C - x
        v = sr[-1][0]+v-(x-c)
        sr.append((v, x))
        str_.update(i, v)
        c = x

    ans = 0
    for i in range(N+1):
        t = sf[i][0] + max(0, str_.query(0, N-i) - sf[i][1])
        ans = max(ans, t)
        t = sr[i][0] + max(0, stf.query(0, N-i) - sr[i][1])
        ans = max(ans, t)
    return ans


def main():
    N, C = read_int_n()
    XV = [read_int_n() for _ in range(N)]
    print(slv(N, C, XV))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,c= map(int,input().split())
xlist=[]
for i in range(n):
    x,v= map(int,input().split())
    xlist.append((x,v))
fclock=[[0,0] for _ in range(n)]
ftemp,fval=[0]*n,[0]*n
for i in range(n):
    if i==0:
        fval[0]=xlist[i][1]
        if fval[i]-xlist[i][0]<0:fclock[i]=[-1,0]
        else:fclock[i]=[0,fval[0]-xlist[i][0]]
    else:
        fval[i]=fval[i-1]+xlist[i][1]
        if fclock[i-1][1]<fval[i]-xlist[i][0]:
            fclock[i]=[i,fval[i]-xlist[i][0]]
        else:fclock[i]=fclock[i-1]
fret=[xlist[i][0] for i in range(n)]
rxlist=[]
for i in range(n-1,-1,-1):rxlist.append([c-xlist[i][0],xlist[i][1]])
rclock=[[0,0] for _ in range(n)]
rtemp,rval=[0]*n,[0]*n
for i in range(n):
    if i==0:
        rval[0]=rxlist[i][1]
        if rval[i]-rxlist[i][0]<0:rclock[i]=[-1,0]
        else:rclock[i]=[0,rval[0]-rxlist[i][0]]
    else:
        rval[i]=rval[i-1]+rxlist[i][1]
        if rclock[i-1][1]<rval[i]-rxlist[i][0]:rclock[i]=[i,rval[i]-rxlist[i][0]]
        else:rclock[i]=rclock[i-1]

rret=[rxlist[i][0] for i in range(n)]
gmax=max(rclock[n-1][1],fclock[n-1][1])
for i in range(n-1):
    tempg=fclock[i][1]+rclock[n-2-i][1]
    if fclock[i][0]<0 or rclock[n-2-i][0]<0:pass
    else:tempg-=min(fret[fclock[i][0]],rret[rclock[n-2-i][0]])
    gmax=max(gmax,tempg)
print(gmax)

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

x = [0] + x + [c]
v = [0] + v + [0]

left = [0] * (n + 2)
right = [0] * (n + 2)

for i in range(n + 1):
    left[i + 1] = left[i] + v[i + 1] - (x[i + 1] - x[i])
for i in range(n + 1, 0, -1):
    right[i - 1] = right[i] + v[i - 1] - (x[i] - x[i - 1])


for i in range(n + 1):
    left[i + 1] = max(left[i + 1], left[i])
for i in range(n + 1, 0, -1):
    right[i - 1] = max(right[i - 1], right[i])

# 引き返さない最大
ans = max(left[-1], right[0])
right = list(reversed(right))
for i in range(n):
    tmp = left[i] - x[i]
    rem = n - i
    ans = max(ans, tmp + right[n - i])

for i in range(n):
    tmp = right[i] - (c - x[-(i + 1)])
    rem = n - i
    ans = max(ans, tmp + left[n - i])

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
#D - Static Sushi 
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N,C = map(int,readline().split())
#時計回りでの距離X,カロリーV
D = []
V = []
for _ in range(N):
    x,v = map(int,readline().split())
    D.append(x)
    V.append(v)
D.append(C)
V.append(0)
##時計回りでのS1-d1,S1-2*d2の最大値 X1,X2
##反時計回りでのS2-d2,S2-2*d2の最大値 Y1,Y2
X1,X2 = [0],[0]
d = 0 
total = 0
tmp1,tmp2 = 0,0
for i in range(N):
    d = D[i]
    total += V[i]
    tmp1 = max(tmp1,total-d)
    tmp2 = max(tmp2,total-2*d)
    X1.append(tmp1)
    X2.append(tmp2)

m1 = 0
m2 = 0
d = 0 
total = 0
for i in range(N,-1,-1):
    d = (C-D[i])
    total += V[i]
    tmp1 = total - d
    tmp2 = total - 2*d
    m1 = max(m1,tmp1+X2[i])
    m2 = max(m2,tmp2+X1[i])
print(max(m1,m2))

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
R = [[0, 0]]
L = [[0, 0]]
R_half = -1
for i in range(N):
    x, v = map(int, input().split())
    R.append([x, v])
for i in R[::-1]:
    L.append([C - i[0], i[1]])
L.pop(-1)

R_sum = [0]
L_sum = [0]
R_sum2 = [0]
L_sum2 = [0]
total_1 = 0
total_2 = 0
total_3 = 0
total_4 = 0
for i in range(1, N + 1):
    total_1 += R[i][1] - (R[i][0] - R[i-1][0])
    total_2 += L[i][1] - (L[i][0] - L[i-1][0])
    total_3 += R[i][1] - 2*(R[i][0] - R[i-1][0])
    total_4 += L[i][1] - 2*(L[i][0] - L[i-1][0])
    R_sum.append(total_1)
    L_sum.append(total_2)
    R_sum2.append(total_3)
    L_sum2.append(total_4)
result_1 = max(R_sum)
result_2 = max(L_sum)
big_R = []
big_L = []
t = 0
p = 0
for i in range(N+1):
    t = max(t, R_sum[i])
    big_R.append(t)
    p = max(p, L_sum[i])
    big_L.append(p)
result_3 = 0
result_4 = 0
for i in range(N+1):
    result_3 = max(result_3, L_sum2[i] + big_R[N - i])
    result_4 = max(result_4, R_sum2[i] + big_L[N - i])
print(max([result_1, result_2, result_3, result_4]))

Submission status: Accepted

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

    n, c = map(int, input().split())
    # v: cumulative sum
    x, v = [0] * (n+2), [0] * (n+2)
    for i in range(n):
        j, k = map(int, input().split())
        x[i+1] = j
        v[i+1] = v[i] + k
    x[n+1] = c
    v[n+1] = v[n]
    
    max_nut_clockwise = [0] * (n+1)
    for i in range(1, n+1):
        max_nut_clockwise[i] = max(max_nut_clockwise[i-1], v[i] - x[i])
    max_nut_counterclockwise = [0] * (n+1)
    for i in range(n-1, -1, -1):
        max_nut_counterclockwise[i] = max(max_nut_counterclockwise[i+1], v[-1] - v[i] - c + x[i+1])

    ans = 0
    # rotate clockwise, then rotate counterclockwise
    for i in range(n):
        if ans < v[i] - 2*x[i] + max_nut_counterclockwise[i]:
            ans = v[i] - 2*x[i] + max_nut_counterclockwise[i]
    # rotate counterclockwise, then rotate clockwise
    for i in range(2, n+2):
        if ans < v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]:
            ans = v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]
    
    print(ans)

main()

Submission status: Accepted

Solution code:
def main():
    from numpy import zeros
    from sys import stdin
    def input():
        return stdin.readline().strip()

    n, c = map(int, input().split())
    # v: cumulative sum
    x, v = zeros(n+2, dtype=int), zeros(n+2, dtype=int)
    for i in range(n):
        j, k = map(int, input().split())
        x[i+1] = j
        v[i+1] = v[i] + k
    x[n+1] = c
    v[n+1] = v[n]
    
    max_nut_clockwise = zeros(n+1, dtype=int)
    for i in range(1, n+1):
        max_nut_clockwise[i] = max(max_nut_clockwise[i-1], v[i] - x[i])
    max_nut_counterclockwise = zeros(n+1, dtype=int)
    for i in range(n-1, -1, -1):
        max_nut_counterclockwise[i] = max(max_nut_counterclockwise[i+1], v[-1] - v[i] - c + x[i+1])

    ans = 0
    # rotate clockwise, then rotate counterclockwise
    for i in range(n):
        if ans < v[i] - 2*x[i] + max_nut_counterclockwise[i]:
            ans = v[i] - 2*x[i] + max_nut_counterclockwise[i]
    # rotate counterclockwise, then rotate clockwise
    for i in range(2, n+2):
        if ans < v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]:
            ans = v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]
    
    print(ans)

main()

Submission status: Accepted

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

    n, c = map(int, input().split())
    # v: cumulative sum
    x, v = [0] * (n+2), [0] * (n+2)
    for i in range(n):
        j, k = map(int, input().split())
        x[i+1] = j
        v[i+1] = v[i] + k
    x[n+1] = c
    v[n+1] = v[n]
    
    max_nut_clockwise = [0] * (n+1)
    for i in range(1, n+1):
        max_nut_clockwise[i] = max(max_nut_clockwise[i-1], v[i] - x[i])
    max_nut_counterclockwise = [0] * (n+1)
    for i in range(n-1, -1, -1):
        max_nut_counterclockwise[i] = max(max_nut_counterclockwise[i+1], v[-1] - v[i] - c + x[i+1])

    ans = 0
    # rotate clockwise, then rotate counterclockwise
    for i in range(n):
        if ans < v[i] - 2*x[i] + max_nut_counterclockwise[i]:
            ans = v[i] - 2*x[i] + max_nut_counterclockwise[i]
    # rotate counterclockwise, then rotate clockwise
    for i in range(2, n+2):
        if ans < v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]:
            ans = v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]
    
    print(ans)

main()

Submission status: Accepted

Solution code:
from itertools import *
N,C,*XV = map(int,open(0).read().split())
X = XV[::2] + [C]
A = [0] + list(accumulate(XV[1::2]))
ans = L = R = 0

for b in range(N + 1):
    T = A[N] - A[b]
    d = C - X[b]
    L = max(L, A[b] - X[b - 1])
    R = max(R, A[b] - 2 * X[b - 1])
    ans = max(ans, L + T - 2 * d, R + T - d)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


# inputna
n,c = list(map(int, input().split()))
xv = [tuple(map(int, input().split())) for _ in range(n)]
c0 = []
c1 = []
v = 0
for i in range(n):
    v += xv[i][1]
    c0.append(v-xv[i][0])
v = 0
for i in range(n-1,-1,-1):
    v += xv[i][1]
    c1.append(v-(c-xv[i][0]))
c1 = c1[::-1]
d0 = []
d1 = []
v = 0
for i in range(n):
    v += xv[i][1]
    d0.append(v-2*xv[i][0])
v = 0
for i in range(n-1,-1,-1):
    v += xv[i][1]
    d1.append(v-2*(c-xv[i][0]))
d1 = d1[::-1]
# print(d0,d1)
for i in range(1,n):
    c0[i] = max(c0[i-1], c0[i])
    d0[i] = max(d0[i-1], d0[i])
for i in range(n-2, -1, -1):
    c1[i] = max(c1[i+1], c1[i])
    d1[i] = max(d1[i+1], d1[i])
m0 = max(c0)
m1 = max(c1)
if n>1:
    m2 = max((c0[i]+d1[i+1]) for i in range(n-1))
    m3 = max((c1[i]+d0[i-1]) for i in range(1,n))
else:
    m2 = m3 = -1
ans = max(m0,m1,m2,m3,0)
print(ans)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
clock = []
counter_clock = []
for i in range(n):
    x, v = map(int, input().split())
    clock.append([x, v])
    counter_clock.append([c - x, v])
clock.sort()
counter_clock.sort()
clock_ac = [0]
counter_clock_ac = [0]
for i in range(n):
    v = clock[i][1]
    clock_ac.append(clock_ac[-1] + v)
    v2 = counter_clock[i][1]
    counter_clock_ac.append(counter_clock_ac[-1] + v2)
for i in range(n):
    x = clock[i][0]
    clock_ac[i + 1] -= x
    x2 = counter_clock[i][0]
    counter_clock_ac[i + 1] -= x2
max_clock_ac = [0]
max_counter_clock_ac = [0]
for i in range(n):
    max_clock_ac.append(max(max_clock_ac[-1], clock_ac[i + 1]))
    max_counter_clock_ac.append(max(max_counter_clock_ac[-1], counter_clock_ac[i + 1]))
ans = max(max_clock_ac[n], max_counter_clock_ac[n])
for i in range(n):
    ans = max(ans, clock_ac[i + 1] - clock[i][0] + max_counter_clock_ac[n - i - 1])
    ans = max(ans, counter_clock_ac[i + 1] - counter_clock[i][0] + max_clock_ac[n - i - 1])
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
D, D2 = [], []
for _ in range(N):
    x, v = map(int, input().split())
    D.append((x,v))
    D2.append((C-x,v))
P, S, x0 = [0], [], 0
for x, v in D:
    P.append(P[-1] + v - (x - x0))
    S.append(P[-1] - x)
    x0 = x
T = [0]
for i in range(N):
    T.append(max(T[-1],S[i]))
Q, R, x0 = [0], [0], 0
for i, d in enumerate(reversed(D)):
    x, v = d
    x = C-x
    Q.append(Q[-1]+v-(x-x0))
    R.append(Q[-1]+T[-2-i])
    x0 = x
m1 = max(P+Q+R)
D = list(reversed(D2))
P, S, x0 = [0], [], 0
for x, v in D:
    P.append(P[-1] + v - (x - x0))
    S.append(P[-1] - x)
    x0 = x
T = [0]
for i in range(N):
    T.append(max(T[-1],S[i]))
Q, R, x0 = [0], [0], 0
for i, d in enumerate(reversed(D)):
    x, v = d
    x = C-x
    Q.append(Q[-1]+v-(x-x0))
    R.append(Q[-1]+T[-2-i])
    x0 = x
m2 = max(P+Q+R)
print(max(m1,m2))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,C = map(int, input().split())

X = []

for i in range(N):
  x,c = map(int, input().split())
  X.append((x,c))
  
PS1 = [[0,0,0]]
PS2 = [[0,0,0]]
QS1 = [[0,0,0]]
QS2 = [[0,0,0]]

# PS[i] = c,i,c0
# PS1:右回りで得られるコスト（行きのxのロス組み込み
# PS2:右回り＋Oに帰るまでで得られるコスト
# i:Xのindex。

for i in range(N):
  c1, xx, c0 = PS1[i]
  c2, _,  _  = PS2[i]
  x,c = X[i]
  PS1.append([c0+c-x, i+1, c0+c])
  PS2.append([c0+c-x*2, i+1, c0+c])

for i in range(N):
  c1, xx, c0 = QS1[i]
  c2, _,  _  = QS2[i]
  x,c = X[N-i-1]
  x = C-x
  QS1.append([c0+c-x, i+1, c0+c])
  QS2.append([c0+c-x*2, i+1, c0+c])

PS1.sort(reverse=True)
PS2.sort(reverse=True)

"""
print(PS1)
print(PS2)
print(QS1)
print(QS2)
"""

# 左回りのINDEXをqとする。ただし原点=0とする
# するとQSindex + PSindex <= N であればOKで
# かつPSがソート済単調減少なので、貪欲に取れるはず
ans = 0
ps1index, ps2index = 0,0
for q in range(N+1):
  while PS1[ps1index][1] + q > N:
    ps1index += 1
  while PS2[ps2index][1] + q > N:
    ps2index += 1
  a1 = PS1[ps1index][0] + QS2[q][0]
  a2 = PS2[ps2index][0] + QS1[q][0]
  ans = max(ans, a1,a2)
  
print(ans)

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


class HeapSet:
    def __init__(self):
        self.minQue = []
        self.maxQue = []
        self.counter = defaultdict(lambda: 0)

    def insert(self, x):
        heappush(self.minQue, x)
        heappush(self.maxQue, -x)
        self.counter[x] += 1

    def delete(self, x):
        self.counter[x] = max(0, self.counter[x] - 1)

    def get_max(self):
        while self.maxQue and self.counter[-self.maxQue[0]] == 0:
            heappop(self.maxQue)
        return -self.maxQue[0] if self.maxQue else None

    def get_min(self):
        while self.minQue and self.counter[self.minQue[0]] == 0:
            heappop(self.minQue)
        return self.minQue[0] if self.minQue else None

    def __str__(self):

        min = []
        sl = sorted(list(set(self.minQue)))
        for i in range(len(sl)):
            if self.counter[sl[i]]:
                min += [sl[i]] * self.counter[sl[i]]

        return min.__str__()


def main():

    N, C = in_nn()
    xv = []

    for i in range(N):
        x, v = in_nn()
        xv.append((x, v))

    if N == 1:
        ans = 0
        x, v = xv[0]
        ans = max(ans, v - min(x, C - x))
        print(ans)
        exit()

    xv.sort()

    tsum = [0] * (N + 1)
    for i in range(N):
        tsum[i + 1] = tsum[i] + xv[i][1]

    for i in range(N):
        tsum[i + 1] -= xv[i][0]

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

    for i in range(N):
        rev_tsum[i + 1] -= C - xv[N - 1 - i][0]

    heap = HeapSet()

    for i in range(N + 1):
        heap.insert(tsum[i])

    # print(tsum)
    # print(rev_tsum)
    # print(dmin)

    ans = heap.get_max()
    for i in range(1, N + 1):
        heap.delete(tsum[N + 1 - i])
        v1 = heap.get_max()
        v2 = rev_tsum[i]
        c2 = C - xv[N - i][0]
        value = v1 + v2 - c2
        ans = max(ans, value)

    heap2 = HeapSet()
    for i in range(N + 1):
        heap2.insert(rev_tsum[i])

    ans = max(ans, heap2.get_max())
    for i in range(1, N + 1):
        heap2.delete(rev_tsum[N + 1 - i])
        v1 = heap2.get_max()
        v2 = tsum[i]
        c2 = xv[i - 1][0]
        value = v1 + v2 - c2
        ans = max(ans, value)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, C = MAP()
xv = [LIST() for _ in range(N)]

#左回り用
energy_left_1 = [0]
energy_left_2 = [0] #折り返し用
tmp_v = 0
for x, v in xv:
	tmp_v += v
	energy_left_1.append(tmp_v-x)
	energy_left_2.append(tmp_v-2*x)

#右周り用
energy_right_1 = [0]
energy_right_2 = [0] #折り返し用
tmp_v = 0 
for x, v in xv[::-1]:
	y = C-x
	tmp_v += v
	energy_right_1.append(tmp_v-y)
	energy_right_2.append(tmp_v-2*y)

energy_left_1_acc = list(accumulate(energy_left_1, max))
energy_left_2_acc = list(accumulate(energy_left_2, max))
energy_right_1_acc = list(accumulate(energy_right_1, max))
energy_right_2_acc = list(accumulate(energy_right_2, max))

ans = -INF
for i in range(N+1):
	ans = max(ans, energy_left_1_acc[i]+energy_right_2_acc[N-i])
	ans = max(ans, energy_left_2_acc[i]+energy_right_1_acc[N-i])
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, c = map(int, input().split())
    XY = [list(map(int, input().split())) for _ in range(n)]
    R1, R2 = [0], [0]
    max1, max2 = [0], [0]
    ma = 0
    prev = 0
    for x, y in XY:
        R1.append(R1[-1] + y - (x - prev))
        prev = x
        if ma < R1[-1]:
            ma = R1[-1]
        max1.append(ma)

    ma = 0
    prev = 0
    for x, y in XY[::-1]:
        R2.append(R2[-1] + y - ((c - x) - prev))
        prev = (c - x)
        if ma < R2[-1]:
            ma = R2[-1]
        max2.append(ma)

    res = max(max(R1), max(R2))
    for i in range(1, n + 1):
        point1 = R1[i] - XY[i - 1][0] + max2[n - i]
        point2 = R2[i] - (c - XY[-i][0]) + max1[n - i]
        res = max(res, point1, point2)
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(N)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, left, right):
        """
        [left, right)のsegfuncしたものを得る
        left: index(0-index)
        right: index(0-index)
        """
        res = self.ide_ele
        left += self.num
        right += self.num
        while left < right:
            if left & 1:
                res = self.segfunc(res, self.tree[left])
                left += 1
            if right & 1:
                res = self.segfunc(res, self.tree[right - 1])
            left >>= 1
            right >>= 1
        return res


def resolve():
    n, c = map(int, input().split())
    XY = [list(map(int, input().split())) for _ in range(n)]
    R1 = [0]
    prev = 0
    for x, y in XY:
        R1.append(R1[-1] + y - (x - prev))
        prev = x
    R2 = [0]
    prev = 0
    for x, y in XY[::-1]:
        R2.append(R2[-1] + y - ((c - x) - prev))
        prev = (c - x)

    res = max(max(R1), max(R2))
    seg1 = SegTree(R2, lambda x, y: max(x, y), 0)
    for i in range(1, n + 1):
        point1 = R1[i] - XY[i - 1][0]
        point2 = seg1.query(0, n + 1 - i)
        res = max(res, point1 + point2)

    seg2 = SegTree(R1, lambda x, y: max(x, y), 0)
    for i in range(1, n + 1):
        point1 = R2[i] - (c - XY[-i][0])
        point2 = seg2.query(0, n + 1 - i)
        res = max(res, point1 + point2)
    print(res)


if __name__ == '__main__':
    resolve()