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.

Solution (Python):
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()

Solution (Python):


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

x, v = [], []
for i in range(n):
    a, b = list(map(int, input().split()))
    x.append(a)
    v.append(b)

cw = [0]*(n+1)
ccw = [0]*(n+1)
for i in range(n):
    cw[i+1] = cw[i]+v[i]
    ccw[i+1] = ccw[i]+v[-i-1]


for i in range(1, n+1):
    cw[i] -= x[i-1]
    ccw[i] -= c-x[-i]


maxcw = [0]*(n+1)
maxccw = [0]*(n+1)
for i in range(1, n+1):
    maxcw[i] = max(maxcw[i-1], cw[i])
    maxccw[i] = max(maxccw[i-1], ccw[i])

ans = max(0, maxcw[-1], maxccw[-1])

for i in range(1, n+1):
    ans = max(ans, cw[i] + maxccw[-i-1] - x[i-1])
    ans = max(ans, ccw[i] + maxcw[-i-1]-(c-x[-i]))

print(ans)

Solution (Python):
N, C = map(int, input().split())
XV = []

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



R = [0]
Rr = [0]
for x, v in XV:
  R.append(R[-1] + v)
  Rr.append(Rr[-1] + v)
for i, (x, v) in enumerate(XV):
  R[i+1] -= x
  Rr[i+1] -= 2*x
for i in range(N):
  Rr[i+1] = max(Rr[i+1], Rr[i])


L = [0]
Lr = [0]
for x, v in reversed(XV):
  L.append(L[-1] + v)
  Lr.append(Lr[-1] + v)
for i, (x, v) in enumerate(reversed(XV)):
  L[i+1] -= (C-x)
  Lr[i+1] -= 2*(C-x)
for i in range(N):
  Lr[i+1] = max(Lr[i+1], Lr[i])


ans = 0

for i in range(1, N+1):
  temp = max(R[i], R[i] + Lr[N-i], L[N+1-i], L[N+1-i] + Rr[i-1])
  ans = max(ans, temp)

print(ans)

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]
import heapq
N,C=map(int,input().split())
a=0
x=[0]*N
v=[0]*N
for i in range(N):
    x[i],v[i]=map(int,input().split())
h=[0]
s=t=sum(v)
for i in range(N-1,-1,-1):
    k=t-x[i]-h[0]
    if k>a:
        a=k
    t-=v[i]
    heapq.heappush(h,t-s+2*(C-x[i]))
h=[0]
t=s
for i in range(N):
    k=t-C+x[i]-h[0]
    if k>a:
        a=k
    t-=v[i]
    heapq.heappush(h,t-s+2*x[i])
print(a)

Solution (Python):
import sys
input = sys.stdin.readline

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

for x, v in xv:
    av += v
    left.append(av-2*x)

right = [0]
av = 0

for x, v in xv[::-1]:
    av += v
    right.append(av-2*(C-x))

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

ans = 0
av = 0

for i in range(N):
    av += xv[i][1]
    ans = max(ans, av-xv[i][0]+right[N-1-i])

av = 0

for i in range(N):
    av += xv[N-1-i][1]
    ans = max(ans, av-(C-xv[N-1-i][0])+left[N-1-i])

print(ans)

Solution (Python):
import sys
import math
import collections
import bisect
import itertools



sys.setrecursionlimit(10 ** 7)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))




def main():
    n, c = ns()

    dist = []
    value = []
    dist_r = []
    value_r = []
    for _ in range(n):
        di, vi = ns()
        dist.append(di)
        value.append(vi)
        dist_r.append(c - di)
        value_r.append(vi)

    dist_r.reverse()
    value_r.reverse()

    cum = []
    cum_r = []

    value_sum = 0
    value_max = -INF
    for di, vi in zip(dist, value):
        value_sum += vi
        value_max = max(value_max, value_sum - di)
        cum.append(value_max)

    value_sum = 0
    value_max = -INF
    for di, vi in zip(dist_r, value_r):
        value_sum += vi
        value_max = max(value_max, value_sum - di)
        cum_r.append(value_max)

    ans = 0
    for i in range(n):
        a = cum[i]
        c = cum_r[i]
        b, d = 0, 0
        if i != n - 1:
            b = cum[i] - dist[i] + cum_r[n - 2 - i]
            d = cum_r[i] - dist_r[i] + cum[n - 2 - i]
        ans = max(ans, a, b, c, d)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



