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:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    x = [0] + x
    v = [0] + v

    mx_r = [0]
    for xx, acc in zip(x[1:], accumulate(v[1:], add)):
        mx_r.append(max(acc - xx, mx_r[-1]))

    mx_l = [0]
    for xx, cal in zip(reversed(x), accumulate(reversed(v), add)):
        mx_l.append(max(cal - (C - xx), mx_l[-1]))
    mx_l.reverse()

    ans = 0
    for i in range(N+1):
        ans = max(mx_r[i], mx_r[i] - x[i] + mx_l[i+1], ans)
        if i != 0:
            ans = max(mx_l[i], mx_l[i] - (C - x[i]) + mx_r[i-1], ans)
    return ans


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    x = [int()] * (N)  # type: "List[int]" 
    v = [int()] * (N)  # type: "List[int]" 
    for i in range(N):
        x[i] = int(next(tokens))
        v[i] = int(next(tokens))
    result = solve(N, C, x, v)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,C = map(int,input().split())
L = []
for i in range(N):
  L.append(list(map(int,input().split())))
A = [0]
B = [0]
k = 0
for i in range(N):
  k += L[i][1]
  p = max(A[i],k-L[i][0])
  A.append(p)
k = 0
for i in range(N):
  k += L[N-i-1][1]
  p = max(B[i],k-(C-L[N-i-1][0]))
  B.append(p)
ans = max(A[N],B[N])
t = 0
for i in range(N):
  b = L[N-i-1][0]
  t += L[N-i-1][1]
  if ans <= t-2*(C-b)+A[N-i-1]:
    ans = t-2*(C-b)+A[N-i-1]
t = 0
for i in range(N):
  a = L[i][0]
  t += L[i][1]
  if ans <= t-2*a+B[N-i-1]:
    ans = t-2*a+B[N-i-1]