n, c = LI()
clock_pos = []
value = []
for pos, v in LIR(n):
    clock_pos += [pos]
    value += [v]

r1 = 0
r2 = 0
A1 = [0]
A2 = [0]
for i in range(n):
    r1 += value[i]
    r2 += value[-i - 1]
    A1 += [max(A1[i], r1 - clock_pos[i])]
    A2 += [max(A2[i], r2 - (c - clock_pos[-i-1]))]

ans = 0
for j in range(n-1):
    ans = max(ans, A1[j+1] + A2[n - j - 1] - clock_pos[j], A2[j+1] + A1[n - j - 1] - (c - clock_pos[-j-1]))

print(max(ans, A1[-1], A2[-1]))

Solution (Python):
import sys
input = sys.stdin.buffer.readline

n, c = map(int, input().split())
X = [0]*n
V = [0]*n
for i in range(n):
    x, v = map(int, input().split())
    X[i] = x
    V[i] = v

from itertools import accumulate

A1 = [0]+V
A1 = list(accumulate(A1))
for i, x in enumerate(X):
    A1[i+1] -= x



B1 = [0]+list(reversed(V))
B1 = list(accumulate(B1))
for i, x in enumerate(reversed(X)):
    B1[i+1] -= c-x


import copy
MA1 = copy.copy(A1)
for i in range(1, n+1):
    MA1[i] = max(MA1[i-1], A1[i])

MB1 = copy.copy(B1)
for i in range(1, n+1):
    MB1[i] = max(MB1[i-1], B1[i])




A2 = copy.copy(A1)
for i, x in enumerate(X):
    A2[i+1] -= x


B2 = copy.copy(B1)
for i, x in enumerate(reversed(X)):
    B2[i+1] -= c-x


MA2 = copy.copy(A2)
for i in range(1, n+1):
    MA2[i] = max(MA2[i-1], A2[i])

MB2 = copy.copy(B2)
for i in range(1, n+1):
    MB2[i] = max(MB2[i-1], B2[i])




ans = 0

for i in range(n+1):
    temp = MA2[i]+MB1[n-i]
    ans = max(ans, temp)

for i in range(n+1):
    temp = MB2[i]+MA1[n-i]
    ans = max(ans, temp)
print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

n, c = map(int, input().split())
X = [0]*n
V = [0]*n
for i in range(n):
    x, v = map(int, input().split())
    X[i] = x
    V[i] = v

from itertools import accumulate

A1 = [0]+V
A1 = list(accumulate(A1))
for i, x in enumerate(X):
    A1[i+1] -= x



B1 = [0]+list(reversed(V))
B1 = list(accumulate(B1))
for i, x in enumerate(reversed(X)):
    B1[i+1] -= c-x


import copy
MA1 = copy.copy(A1)
for i in range(1, n+1):
    MA1[i] = max(MA1[i-1], A1[i])

MB1 = copy.copy(B1)
for i in range(1, n+1):
    MB1[i] = max(MB1[i-1], B1[i])




A2 = copy.copy(A1)
for i, x in enumerate(X):
    A2[i+1] -= x


B2 = copy.copy(B1)
for i, x in enumerate(reversed(X)):
    B2[i+1] -= c-x


MA2 = copy.copy(A2)
for i in range(1, n+1):
    MA2[i] = max(MA2[i-1], A2[i])

MB2 = copy.copy(B2)
for i in range(1, n+1):
    MB2[i] = max(MB2[i-1], B2[i])




ans = 0

for i in range(n+1):
    temp = MA2[i]+MB1[n-i]
    ans = max(ans, temp)

for i in range(n+1):
    temp = MB2[i]+MA1[n-i]
    ans = max(ans, temp)
print(ans)

Solution (Python):
import sys

N, C = map(int, sys.stdin.readline().split())

sushi_set = []
for i in range(N):
    x, v = map(int, sys.stdin.readline().split())
    sushi_set.append((x, v))
sushi_set.sort()

ans = -1



right = [0 for _ in range(N)]
max_n = -float("inf")
energy = 0
right_back = [0 for _ in range(N)]
for i, (x, v) in enumerate(sushi_set):
    energy += v
    if energy - x > max_n:
        max_n = energy - x
    right[i] = max_n
    right_back[i] = energy - 2 * x


left = [0 for _ in range(N)]
max_n = -float("inf")
energy = 0
left_back = [0 for _ in range(N)]
for i, (x, v) in enumerate(sushi_set[::-1]):
    energy += v
    if energy - (C - x) > max_n:
        max_n = energy - (C - x)
    left[i] = max_n
    left_back[i] = energy - 2 * (C - x)






ans = max(max(right), max(left))


for i in range(N-1):
    ans = max(ans, right_back[i] + left[N-2-i])

for i in range(N-1):
    ans = max(ans, left_back[i] + right[N-2-i])

print(max(ans, 0))

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def calc_max(A):
    Amax = [0] * len(A)
    cal = 0
    for i, (x, v) in enumerate(A):
        cal += v
        if i == 0:
            Amax[i] = max(cal - x, 0)
        else:
            Amax[i] = max(cal - x, Amax[i - 1])

    return Amax


def solve(A, Amax, B, Bmax, ans):
    N = len(A)
    for i in range(N - 1):
        if ans < Amax[i] - A[i][0] + Bmax[N - i - 2]:
            ans = Amax[i] - A[i][0] + Bmax[N - i - 2]

    return ans


def main():
    N, C, *XV = map(int, read().split())

    A = [0] * N
    for i, (x, v) in enumerate(zip(*[iter(XV)] * 2)):
        A[i] = (x, v)
    Amax = calc_max(A)

    B = [(C - x, v) for x, v in reversed(A)]
    Bmax = calc_max(B)

    ans = max(Amax[-1], Bmax[-1])
    ans = max(ans, solve(A, Amax, B, Bmax, ans))
    ans = max(ans, solve(B, Bmax, A, Amax, ans))

    print(ans)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np
import itertools
N, C, *XV = [int(_) for _ in open(0).read().split()]
XV = [0, 0] + XV
XV = np.array(XV).reshape((N+1, 2))
YV = np.zeros((N+1, 2), dtype=np.int64)
YV[1:] = XV[:0:-1]
YV[1:, 0] *= -1
YV[1:, 0] += C

def calc(XV,YV):
    cumxvv = np.cumsum(XV[:, 1])
    cumxvv -= 2 * XV[:, 0]
    cumyvv = np.cumsum(YV[:, 1])
    cumyvv -= YV[:, 0]
    cummaxyvv = list(itertools.accumulate(cumyvv, func=lambda a, b: a if a > b else b))
    ans=-float('inf')
    for i in range(N + 1):
        ans = max(ans, cumxvv[i] + cummaxyvv[N - i])
    return ans
print(max(calc(XV, YV), calc(YV, XV)))

Solution (Python):

import sys
def main(N, C, XV):
    rXV = [(C - x, v) for x, v in reversed(XV)]
    ans1 = solve(N, C, XV, rXV)
    ans2 = solve(N, C, rXV, XV)
    print(max(ans1, ans2))

def solve(N, C, XV, rXV):
    M = [0]
    px = 0
    now = 0
    tmp = 0
    for x, v in rXV:
        now += v - (x - px)
        tmp = max(tmp, now)
        M.append(tmp)
        px = x

    res = 0
    px = 0
    now = 0
    for i, (x, v) in enumerate(XV):
        now += v - (x - px)
        res = max(res, now)
        res = max(res, now - x + M[N - i - 1])
        px = x
    return res