print(ans)

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
IA=[eval(input().replace(" ",","))for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
RS=0
for i,[a,v] in enumerate(IA):
  CS[i+1]=CS[i]+v
  MS[i+1]=max(CS[i+1]-a,MS[i][0]),max(CS[i+1]-2*a,MS[i][1])
for i in range(N):
  ob=CS[N]-CS[i]
  RS=max(RS,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(RS,MS[N][0],0))

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
IA=[[int(i)for i in input().split()]for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
for i,[a,v] in enumerate(IA):
  CS[i+1]=CS[i]+v
  MS[i+1]=CS[i+1]-a if(CS[i+1]-a)>MS[i][0]else MS[i][0],CS[i+1]-2*a if(CS[i+1]-2*a)>MS[i][1]else MS[i][1]
RS=0
for i in range(N):
  ob=CS[N]-CS[i]
  RS=max(RS,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(RS, MS[N][0], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
IA=[[int(i)for i in input().split()]for _ in range(N)]
MS=[(0,0)]*(N+1)
CS=[0]*(N+1)
for i,[a,v] in enumerate(IA):
    CS[i+1]=CS[i]+v
    MS[i+1]=CS[i+1]-a if(CS[i+1]-a)>MS[i][0]else MS[i][0],CS[i+1]-2*a if(CS[i+1]-2*a)>MS[i][1]else MS[i][1]
res = 0
for i in range(N):
    ob=CS[N]-CS[i]
    res=max(res,ob+MS[i][0]-2*(C-IA[i][0]),ob+MS[i][1]-(C-IA[i][0]))
print(max(res, MS[N][0], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
IA=[[int(i) for i in input().split()] for _ in range(N)]
MS=[[0]*(N+1),[0]*(N+1)]
CS=[0]*(N+1)
cum = 0
for i,[a,v] in enumerate(IA):
    cum += v
    MS[0][i+1]=cum-a if(cum-a)>MS[0][i]else MS[0][i]
    MS[1][i+1]=cum-2*a if(cum-2*a)>MS[1][i]else MS[1][i]
    CS[i+1]=cum
res = 0
for i in range(N):
    ob=CS[N]-CS[i]
    res=max(res,ob+MS[0][i]-2*(C-IA[i][0]),ob+MS[1][i]-(C-IA[i][0]))
print(max(res, MS[0][N], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
IA=[[int(i) for i in input().split()] for _ in range(N)]
MS=[[(0, 0)]*(N+1),[(0, 0)]*(N+1)]
CS=[0]*(N+1)
cum = 0
for i,[a,v] in enumerate(IA):
    cum += v
    MS[0][i+1]=(cum-a,a)if(cum-a)>MS[0][i][0]else MS[0][i]
    MS[1][i+1]=(cum-2*a,a)if(cum-2*a)>MS[1][i][0]else MS[1][i]
    CS[i+1]=cum
resmax = 0
for i in range(N):
    oasum1, x = MS[0][i]
    oasum2, x = MS[1][i]
    ob = CS[N] - CS[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-IA[i][0]), ob + oasum2 - (C-IA[i][0]))
print(max(resmax, MS[0][N][0], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes=[[(0, 0)]*(N+1),[(0, 0)]*(N+1)]
cums=[0]*(N+1)
cum = 0
for i, [a, v] in enumerate(inarr):
    cum += v
    maxes[0][i+1]=(cum-a,a) if (cum - a) > maxes[0][i][0] else maxes[0][i]
    maxes[1][i+1]=(cum-2*a,a) if (cum - 2*a) > maxes[1][i][0] else maxes[1][i]
    cums[i+1]=cum

resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = maxes[0][i]
    oasum2, x = maxes[1][i]
    ob = cums[N] - cums[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-b), ob + oasum2 - (C-b))

print(max(resmax, maxes[0][N][0], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes=[[(0, 0)]*N,[(0, 0)]*N]
cums=[0]*(N+1)
cum = 0
cummax1 = (0, 0)
cummax2 = (0, 0)
for i, [a, v] in enumerate(inarr):
    cum += v
    if (cum - a) > cummax1[0]:
        cummax1 = (cum - a, a)
    if (cum - 2*a) > cummax2[0]:
        cummax2 = (cum - 2*a, a)
    maxes[0][i]=cummax1
    maxes[1][i]=cummax2
    cums[i+1]=cum

resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = (0, 0) if i == 0 else maxes[0][i-1]
    oasum2, x = (0, 0) if i == 0 else maxes[1][i-1]
    ob = cums[N] - cums[i]
    resmax = max(resmax, ob + oasum1 - 2*(C-b), ob + oasum2 - (C-b))

print(max(resmax, maxes[0][N-1][0], 0))

Submission status: Accepted

Solution code:
N,C=map(int, input().split())
inarr=[[int(i) for i in input().split()] for _ in range(N)]
maxes1=[(0, 0)]*N
maxes2=[(0, 0)]*N
cums=[0]*(N+1)
cum = 0
cummax1 = (0, 0)
cummax2 = (0, 0)
for i, [a, v] in enumerate(inarr):
    cum += v
    if (cum - a) > cummax1[0]:
        cummax1 = (cum - a, a)
    if (cum - 2*a) > cummax2[0]:
        cummax2 = (cum - 2*a, a)
    maxes1[i]=cummax1
    maxes2[i]=cummax2
    cums[i+1]=cum

# print("{}".format(maxes1))
resmax = 0
for i, [b, v] in enumerate(inarr):
    oasum1, x = (0, 0) if i == 0 else maxes1[i-1]
    oasum2, x = (0, 0) if i == 0 else maxes2[i-1]
    obsum = cums[N] - cums[i]
    resmax = max(resmax, obsum + oasum1 - 2*(C-b), obsum + oasum2 - (C-b))
    # print(resmax)

# print(maxes1[N-1])
print(max(resmax, maxes1[N-1][0], 0))

Submission status: Accepted

Solution code:
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys

sys.setrecursionlimit(10000)
INF = float('inf')


def cummax(li, first=-float('inf')):
    """
    累積 max
    :param collections.Iterable li:
    :param float first:
    :return:
    """
    cm = first
    ret = []
    for v in li:
        cm = max(v, cm)
        ret.append(cm)
    return ret


N, C = list(map(int, input().split()))
X, V = zip(*[list(map(int, input().split())) for _ in range(N)])

X = np.array(X)
V = np.array(V)

# cs1[i]: 時計回りに i 番目まで食べたときの累計カロリー
cs1 = V.cumsum() - X
# 累積 max
cm1 = np.array(cummax(cs1, first=0))

# cs2[i]: 反時計回りに i 番目まで食べたときの累計カロリー
cs2 = V[::-1].cumsum() - (C - X)[::-1]
# 累積 max
cm2 = np.array(cummax(cs2, first=0))
cs2 = cs2[::-1]
cm2 = cm2[::-1]

ans = max(cm1[-1], cm2[0])
# 時計回りに X[L] まで行って折り返したときの最大
for L in range(len(X) - 1):
    ans = max(ans, cm1[L] + cm2[L + 1] - X[L])
# 反時計回りが先の場合
for r in reversed(range(1, len(X))):
    ans = max(ans, cm2[r] + cm1[r - 1] - (C - X[r]))
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys

sys.setrecursionlimit(10000)
INF = float('inf')


def cummax(li, first=-float('inf')):
    """
    累積 max
    :param collections.Iterable li:
    :param float first:
    :return:
    """
    cm = first
    ret = []
    for v in li:
        cm = max(v, cm)
        ret.append(cm)
    return ret


N, C = list(map(int, input().split()))
X, V = zip(*[list(map(int, input().split())) for _ in range(N)])

X = np.array(X)
V = np.array(V)

# cs1[i]: 時計回りに i 番目まで食べたときの累計カロリー
cs1 = V.cumsum() - X
# 累積 max
cm1 = np.array(cummax(cs1, first=0))

# cs2[i]: 反時計回りに i 番目まで食べたときの累計カロリー
cs2 = V[::-1].cumsum() - (C - X)[::-1]
# 累積 max
cm2 = np.array(cummax(cs2, first=0))
cs2 = cs2[::-1]
cm2 = cm2[::-1]

ans = max(cm1.max(), cm2.max())
# 時計回りに X[L] まで行って、折り返して反時計回りに X[r] まで行く
r = 0
for L in range(len(X)):
    while r < len(X) and X[r] < X[L] * 2:
        r += 1
    if r < len(X):
        ans = max(ans, cm1[L] + cm2[r] - X[L])
    else:
        break
# 反時計回りが先
L = len(X) - 1
for r in reversed(range(len(X))):
    while L >= 0 and X[L] > C - (C - X[r]) * 2:
        L -= 1
    if L >= 0:
        ans = max(ans, cm2[r] + cm1[L] - (C - X[r]))
    else:
        break
print(ans)

Submission status: Accepted

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

max_e = 0

# clock
e = 0
for x, v in ss:
    e += v
    max_e = max(max_e, e - x)

# aclock
e = 0
for x, v in ss[::-1]:
    e += v
    max_e = max(max_e, e - (c - x))


# aclock -> clock
clocks = []
e = 0
for x, v in ss:
    e += v
    clocks.append(e - x)

max_clocks = clocks[:]
for i in range(1, len(clocks)):
    max_clocks[i] = max(clocks[i], max_clocks[i-1])

e = 0
for i in range(len(ss) - 1, 0, -1):
    x, v = ss[i]
    e += v
    max_e = max(max_e, e - 2 * (c - x) + max_clocks[i-1])

# clock -> aclock
aclocks = []
e = 0
for x, v in ss[::-1]:
    e += v
    aclocks.append(e - (c - x))

max_aclocks = aclocks[:]
for i in range(1, len(aclocks)):
    max_aclocks[i] = max(aclocks[i], max_aclocks[i-1])

aclocks.reverse()
max_aclocks.reverse()

e = 0
for i in range(len(ss) - 1):
    x, v = ss[i]
    e += v
    max_e = max(max_e, e - 2 * x + max_aclocks[i+1])

print(max_e)

Submission status: Accepted

Solution code:
def main():
	N, C = map(int, input().split())
	sushi_r = [[0 for _ in range(2)] for _ in range(N+2)]
	sushi_l = [[0 for _ in range(2)] for _ in range(N+2)]
	sushi_r[N+1] = [C, 0]
	sushi_l[N+1] = [C, 0]
	dp_r = [0]*(N+2)
	dp_l = [0]*(N+2)
	ans = 0
	for i in range(1, N+1):
		sushi_r[i] = list(map(int, input().split()))
		sushi_r[i][1] += sushi_r[i-1][1]
		dp_r[i] = max(dp_r[i-1], sushi_r[i][1]-sushi_r[i][0])
	for i in range(1, N+1):
		sushi_l[i][0] = C - sushi_r[N-i+1][0]
		sushi_l[i][1] = sushi_r[N-i+1][1]-sushi_r[N-i][1] + sushi_l[i-1][1]
		dp_l[i] = max(dp_l[i-1], sushi_l[i][1]-sushi_l[i][0])

	for i in range(0, N+1):
		ans = max(ans, dp_l[i]-sushi_l[i][0]+dp_r[N-i])
		ans = max(ans, dp_r[i]-sushi_r[i][0]+dp_l[N-i])

	print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate
inf = float('inf')

def acc_max(array):
    na = []
    tmp = 0
    for a in array:
        if a > tmp:
            tmp = a
        na.append(tmp)
    return na

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

right = list(accumulate(V))
left = list(accumulate(V[::-1]))

right1 = [r - x for r, x in zip(right,X)]

left1 = [l - (C-x) for l, x in zip(left,X[::-1])]

right2 = acc_max([r - 2*x for r, x in zip(right,X)])

left2 = acc_max([l - 2*(C-x) for l, x in zip(left,X[::-1])])

ans = 0

for end in range(N):
    if end == N-1:
        res = max(right1[end],left1[end])
    else:
        res = max(right1[end]+left2[N-1-(end+1)],left1[end]+right2[N-1-(end+1)])
    if res > ans:
        ans = res

print(ans)

Submission status: Accepted

Solution code:
import numpy as np

N,C = list(map(int, input().split()))
XV = [list(map(int, input().split())) for _ in range(N)]
X = np.array([0] + [x for x,v in XV])
V = np.array([0] + [v for x,v in XV])

V_cw_cumsum = V.cumsum()

right_one_ways = V_cw_cumsum - X

V_ccw_cumsum = V[::-1].cumsum()[::-1]

left_one_ways = V_ccw_cumsum - (C-X)

def reduce_each(func, l):
  temp = l.copy()
  for i in range(1,len(l)):
    temp[i] = func(temp[i-1], temp[i])
  return temp


additional_left = np.roll(reduce_each(max, left_one_ways[::-1])[::-1], -1)
additional_left[-1] = 0
right_to_left = V_cw_cumsum - 2*X + additional_left

additional_right = np.roll(reduce_each(max, right_one_ways), 1)
additional_right[0] = 0
left_to_right = V_ccw_cumsum - 2*(C-X) + additional_right

print(max(max(right_one_ways),
          max(left_one_ways),
          max(right_to_left),
          max(left_to_right)))

Submission status: Accepted

Solution code:
from itertools import accumulate as acc
import sys

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

if N==1: print(max(0, a[0][1]-a[0][0], a[0][1]-(C-a[0][0]) ) ),sys.exit()

tmp=a[0][1]-a[0][0]
M=max(0,tmp)
l=[M]
for i in range(1,N):
    tmp+=a[i][1]-(a[i][0]-a[i-1][0])
    M=max(tmp,M)
    l.append(M)

tmp=a[N-1][1]-(C-a[N-1][0])
M=max(0,tmp)
r=[M]
for i in range(N-2,-1,-1):
    tmp+=a[i][1]-(a[i+1][0]-a[i][0])
    M=max(tmp,M)
    r.append(M)

r.reverse()

ans=max(l[0], r[0], l[0]-a[0][0]+r[1], l[N-1], r[N-1], r[N-1]-(C-a[N-1][0])+l[N-2])

for i in range(1,N-1):
    ans=max(ans, l[i], r[i], l[i]-a[i][0]+r[i+1], r[i]-(C-a[i][0])+l[i-1])

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate as acc
import sys

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

if N==1: print(max(0, a[0][1]-a[0][0], a[0][1]-(C-a[0][0]) ) ),sys.exit()

b=list(acc( [ a[i][1] for i in range(N)] ))

ans= sum([a[i][1] for i in range(N)])+max(C-a[0][0],a[N-1][0])

l=[[b[i]-a[i][0],0] for i in range(N)]
r=[[b[N-1]-(C-a[0][0]),0]]+[[b[N-1]-b[i]-(C-a[i+1][0]),0] for i in range(N-1)]

tmp=0
for i in range(N):
    if l[i][0]>tmp: tmp=l[i][0]
    l[i][1]=tmp
tmp=0
for i in range(N-1,-1,-1):
    if r[i][0]>tmp: tmp=r[i][0]
    r[i][1]=tmp

p=[l[0][1],r[0][1],l[0][1]-a[0][0]+r[1][1]]
q=[l[N-1][1],r[N-1][1],r[N-1][0]-(C-a[N-1][0])+l[N-2][1]]

ans=max(p+q)

for i in range(1,N-1):
    p1=l[i][1]
    p2=r[i][1]
    p3=l[i][1]-a[i][0]+r[i+1][1]
    p4=r[i][1]-(C-a[i][0])+l[i-1][1]
    
    ans=max(ans,p1,p2,p3,p4)
    
print(ans)

Submission status: Accepted

Solution code:
n, c, *t = map(int, open(0).read().split())
right = [0]
left = [0]
sushi = tuple([(0, 0)]) + tuple(zip(t[::2], t[1::2])) + tuple([(c, 0)])
for i in range(1, n + 1):
    x, v = sushi[i]
    y = sushi[i - 1][0]
    cost = right[-1] + v - (x - y)
    right.append(cost)
    x, v = sushi[n + 1 - i]
    y = sushi[n + 2 - i][0]
    cost = left[-1] + v - (y - x)
    left.append(cost)
ans = max(right + left)
right_max = right[:]
left_max = left[:]
for i in range(1, n + 1):
    right_max[i] = max(right_max[i], right_max[i - 1])
    left_max[i] = max(left_max[i], left_max[i - 1])
for i in range(1, n + 1):
    ans = max(ans, \
            right[i] - sushi[i][0] + left_max[n - i], \
            left[i] - c + sushi[n + 1 - i][0] + right_max[n - i])
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N, C = map(int, input().split())
XV = [list(map(int, input().split())) for i in range(N)]


V_minus_X = [XV[i][1]-(XV[i][0]-XV[i-1][0])
             for i in range(1, N)]  # i==0なら見ない それ以外ならXV[i-1][0]足して上げる
V_minus_X.insert(0, XV[0][1]-XV[0][0])
cum_ = np.cumsum(V_minus_X)


V_minus_X_reverse = [XV[i][1]-(XV[i+1][0]-XV[i][0])
                     for i in range(0, N-1)]
V_minus_X_reverse.append(XV[-1][1]-(C-XV[-1][0]))
V_minus_X_reverse.reverse()
cum_reverse = np.cumsum(V_minus_X_reverse)

m_ = []
m_reverse = []
maxim = 0
maxim_reverse = 0
maxim_where = 0
maxim_reverse_where = 0
# print("print")
for i in range(N-1):
    if maxim < cum_[i]:
        maxim = cum_[i]
        maxim_where = XV[i][0]
    if maxim_reverse < cum_reverse[i]:
        maxim_reverse = cum_reverse[i]
        maxim_reverse_where = C - XV[-i - 1][0]
    m_.append((maxim, maxim_where))
    m_reverse.append((maxim_reverse, maxim_reverse_where))

ans = 0

for i in range(N - 1):
    next = m_[i][0] + m_reverse[-i - 1][0] - \
        min(m_[i][1], m_reverse[-i - 1][1])
    ans = max(next, ans)

print(max(ans, max(cum_), max(cum_reverse)))

Submission status: Accepted

Solution code:
import numpy as np
N, C = map(int, input().split())
XV = [list(map(int, input().split())) for i in range(N)]
# V_minus_X = [a[1]-a[0] for a in XV]

V_minus_X = [XV[i][1]-(XV[i][0]-XV[i-1][0])
             for i in range(1, N)]  # i==0なら見ない それ以外ならXV[i-1][0]足して上げる
V_minus_X.insert(0, XV[0][1]-XV[0][0])
cum_ = np.cumsum(V_minus_X)


V_minus_X_reverse = [XV[i][1]-(XV[i+1][0]-XV[i][0])
                     for i in range(0, N-1)]
V_minus_X_reverse.append(XV[-1][1]-(C-XV[-1][0]))
V_minus_X_reverse.reverse()
cum_reverse = np.cumsum(V_minus_X_reverse)
#print("cum", cum_)
m_ = []
m_reverse = []
maxim = 0
maxim_reverse = 0
maxim_where = 0
maxim_reverse_where = 0
# print("print")
for i in range(N-1):
    if maxim < cum_[i]:
        maxim = cum_[i]
        maxim_where = XV[i][0]
    if maxim_reverse < cum_reverse[i]:
        maxim_reverse = cum_reverse[i]
        maxim_reverse_where = C - XV[-i - 1][0]
    m_.append((maxim, maxim_where))
    m_reverse.append((maxim_reverse, maxim_reverse_where))

ans = 0
# print("print")
for i in range(N - 1):
    next = m_[i][0] + m_reverse[-i - 1][0] - \
        min(m_[i][1], m_reverse[-i - 1][1])
    # print(next)
    # print(cum_[i], m_reverse[-i - 1][0], min(XV[i][0], m_reverse[-i - 1][1]))
    ans = max(next, ans)

# print(m_reverse)
print(max(ans, max(cum_), max(cum_reverse)))

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X, V = [], []

cw1 = [0]
cw2 = [0]
ccw1 = [0]
ccw2 = [0]

s = 0
for _ in range(N):
  x, v = map(int, input().split())
  X.append(x)
  V.append(v)
  s += v
  cw1.append(max(cw1[-1], s-x))
  cw2.append(max(cw2[-1], s-2*x))

s = 0

for x,v in zip(X[::-1], V[::-1]):
  s += v
  ccw1.append(max(ccw1[-1], s-(C-x)))
  ccw2.append(max(ccw2[-1], s-(C-x)*2))

ans = 0

for a,b,c,d in zip(cw1, ccw2[::-1], cw2, ccw1[::-1]):
  ans = max(ans, a+b, c+d)

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
N, C = map(int, input().split())
X, V = [], []
for i in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)


# 右回り・左回りに進んだ場合の、効用の累積和
R_acc_val = [0] + list(accumulate(V))
L_acc_val = [0] + list(accumulate(V[::-1]))


# 右回り・左回りに進んだ場合のコストを加味した効用
R_val, L_val = [0], [0]
for i in range(1, N + 1):
    R_val.append(R_acc_val[i] - X[i - 1])
    L_val.append(L_acc_val[i] - (C - X[-i]))


# コストを加味した効用の、max累積和
R_max_val, L_max_val = list(accumulate(R_val, func=max)), list(accumulate(L_val, func=max))


ans = 0
for i in range(N + 1):
    ans = max(ans,
              R_val[i],
              R_val[i] + L_max_val[-i-1] - X[i - 1],
              L_val[i],
              L_val[i] + R_max_val[-i-1] - (C - X[-i]))

print(ans)

Submission status: Accepted

Solution code:
n,c=map(int, input().split())
lst = [list(map(int, input().split())) for i in range(n)] 
ans=0
lback=[0]
rback=[0]
l=0
r=0
for i, j in enumerate(lst,1):
  l+=j[1]
  if(lback[i-1]<l-2*j[0]):
    lback+=[l-2*j[0]]
  else:
    lback+=[lback[i-1]]
  ans=max(ans,l-j[0])
for i, j in enumerate(lst[::-1],1):
  r+=j[1]
  if(rback[i-1]<r-2*(c-j[0])):
    rback+=[r-2*(c-j[0])]
  else:
    rback+=[rback[i-1]]
  ans=max(ans,r-(c-j[0]), lback[n-i]+r-(c-j[0]) )
l=0
for i, j in enumerate(lst,1):
  l+=j[1]
  ans=max(ans,rback[n-i]+l-j[0])
print(ans)

Submission status: Accepted

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

L=[]
for i in range(N):
    x,y=map(int,input().split())
    L.append([x,y])
    
l=L[::-1]
L=[[0,0]]+L
R=[]

for i in range(N):
    R.append([C-l[i][0],l[i][1]])
R=[[0,0]]+R


#print(L)
#print(R)
TS=[0]
TW=[0]
RS=[0]
RW=[0]

for i in range(N):
    TS.append(TS[i]-L[i+1][0]+L[i][0]+L[i+1][1])
    TW.append(TW[i]-2*(L[i+1][0]-L[i][0])+L[i+1][1])
    RS.append(RS[i]-R[i+1][0]+R[i][0]+R[i+1][1])
    RW.append(RW[i]-2*(R[i+1][0]-R[i][0])+R[i+1][1])
    
MTS=[0]
MRS=[0]
for i in range(1,N+1):
    MTS.append(max(MTS[i-1],TS[i]))
    MRS.append(max(MRS[i-1],RS[i]))

ans=0
for i in range(N+1):
    if i>0 and L[i-1][0]*2>C:
        break
    else:
        if ans<TW[i] + MRS[N-i]:
            ans=TW[i] + MRS[N-i]
            
for i in range(N+1):
    if i>0 and R[i-1][0]*2>C:
        break
    else:
        if ans<RW[i]+MTS[N-i]:
            ans=RW[i]+MTS[N-i]
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
import bisect

n, c = [int(item) for item in input().split()]

xs, vs, xrs = [], [], []
for i in range(n):
  x, v = [int(item) for item in input().split()]
  xs.append(x)
  xrs.append(c-x)
  vs.append(v)
xrs = xrs[::-1]

lft_v = list(accumulate(vs))
rgt_v = list(accumulate(vs[::-1]))

lft_c = []
rgt_c = []
for i in range(n):
  lft_c.append(lft_v[i]-xs[i])
  rgt_c.append(rgt_v[i]-xrs[i])
  
lft_max = [0] * n
rgt_max = [0] * n
lm, rm = 0,0
for i in range(n):
  if lm < lft_c[i]:
    lm = lft_c[i]
  lft_max[i] = lm
  if rm < rgt_c[i]:
    rm = rgt_c[i]
  rgt_max[i] = rm

ans = 0
# No return
for i in range(n):
  ans = max(ans, lft_c[i], rgt_c[i])
  
# Includes return
for i in range(n-1):
  ans = max(ans, lft_c[i] - xs[i] + rgt_max[n-2-i])
  ans = max(ans, rgt_c[i] - xrs[i] + lft_max[n-2-i])
    
print(ans)

Submission status: Accepted

Solution code:
n, c = [int(i) for i in input().split(" ")]
x = [0] * (n + 1)
v = [0] * (n + 1)

for i in range(1, n + 1):
    x[i], v[i] = [int(i) for i in input().split(" ")]

def s(x, v):
    #print(x, v)
    sum_v = [0] * (n + 1)
    for i in range(1, n + 1):
        sum_v[i] = sum_v[i - 1] + v[i]
    v_sub = [sum_v[i] - x[i] for i in range(0, n + 1)]
    max_v = [0] * (n + 1)
    for i in range(1, n + 1):
        max_v[i] = max(max_v[i - 1], v_sub[i])
    #print(max_v)
    
    sum_r = v[n]
    max_v_sub = max_v[n]
    for i in range(1, n // 2 + 1):
        v_sub = sum_r - (c - x[n - i + 1]) * 2 + max_v[n - i]
        #print(v_sub, i)
        if v_sub > max_v_sub:
            max_v_sub = v_sub
        sum_r += v[n - i]
    return max_v_sub
        
print(max(s(x, v), s([0] + [c - xi for xi in x[1::]][::-1], [0] + v[1::][::-1])))

Submission status: Accepted

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

re_lst = []
for i in reversed(range(n)):
    re_lst.append([abs(c-lst[i][0]), lst[i][1]])

r_accum = []
s = 0
for i in range(n):
    s += lst[i][1]
    r_accum.append(s)

l_accum = []
s = 0
for i in range(n):
    s += re_lst[i][1]
    l_accum.append(s)

r_max = 0
r_max_lst = []
for i in range(n):
    r_max = max(r_max, r_accum[i] - lst[i][0])
    r_max_lst.append(r_max)
    
l_max = 0
l_max_lst = []
for i in range(n):
    l_max = max(l_max, l_accum[i] - re_lst[i][0])
    l_max_lst.append(l_max)

rd_max = 0
for i in range(n-1):
    pt = r_accum[i] - 2*lst[i][0]
    pt += l_max_lst[(n-1)-i-1]
    if pt > rd_max:
        rd_max = pt
            

ld_max = 0
for i in range(n-1):
    pt = l_accum[i] - 2*re_lst[i][0]
    pt += r_max_lst[(n-1)-i-1]
    if pt > ld_max:
        ld_max = pt

print(max(r_max, l_max, rd_max, ld_max))

Submission status: Accepted

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

x = [0]
v = [0]

acc = [0]
rev = [0]
s = 0
res = 0
for i in range(N):
    a,b = map(int,input().split())
    x.append(a)
    v.append(b)
    s += b
    acc.append(s)


#OB < OA
#O->B->A = 2*OB + OA
F =  []

for i in range(N+1):
    F.append(acc[i]-x[i])
for i in range(1,N+1):
    F[i] = max(F[i],F[i-1])
for B in range(N+1):
    if B == 0:
        A = N
        costB = 0
    else:
        A = B - 1
        costB = (s-acc[B]+v[B]-2*(C-x[B]))
    
    res = max(res,F[A] + costB)

#OA < OB
#O->A->B = 2*OA + OB
F[0] = 0
for i in range(N,0,-1):
    F[i] = (s-acc[i]+v[i]-(C-x[i]))
    F[i] = max(F[i],F[(i+1)%(N+1)])
for A in range(N+1):
    if A == N:
        B = 0
    else:
        B = A + 1
    
    res = max(res,F[B] + acc[A]-2*x[A])
print(res)

Submission status: Accepted

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

#両端に(0,0)があると考えると楽なので追加
Xi.insert(0, [0, 0])
Xi.append([C, 0])

# 真上に0があると考える。下から⇢にいくか←にいくかで区別
#右方向に進んだときの累積Caloryと累積max
total = 0
R_max = [0 for i in range(N + 2)]
for i in range(1, N + 1):
    total += Xi[i][1] - (Xi[i][0] - Xi[i - 1][0])
    R_max[i] = max(total, R_max[i - 1])

#右方向に進んだときの累積max
total = 0
L_max = [0 for i in range(N + 2)]
for i in range(N, 0, -1):
    total += Xi[i][1] - (Xi[i + 1][0] - Xi[i][0])
    L_max[i] = max(total, L_max[i + 1])

max_value = 0
for i in range(0, N + 1):
    i2 = N - i - 1
    #右方向にとにかくすすむ
    cal = R_max[i] + L_max[i + 1] - Xi[i][0]
    max_value = max(cal, max_value)

    #左にとにかくすすむ
    cal = R_max[i] + L_max[i + 1] - (C - Xi[i + 1][0])
    max_value = max(cal, max_value)
print(max_value)

Submission status: Accepted

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

    sc = 0
    v11 = [0 for i in range(N)]
    v12 = [0 for i in range(N)]
    for i in range(N):
        sc += v[i]
        v11[i] = sc - x[i]
        v12[i] = sc - x[i] * 2
    for i in range(1,N):
        v11[i] = max(v11[i], v11[i-1])
        v12[i] = max(v12[i], v12[i-1])

    sc = 0
    v21 = [0 for i in range(N)]
    v22 = [0 for i in range(N)]
    for i in range(N-1,-1,-1):
        sc += v[i]
        v21[i] = sc - (C - x[i])
        v22[i] = sc - (C - x[i]) * 2
    for i in range(N-2,-1,-1):
        v21[i] = max(v21[i], v21[i+1])
        v22[i] = max(v22[i], v22[i+1])

    ans = 0
    for i in range(N):
        ans = max(ans, v11[i])
        ans = max(ans, v21[i])
    for i in range(N-1):
        ans = max(ans, v12[i]+v21[i+1])
        ans = max(ans, v11[i]+v22[i+1])

    return ans

print(solve())

Submission status: Accepted

Solution code:
n,c = map(int,input().split())
info = [[0,0]]+[list(map(int,input().split())) for i in range(n)]+[[c,0]]
left_info = info[::-1]

right_ruiseki = [0]*(n+1)
left_ruiseki = [0]*(n+1)
ou_right_ruiseki = [0]*(n+1)
ou_left_ruiseki = [0]*(n+1)

for i in range(n):
  right_ruiseki[i+1] = right_ruiseki[i] + info[i+1][1] - info[i+1][0] + info[i][0]
  left_ruiseki[i+1] = left_ruiseki[i] + left_info[i+1][1] + left_info[i+1][0] - left_info[i][0]
  ou_right_ruiseki[i+1] = ou_right_ruiseki[i] + info[i+1][1] - 2*info[i+1][0] + 2*info[i][0]
  ou_left_ruiseki[i+1] = ou_left_ruiseki[i] + left_info[i+1][1] + 2*left_info[i+1][0] - 2*left_info[i][0]

#print(right_ruiseki,left_ruiseki,ou_right_ruiseki,ou_left_ruiseki)

for i in range(n):
  right_ruiseki[i+1]=max(right_ruiseki[i],right_ruiseki[i+1])
  left_ruiseki[i+1]=max(left_ruiseki[i],left_ruiseki[i+1])

#print(right_ruiseki,left_ruiseki,ou_right_ruiseki,ou_left_ruiseki)
ans = 0

for i in range(n+1):
  tmp1 = ou_right_ruiseki[i]+left_ruiseki[n-i]
  tmp2 = ou_left_ruiseki[i]+right_ruiseki[n-i]
  ans = max(tmp1,tmp2,ans)
print(ans)

Submission status: Accepted

Solution code:
def static_sushi(N: int, C: int, XV: list) -> int:
    Sv = [0] * (N+1)
    fr, fl = [0] * (N+1), [0] * (N+1)
    gr, gl = [0] * (N+1), [0] * (N+1)
    for i, (x, v) in enumerate(XV):
        Sv[i+1] = Sv[i] + v

        fl[i+1] = Sv[i+1] - x
        gl[i+1] = max(gl[i], fl[i+1])

        fr[i+1] = Sv[i+1] - 2*x
        gr[i+1] = max(gr[i], fr[i+1])

    max_cal = 0
    for ib, (xb, _) in enumerate(XV+[(C,0)]):
        cal_a1, cal_a2 = gr[ib], gl[ib]
        cal_b1, cal_b2 = Sv[N] - Sv[ib] - (C-xb), Sv[N] - Sv[ib] - 2*(C-xb)
        cal1, cal2 = cal_a1 + cal_b1, cal_a2 + cal_b2
        max_cal = max(max_cal, cal1, cal2)

    return max_cal


if __name__ == "__main__":
    N = 0
    N, C = map(int, input().split())
    XV = [tuple(map(int, input().split())) for _ in range(N)]
    ans = static_sushi(N, C, XV)
    print(ans)