if __name__ == '__main__':
    input = sys.stdin.readline
    N, C = map(int, input().split())
    XV = [tuple(map(int, input().split())) for _ in range(N)]
    main(N, C, XV)

Solution (Python):
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 segfunc(x, y):
    """
    区間(x,y)に対して行いたい操作の入力
    最小値：min(x,y)
    最大値：max(x,y)
    和：x + y
    積：x * y
    最大公約数：math.gcd(x, y)
    """
    return max(x, y)


ide_ele = -f_inf


def resolve():
    n, c = map(int, input().split())
    XV = [list(map(int, input().split())) for _ in range(n)]

    R = [0]
    prev = 0
    for i in range(n):
        x, v = XV[i]
        R.append(R[-1] + v - (x - prev))
        prev = x
    seg = SegTree(R, segfunc, ide_ele)

    R_r = [0]
    prev_r = 0
    for i in reversed(range(n)):
        x_r, v_r = XV[i]
        x_r = c - x_r
        R_r.append(R_r[-1] + v_r - (x_r - prev_r))
        prev_r = x_r
    seg_r = SegTree(R_r, segfunc, ide_ele)

    res1 = max(R)
    res2 = max(R_r)
    res3 = 0
    for i in range(1, n + 1):
        right = R[i] - XV[i - 1][0]
        idx = n + 1 - i
        left = seg_r.query(0, idx)
        res3 = max(res3, right + left)
    res4 = 0
    for i in range(1, n + 1):
        left_r = R_r[i] - (c - XV[-i][0])
        idx_r = n + 1 - i
        right_r = seg.query(0, idx_r)
        res4 = max(res4, left_r + right_r)
    print(max(res1, res2, res3, res4))


if __name__ == '__main__':
    resolve()

Solution (Python):
import sys
from copy import deepcopy as copy
input = sys.stdin.readline

def main():
  n, c = map(int, input().split())
  sushi = [[0, 0]]+[[int(x) for x in input().split()] for _ in range(n)]

  order = [0]*(n+1)
  reverse = [0]*(n+1)

  for i in range(n):
    order[i+1] = order[i]+sushi[i+1][1]
    reverse[i+1] = reverse[i]+sushi[n-i][1]

  order_index = [i for i in range(n+1)]
  reverse_index = [-i for i in range(n+1)]
  for i in range(n):
    order[i+1] -= sushi[i+1][0]
    if order[i+1] <= order[i]:
      order[i+1] = order[i]
      order_index[i+1] = order_index[i]
    reverse[i+1] -= c-sushi[n-i][0]
    if reverse[i+1] <= reverse[i]:
      reverse[i+1] = reverse[i]
      reverse_index[i+1] = reverse_index[i]

  order_back = copy(order)
  reverse_back = copy(reverse)
  for i in range(n+1):
    order_back[i] -= sushi[order_index[i]][0]
    if i != 0 and order_back[i] < order_back[i-1]:
      order_back[i] = order_back[i-1]
    reverse_back[i] -= (c-sushi[reverse_index[i]][0])%c
    if i != 0 and reverse_back[i] < reverse_back[i-1]:
      reverse_back[i] < reverse_back[i-1]

  ans = 0
  for i in range(n+1):
    sub = max(order[i]+reverse_back[n-i], order_back[i]+reverse[n-i])
    if ans < sub:
      ans = sub

  print(ans)

if __name__ == "__main__":
  main()

Solution (Python):
from copy import deepcopy as copy

n, c = map(int, input().split())
sushi = [[0, 0]]+[[int(x) for x in input().split()] for _ in range(n)]

order = [0]*(n+1)
reverse = [0]*(n+1)

for i in range(n):
  order[i+1] = order[i]+sushi[i+1][1]
  reverse[i+1] = reverse[i]+sushi[n-i][1]

order_index = [i for i in range(n+1)]
reverse_index = [-i for i in range(n+1)]
for i in range(n):
  order[i+1] -= sushi[i+1][0]
  if order[i+1] <= order[i]:
    order[i+1] = order[i]
    order_index[i+1] = order_index[i]
  reverse[i+1] -= c-sushi[n-i][0]
  if reverse[i+1] <= reverse[i]:
    reverse[i+1] = reverse[i]
    reverse_index[i+1] = reverse_index[i]

order_back = copy(order)
reverse_back = copy(reverse)
for i in range(n+1):
  order_back[i] -= sushi[order_index[i]][0]
  if i != 0 and order_back[i] < order_back[i-1]:
    order_back[i] = order_back[i-1]
  reverse_back[i] -= (c-sushi[reverse_index[i]][0])%c
  if i != 0 and reverse_back[i] < reverse_back[i-1]:
    reverse_back[i] < reverse_back[i-1]

ans = 0
for i in range(n+1):
  sub = max(order[i]+reverse_back[n-i], order_back[i]+reverse[n-i])
  if ans < sub:
    ans = sub

print(ans)

Solution (Python):
n,c=map(int,input().split())
x=[0]
v=[0]
su=[0]*(n+1)
for i in range(n):
    xx,vv=map(int,input().split())
    x.append(xx)
    v.append(vv)
    su[i+1]=su[i]+v[i+1]
lmax=[0]*(n+2)
rmax=[0]*(n+2)
for i in range(n):
    lmax[i+1]=max(lmax[i],su[i+1]-x[i+1])
    rmax[n-i]=max(rmax[n-i+1],(su[n]-su[n-i-1])-(c-x[n-i]))
ans=0
for i in range(n):
    ans=max(ans,su[i+1]-2*x[i+1]+rmax[i+2])
    ans=max(ans,(su[n]-su[n-i-1])-2*(c-x[n-i])+lmax[n-i-1])
ans = max(ans, max(lmax[n],rmax[1]))
print(ans)

Solution (Python):
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())

N,M = MI()
xv = [(0,0)] + [tuple(MI()) for _ in range(N)]

A = [0]*(N+1)  
a = 0
for i in range(1,N+1):
    x,v = xv[i]
    x0,v0 = xv[i-1]
    a += v-(x-x0)
    if a > A[i-1]:
        A[i] = a
    else:
        A[i] = A[i-1]

B = [0]*(N+1)  
b = 0
for i in range(1,N+1):
    x,v = xv[i]
    x0,v0 = xv[i-1]
    b += v-2*(x-x0)
    if b > B[i-1]:
        B[i] = b
    else:
        B[i] = B[i-1]

for i in range(1,N+1):
    x,v = xv[i]
    xv[i] = (M-x,v)
xv.sort()

C = [0]*(N+1)  
c = 0
for i in range(1,N+1):
    x,v = xv[i]
    x0,v0 = xv[i-1]
    c += v-(x-x0)
    if c > C[i-1]:
        C[i] = c
    else:
        C[i] = C[i-1]

D = [0]*(N+1)  
d = 0
for i in range(1,N+1):
    x,v = xv[i]
    x0,v0 = xv[i-1]
    d += v-2*(x-x0)
    if d > D[i-1]:
        D[i] = d
    else:
        D[i] = D[i-1]

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

Solution (Python):
from itertools import accumulate

n, c = (int(x) for x in input().split())
X = []
V = []
D = []
prev_x = 0
for _ in range(n):
    x, v = (int(x) for x in input().split())
    X.append(x)
    D.append(x - prev_x)
    V.append(v)
    prev_x = x
D.append(c - X[-1])
rev_D = list(reversed(D))
rev_V = list(reversed(V))

ans = 0

A = [0] * n
for i in range(n):
    A[i] = V[i] - D[i]
acc_A = list(accumulate(A))
ans = max(ans, max(acc_A))


B = [0] * n
for i in range(n):
    B[i] = rev_V[i] - rev_D[i]
acc_B = list(accumulate(B))
ans = max(ans, max(acc_B))

max_acc_A = [acc_A[0]]
max_acc_B = [acc_B[0]]
for i in range(1, n):
    max_acc_A.append(max(max_acc_A[-1], acc_A[i]))
    max_acc_B.append(max(max_acc_B[-1], acc_B[i]))


tmp = 0
for i in range(n - 1):
    tmp_cal = acc_A[i] - X[i]  
    tmp = max(tmp, tmp_cal + max_acc_B[n - i - 2])
ans = max(ans, tmp)


tmp = 0
for i in range(n - 1):
    tmp_cal = acc_B[i] - (c - X[-i - 1])  
    tmp = max(tmp, tmp_cal + max_acc_A[n - i - 2])
ans = max(ans, tmp)

print(ans)

Solution (Python):
from itertools import accumulate

class SegTree:  
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]



n, c = (int(x) for x in input().split())
X = []
V = []
D = []
prev_x = 0
for _ in range(n):
    x, v = (int(x) for x in input().split())
    X.append(x)
    D.append(x - prev_x)
    V.append(v)
    prev_x = x
D.append(c - X[-1])
rev_D = list(reversed(D))
rev_V = list(reversed(V))

ans = 0

A = [0] * n
for i in range(n):
    A[i] = V[i] - D[i]
acc_A = list(accumulate(A))
ans = max(ans, max(acc_A))


B = [0] * n
for i in range(n):
    B[i] = rev_V[i] - rev_D[i]
acc_B = list(accumulate(B))
ans = max(ans, max(acc_B))


seg_B = SegTree(acc_B, fx=max, ex=-10**18)
tmp = 0
for i in range(n - 1):
    tmp_cal = acc_A[i] - X[i]  
    tmp = max(tmp, tmp_cal + seg_B.query(0, n-i-1))
ans = max(ans, tmp)


seg_A = SegTree(acc_A, fx=max, ex=-10**18)
tmp = 0
for i in range(n - 1):
    tmp_cal = acc_B[i] - (c - X[-i - 1])  
    tmp = max(tmp, tmp_cal + seg_A.query(0, n-i-1))
ans = max(ans, tmp)

print(ans)

Solution (Python):
N,C=map(int, input().split())
x=[]
v=[]

for i in range(N):
  xi,vi = map(int, input().split())
  x.append(xi)
  v.append(vi)

l1 = [0]
l2 = [0]
r1 = [0]
r2 = [0]

vtotal = 0
for i in range(N):
  vtotal += v[i]
  l1.append(max(l1[-1], vtotal - x[i]))
  l2.append(max(l2[-1], vtotal - 2 * x[i]))

vtotal = 0
for i in range(N-1, -1, -1):
  vtotal += v[i]
  r1.append(max(r1[-1], vtotal-(C-x[i])))
  r2.append(max(r2[-1], vtotal-2*(C-x[i])))

ans = 0
for i in range(N+1):
  ans = max(ans, l1[i] + r2[N-i], l2[i] + r1[N-i])

print(ans)

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

cumR=[0]*(N+1)
cummaxR=[0]*(N+1)
for i in range(N):
    cumR[i+1]=cumR[i]+li[i][1]-li[i][0]
    cummaxR[i+1]=cummaxR[i]+li[i][1]-li[i][0]*2
    if i>0:
        cumR[i+1]+=li[i-1][0]
        cummaxR[i+1]+=li[i-1][0]*2
for i in range(1,N):
    cummaxR[i]=max(cummaxR[i],cummaxR[i-1])
cumL=[0]*(N+1)
cummaxL=[0]*(N+1)
for i in reversed(range(N)):
    cumL[i]=cumL[i+1]+li[i][1]-(C-li[i][0])
    cummaxL[i]=cummaxL[i+1]+li[i][1]-(C-li[i][0])*2
    if i<N-1:
        cumL[i]+=(C-li[i+1][0])
        cummaxL[i]+=(C-li[i+1][0])*2
for i in reversed(range(N)):
    cummaxL[i]=max(cummaxL[i],cummaxL[i+1])
ans=0
for i in range(N):
    ans=max(ans,cumR[i+1]+cummaxL[i+1])
    ans=max(ans,cumL[i]+cummaxR[i])
print(ans)

Solution (Python):
N,C = map(int,input().split())
xv = [[0,0]]+[list(map(int,input().split())) for i in range(N)]+[[C,0]]






tokei_maxs = [0]*(N+2)

tokei=[0]*(N+2)
tokei_max = 0
preans = 0
for i in range(1,N+1,1):
    tmpans = preans + xv[i][1] - (xv[i][0]-xv[i-1][0])
    tokei_max = max(tokei_max,tmpans)
    tokei[i]=tmpans
    tokei_maxs[i]=tokei_max
    preans = tmpans



htokei_maxs = [0]*(N+2)
htokei=[0]*(N+2)

htokei_max = 0
preans = 0
for i in range(N,0,-1):
    tmpans = preans + xv[i][1] - (xv[i+1][0]-xv[i][0])
    htokei_max = max(htokei_max,tmpans)
    htokei_maxs[i]=htokei_max
    htokei[i]=tmpans
    preans=tmpans

ans = max(max(tokei),max(htokei))

for i in range(0,N+1,1):
    ans = max(ans,tokei[i]+htokei_maxs[i+1]-xv[i][0])
for i in range(N+1,0,-1):
    ans = max(ans,htokei[i]+tokei_maxs[i-1]-C+xv[i][0])

print(ans)

Solution (Python):
n,c=map(int,input().split())
l,L,m,M,C,a,x,v=[0],[0],[0],[0],0,0,[],[]
for i in range(n):X,V=map(int,input().split());x.append(X);v.append(V)
for i in range(n):C+=v[i];l.append(max(l[-1],C-x[i]));L.append(max(L[-1],C-2*x[i]))
C=0
for i in range(n)[::-1]:C+=v[i];m.append(max(m[-1],C-(c-x[i])));M.append(max(M[-1],C-2*(c-x[i])))
for i in range(n+1):a=max(a,l[i]+M[n-i],L[i]+m[n-i])
print(a)

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

cr=[0]*(n+1)
cl=[0]*(n+1)

for i in range(n):
    cr[i+1]=cr[i]+xv[i][1]
    cl[n-i-1]=cl[n-i]+xv[n-i-1][1]

leftmax=[0]*(n+1)

for i in range(n-1,-1,-1):
    leftmax[i]=max(leftmax[i+1],cl[i]-2*(c-xv[i][0]))

rightmax=[0]*(n+1)

for i in range(n):
    rightmax[i+1]=max(rightmax[i],cr[i+1]-2*xv[i][0])

ans=0
for i in range(n):
    ans=max(ans,cr[i+1]-xv[i][0]+leftmax[i+1])
    ans=max(ans,cl[n-i-1]-c+xv[n-i-1][0]+rightmax[n-i-1])

print(ans)

Solution (Python):
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]

right=[0]*n
right_re=[0]*n

sumv=0

for i,(x,v) in enumerate(xv):
    if i==0:
        sumv=v
        right[i]=max(0,sumv-x)
        right_re[i]=max(0,sumv-2*x)
    else:
        sumv+=v
        right[i]=max(right[i-1],sumv-x)
        right_re[i]=max(right_re[i-1],sumv-2*x)    

sumv=0
left=[0]*n
left_re=[0]*n


for i,(x,v) in enumerate(xv_rev):
    if i==0:
        sumv=v
        left[i]=max(0,sumv-x)
        left_re[i]=max(0,sumv-2*x)
    else:
        sumv+=v
        left[i]=max(left[i-1],sumv-x)
        left_re[i]=max(left_re[i],sumv-2*x)    

ans=0
for i in range(n):
    if i==n-1:
        ans=max(ans,right[i])
        ans=max(ans,left[i])
    else:
        ans=max(ans,right[i]+left_re[n-i-2])
        ans=max(ans,left[i]+right_re[n-i-2])

print(ans)