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:
def main():
    N, C = map(int, input().split())
    sushis = [(0, 0) for _ in range(N)]
    for i in range(N):
        x, v = map(int, input().split())
        sushis[i] = (x, v)
    ls, rs = 0, 0
    left = [(0, 0) for _ in range(N+1)]
    right = [(0, 0) for _ in range(N+1)]
    for i in range(N):
        ls += sushis[i][1]
        lx = sushis[i][0]
        rs += sushis[-i-1][1]
        rx = C - sushis[-i-1][0]
        left[i+1] = (max(ls-lx, left[i][0]),
                     max(ls-lx*2, left[i][1]))
        right[i+1] = (max(rs-rx, right[i][0]),
                      max(rs-rx*2, right[i][1]))
    ans = 0
    for i in range(N+1):
        ans = max([left[i][0] + right[N-i][1],
                   left[i][1] + right[N-i][0],
                   ans])
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
sushi = [tuple(map(int, input().split())) for _ in range(n)]
sushi = [(0, 0)] + sushi
cclkmax = [0] * (n+1)
cumvalue = 0
for i in range(1, n+1):
    cumvalue += sushi[i][1]
    cclkmax[i] = max(cclkmax[i-1], cumvalue - sushi[i][0])
maxscore = cclkmax[n]
cum = 0
for i in range(n, 0, -1):
    cum += sushi[i][1]
    score = cclkmax[i-1] + cum - 2*(c - sushi[i][0])
    maxscore = max(maxscore, score)
clkmax = [0] * (n+1)
cumvalue = 0
for i in range(n, 0, -1):
    cumvalue += sushi[i][1]
    clkmax[i] = max(clkmax[(i+1)%(n+1)], cumvalue - (c - sushi[i][0]))
maxscore = max(maxscore, clkmax[1])
cum = 0
for i in range(1, n+1):
    cum += sushi[i][1]
    score = clkmax[(i+1)%(n+1)] + cum - 2*sushi[i][0]
    maxscore = max(maxscore, score)
print(maxscore)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
from itertools import accumulate
n,c=map(int,input().split())
X,V=[],[]
for _ in range(n):
    x,v=map(int, input().split())
    X.append(x)
    V.append(v)
V_ret,X_ret=V[::-1],X[::-1]
S,S_ret=list(accumulate(V)),list(accumulate(V_ret))
S[0]-=X[0]
S_ret[0]-=(c-X_ret[0])
for i in range(1,n):
    S[i]=max(S[i-1],S[i]-X[i])
    S_ret[i]=max(S_ret[i-1],S_ret[i]-(c-X_ret[i]))
ans=max(0,max(S),max(S_ret))
for i in range(n-1):
    tmp1=S[i]+S_ret[n-(i+2)]-X[i]
    tmp2=S_ret[i]+S[n-(i+2)]-(c-X_ret[i])
    ans=max(ans,tmp1,tmp2)
print(ans)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

def main():
  input = sys.stdin.readline
  N, C = map(int, input().split())
  X = []
  V = []
  for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
  Vr = V[::-1]
  Xr = X[::-1]

  F = list(accumulate(V))
  R = list(accumulate(Vr))
  F[0], R[0] = F[0] - X[0], R[0] - (C - Xr[0])
  for i in range(1, N):
    F[i] = max(F[i-1], F[i] - X[i])
    R[i] = max(R[i-1], R[i] - (C - Xr[i]))

  val = 0
  for i in range(N-1):
    v1 = F[i] + R[N-(i+2)] - X[i]
    v2 = R[i] + F[N-(i+2)] - (C - Xr[i])
    val = max(val, v1, v2)
  
  ans = max(0, val, max(F), max(R))
  print(ans)


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
x = [0]
v = [0]
for _ in range(N):
    a, b = map(int, input().split())
    x.append(a)
    v.append(b)
opt_l = [0]
acc_v = 0
for i in range(1, N + 1):
    opt_l.append(max(opt_l[-1], v[i] + acc_v - x[i]))
    acc_v += v[i]
opt_r = [0]
acc_v = 0
for i in range(1, N + 1):
    opt_r.append(max(opt_r[-1], v[-i] + acc_v - (C - x[-i])))
    acc_v += v[-i]
ans = 0
acc_v = 0
for i in range(N + 1):
    ans = max(
        ans,
        acc_v + v[i] - x[i],
        acc_v + v[i] - 2 * x[i] + opt_r[N - i]
    )
    acc_v += v[i]
acc_v = 0
for i in range(N + 1):
    ans = max(
        ans,
        acc_v + v[-i] - (C - x[-i]),
        acc_v + v[-i] - 2 * (C - x[-i]) + opt_l[N - i]
    )
    acc_v += v[-i]
print(ans)

Submission status: Accepted

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

###はじめ反時計回りに回る場合
score = [0 for i in range(n+1)] #時計回りでk番目までの寿司が食べられる時、最大摂取カロリーを記録する
start = 0
noteat = 0
for i in range(1,n+1):
    temp = 0
    if score[i-1] - (sushi[i][0] - start) + sushi[i][1] + noteat > score[i-1]: #寿司を食べた場合
        temp = score[i-1] - (sushi[i][0] - start) + sushi[i][1] + noteat
        noteat = 0
        start = sushi[i][0]
    else:
        noteat += sushi[i][1]
        temp = score[i-1]
    score[i] = temp



ans = score[n]
leftscore = 0
dist = 0
for i in range(1,n): #i個は反時計回りに食べてから時計回りに戻る
    leftscore += sushi[-i][1]
    if i == 1:
        dist += c - sushi[-i][0]
    else:
        dist += sushi[-i+1][0] - sushi[-i][0]
    if leftscore - 2*dist + score[n-i] > ans:
        ans = leftscore - 2*dist + score[n-i]


#######

#######はじめ時計回りに回る場合
reverse = [0 for i in range(n+1)]
start = c
noteat = 0
for i in range(1,n+1):
    temp = 0
    if sushi[-i][1] - (start - sushi[-i][0]) + reverse[i-1] + noteat > reverse[i-1]: #寿司を食べた場合
        temp = sushi[-i][1] - (start - sushi[-i][0]) + reverse[i-1] + noteat
        noteat = 0
        start = sushi[-i][0]
    else:
        noteat += sushi[-i][1]
        temp = reverse[i-1]
    reverse[i] = temp



ans2 = reverse[n]
rightscore = 0
dist = 0
for i in range(1,n): #i個時計回りに食べてから戻る
    rightscore += sushi[i][1]
    dist += sushi[i][0] - sushi[i-1][0]
    if rightscore - 2*dist + reverse[n-i] > ans2:
        ans2 = rightscore - 2*dist + reverse[n-i]

print(max(ans,ans2))

Submission status: Accepted

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

D = []

for i in range(N):
  D.append(list(map(int, input().split())))
  
R = [[0, 0] for i in range(N + 1)]
cnt = 0
ma = 0
rma = 0
R[0][0] = -1
for i in range(N):
  cnt += D[i][1]
  if cnt - D[i][0] > ma:
    ma = cnt - D[i][0]
  if cnt - D[i][0] * 2 > rma:
    rma = cnt - D[i][0] * 2 
  R[i + 1] = [ma, rma]

cnt = 0
Ans = R[N][0]
tmp = 0
for i in range(N - 1, -1, -1):
  cnt += D[i][1]
  tmp = C - D[i][0]
  tmp2 = cnt - tmp * 2 + R[i][0]
  tmp2 = max(tmp2, cnt - tmp + R[i][1])
  if tmp2 > Ans:
    Ans = tmp2

print(Ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X, V, D, E = [0], [0], [0], [0] * (N + 2)
for i in range(1, N + 1):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v + V[i - 1])
    D.append(max(D[i - 1], V[i] - X[i]))

for i in range(N, 0, -1):
    E[i] = max(E[i + 1], (V[N] - V[i - 1]) - (C - X[i]))

ret = max(D[N], E[1])
for i in range(1, N + 1):
    ret = max(ret, D[i] + E[i + 1] - X[i])
for i in range(N, 0, -1):
    ret = max(ret, E[i] + D[i - 1] - (C - X[i]))
print(ret)

Submission status: Accepted

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

S_cw = [0]
S_ccw = [0]
S_cw_return = [0]
S_ccw_return = [0]

for i in range(n):
    S_cw.append(S_cw[-1]+x[i][1])
    S_ccw.append(S_ccw[-1]+x[n-1-i][1])

for i in range(n):
    S_cw[i+1] -= x[i][0]
    S_ccw[i+1] -= c-x[n-1-i][0]
    S_cw_return.append(S_cw[i+1] - x[i][0])
    S_ccw_return.append(S_ccw[i+1] - (c-x[n-1-i][0]))

S_cw_return_max = [0]
S_ccw_return_max = [0]
for i in range(n):
    if S_cw_return[i+1] > S_cw_return_max[-1]:
        S_cw_return_max.append(S_cw_return[i+1])
    else:
        S_cw_return_max.append(S_cw_return_max[-1])

    if S_ccw_return[i+1] > S_ccw_return_max[-1]:
        S_ccw_return_max.append(S_ccw_return[i+1])
    else:
        S_ccw_return_max.append(S_ccw_return_max[-1])

ans = 0
for i in range(n+1):
    idx = n-i
    ans = max(ans, S_cw[i]+S_ccw_return_max[idx], S_ccw[i]+S_cw_return_max[idx])
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

def main():
    n,c = map(int,input().split())
    x1,v1 = [0],[0]
    for _ in range(n):
        a,b = map(int, input().split())
        x1.append(a)
        v1.append(b)
    x2 = [0]
    v2 = [0]
    for i in range(n,0,-1):
        x2.append(c-x1[i])
        v2.append(v1[i])

    v1, v2 = list(accumulate(v1)), list(accumulate(v2))
    g1,g2 = [v2[0]-x2[0]],[v2[0]-2*x2[0]]
    for i in range(1,n+1):
        f = v2[i] - x2[i]
        f2 = v2[i] - 2*x2[i]
        g1.append(max(g1[i-1],f))
        g2.append(max(g2[i-1],f2))
    val = max(v1[n]-x1[n] + g2[0], v1[n]-2*x1[n] + g1[0])
    for i in range(1,n+1):
        val = max(val, v1[n-i]-x1[n-i] + g2[i], v1[n-i]-2*x1[n-i] + g1[i])

    print(val)

if __name__=='__main__': main()

Submission status: Accepted

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


# 順方向,逆方向の累積和
VF,VB = [0]*(N+1),[0]*(N+1)
for i in range(N):
    VF[i+1] += VF[i]+XV[i][1]
for i in range(N):
    VB[N-i-1] += VB[N-i]+XV[N-1-i][1]
# 移動距離を減算
for i in range(N):
    VF[i+1] -= XV[i][0]
for i in range(N):
    VB[N-i-1] -= (C-XV[N-1-i][0])
# 食べに行くと損する場合を除くために単調増加に
for i in range(N):
    if VF[i+1] < VF[i]:
        VF[i+1] = VF[i]
for i in range(N):
    if VB[N-1-i] < VB[N-i]:
        VB[N-1-i] = VB[N-i]

# 順方向,逆方向で全部食べた場合で初期化
ans = 0
ans = max(ans, VF[N], VB[0])

# 反転 : 順方向→逆方向
for i in range(1,N):
    ans = max(ans, VF[i], VF[i]+VB[i]-XV[i-1][0])

# 反転 : 逆方向→順方向
for i in range(1,N):
    ans = max(ans, VB[i], VB[i]+VF[i]-(C-XV[i][0]))

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

def main():
    na = list(map(int, input().split()))
    N, C = na[0], na[1]
    x, v = [], []
    for i in range(N):
        na = list(map(int, input().split()))
        x.append(na[0])
        v.append(na[1])

    cw1 = [0] * N
    cw2 = [0] * N
    acw1 = [0] * N
    acw2 = [0] * N

    sum_v = 0
    m1 = m2 = 0
    for i in range(N):
        sum_v += v[i]
        m1 = max(m1, sum_v - x[i])
        cw1[i] = m1
        m2 = max(m2, sum_v - x[i] * 2)
        cw2[i] = m2

    sum_v = 0
    m1 = m2 = 0
    for i in range(N - 1, -1, -1):
        sum_v += v[i]
        m1 = max(m1, sum_v - (C - x[i]))
        acw1[i] = m1
        m2 = max(m2, sum_v - (C - x[i]) * 2)
        acw2[i] = m2

    m = max(cw1[N - 1], acw1[0])
    for i in range(N - 1):
        m = max(m, cw1[i] + acw2[i + 1], cw2[i] + acw1[i + 1])

    print(m)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

x = [None] * (n + 2)
v = [None] * (n + 2)
for i in range(1, n + 1):
    x[i], v[i] = map(int, input().split())
x[0] = 0
x[n + 1] = c

dp = [[0] * (n + 2) for _ in range(2)]

cal = 0
for i in range(1, n + 1):
    cal -= x[i] - x[i - 1]
    cal += v[i]
    dp[0][i] = max(dp[0][i - 1], cal)

cal = 0
for i in range(n, 0, -1):
    cal -= x[i + 1] - x[i]
    cal += v[i]
    dp[1][i] = max(dp[1][i + 1], cal)

maxcal = 0
for i in range(n + 1):
    maxcal = max(maxcal, dp[0][i] + dp[1][i + 1] - x[i])
    maxcal = max(maxcal, dp[0][i] + dp[1][i + 1] - c + x[i + 1])

print(maxcal)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
xy = []
for _ in range(N):
    xy.append(tuple(map(int, input().split())))
ans = 0
cal_sum_A = [0 for _ in range(N)]
cal_sum_A[0] = xy[0][1] - xy[0][0]
for i in range(1, N):
    cal_sum_A[i] += cal_sum_A[i - 1] + xy[i][1] - xy[i][0] + xy[i - 1][0]

cal_sum_B = [0 for _ in range(N)]
cal_sum_B[N - 1] = xy[N - 1][1] - (C - xy[N - 1][0])
for i in range(N - 2, -1, -1):
    cal_sum_B[i] += cal_sum_B[i + 1] + xy[i][1] - (C - xy[i][0]) + (C - xy[i + 1][0])

# O -> A
max_cal_A = [0 for _ in range(N)]
max_cal_A[0] = cal_sum_A[0]
for i in range(1, N):
    max_cal_A[i] = max(max_cal_A[i - 1], cal_sum_A[i])
ans = max(ans, max_cal_A[N-1])
# O -> B
max_cal_B = [0 for _ in range(N)]
max_cal_B[N-1] = max(max_cal_B[N-1], cal_sum_B[N-1])

for i in range(N-2, -1, -1):
    max_cal_B[i] = max(max_cal_B[i+1], cal_sum_B[i])
ans = max(ans, max_cal_B[0])
# O -> B -> O -> A
for i in range(1, N-1):
    cal = 0
    cal += cal_sum_B[-i]
    cal -= (C-xy[-i][0])
    cal += max_cal_A[N-i-1]
    ans = max(ans, cal)
# 0 -> A -> O -> B
for i in range(1, N):
    cal = 0
    cal += cal_sum_A[i-1]
    cal -= xy[i-1][0]
    cal += max_cal_B[-(N-i)]
    ans = max(ans, cal)
print(ans)

Submission status: Accepted

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

"""
参考：http://blog.livedoor.jp/misteer/archives/9017497.html
　　　https://www.hamayanhamayan.com/entry/2018/04/21/225805
・累積max(累積和の応用)
・先に回る方向がiより手前にmaxがあったとしても、
　そのパターンは別の周回のiで考慮されているので、
　始点まで戻るマイナス分が多くなっていても問題ない。
　どのみち先に回る方向で最終的にansに採用されるのはiまで行った時のはず。
"""

N, C = map(int, input().split())
x, v = [0], [0]
for i in range(N):
    _x, _v = map(int, input().split())
    x.append(_x)
    v.append(_v)
# 累積max
mx_r = [0] * (N+2)
cal = 0
for i in range(1, N+1):
    cal += v[i] - (x[i] - x[i-1])
    mx_r[i] = max(cal, mx_r[i-1])
mx_l = [0] * (N+2)
cal = v[N] - (C - x[N])
mx_l[N] = cal
for i in range(N-1, 0, -1):
    cal += v[i] - (x[i+1] - x[i])
    mx_l[i] = max(cal, mx_l[i+1])

ans = 0
for i in range(N+1):
    # 右回り→左回り(max(右回りのみ, 逆走もする, 今までの最大))
    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)
print(ans)

Submission status: Accepted

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

# 右回り・左回りそれぞれのvalue累積(左回りは右回り最後尾が0番目になる)
right_acc_values = list(accumulate(Values))
left_acc_values = list(accumulate(Values[::-1]))

# 右回り・左回りそれぞれのdistance(左回りは右回り最後尾が0番目になる)
right_distances = Distances
left_distances = [C - d for d in Distances[::-1]]

# 右回り・左回りに進んでいった場合に手に入るエネルギー
right_result = [v - d for d, v in zip(right_distances, right_acc_values)]
left_result = [v - d for d, v in zip(left_distances, left_acc_values)]

# 右回り・左回りに進んでいった場合に手に入るエネルギーの累積max
right_result_max = [0]
left_result_max = [0]
for i in range(N):
    right_result_max.append(max(right_result_max[-1], right_result[i]))
    left_result_max.append(max(left_result_max[-1], left_result[i]))


ans = 0
for i in range(N):
    ans = max(ans,
              right_result[i],
              left_result[i],
              right_result[i] + left_result_max[N - i - 1] - right_distances[i],
              left_result[i] + right_result_max[N - i - 1] - left_distances[i])

print(ans)

Submission status: Accepted

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

"""
参考：http://blog.livedoor.jp/misteer/archives/9017497.html
　　　https://www.hamayanhamayan.com/entry/2018/04/21/225805
・累積和
・累積max
"""

N, C = map(int, input().split())
x, v = [0], [0]
for i in range(N):
    _x, _v = map(int, input().split())
    x.append(_x)
    v.append(_v)
# 累積和
sm_r = [0] * (N+1)
for i in range(1, N+1):
    sm_r[i] = sm_r[i-1] + v[i] - (x[i] - x[i-1])
sm_l = [0] * (N+1)
sm_l[N] = v[N] - (C - x[N])
for i in range(N-1, 0, -1):
    sm_l[i] = sm_l[i+1] + v[i] - (x[i+1] - x[i])
# 累積max
mx_r = [0] * (N+2)
cal = 0
for i in range(1, N+1):
    cal += v[i] - (x[i] - x[i-1])
    mx_r[i] = max(cal, mx_r[i-1])
mx_l = [0] * (N+2)
mx_l[N] = cal = v[N] - (C - x[N])
for i in range(N-1, 0, -1):
    cal += v[i] - (x[i+1] - x[i])
    mx_l[i] = max(cal, mx_l[i+1])

ans = 0
for i in range(N+1):
    # 右回り→左回り(max(右回りのみ, 逆走もする, 今までの最大))
    ans = max(sm_r[i], sm_r[i] - x[i] + mx_l[i+1], ans)
    # 左回り→右回り
    if i != 0:
        ans = max(sm_l[i], sm_l[i] - (C - x[i]) + mx_r[i-1], ans)
print(ans)

Submission status: Accepted

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

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

if n == 1:
    print(max(sushi[0][1]-sushi[0][0], sushi[0][1]-(c-sushi[0][0]), 0))
    exit()

x = []
for i in range(n):
    x.append(sushi[i][0])

vcum = []
v = 0
for i in range(n):
    v += sushi[i][1]
    vcum.append(v)

ans = 0

# 1. 時計回りのみ（方向変換なし）
for i in range(n):
    if ans < vcum[i] - x[i]:
        ans = vcum[i] - x[i]


# 2. 反時計回りのみ（方向転換なし）
for i in range(n):
    if i == 0:
        if ans < vcum[n-1] - (c - x[0]):
            ans = vcum[n-1] - (c - x[0])
    else:
        if ans < (vcum[n - 1] - vcum[i - 1]) - (c - x[i]):
            ans = (vcum[n - 1] - vcum[i - 1]) - (c - x[i])


# 3. 時計回りのあと、方向変換して反時計回り
# right_dp[i]: 反時計回りに見て n-1~i番目 (0-index)までの寿司を取れる時(必ずしもi番目を取らなくて良い)の、カロリーの正味の最大値
right_dp = [0] * n
right_dp[n-1] = vcum[n-1] - vcum[n-2] - (c - x[n-1])
for i in reversed(range(1, n-1)):
    right_dp[i] = max(right_dp[i+1], vcum[n-1] - vcum[i-1] - (c - x[i]))

# 時計回りにi番目まで見てから折り返す(すると、反時計回りに回る時に得る正味のカロリーの最大値はright_dp[i+1]となる
for i in range(n-1):
    cal = vcum[i] - 2 * x[i] + right_dp[i+1]
    if ans < cal:
        ans = cal

# 4. 反時計回りのあと、方向変換して時計回り
# left_dp[i]: 時計回りにみてi番目(0-index)までの寿司を取れる時（必ずしもi番目を取らなくて良い）の、カロリーの正味の最大値
left_dp = [0] * n
left_dp[0] = vcum[0] - x[0]
for i in range(1, n):
    left_dp[i] = max(left_dp[i-1], vcum[i] - x[i])

# 反時計回りにi番目まで見てから折り返す (すると、時計回りに回る時に得る正味のカロリーの最大値はleft_dp[i-1]となる)
for i in range(1, n):
    cal = vcum[n-1] - vcum[i-1] - 2 * (c - x[i]) + left_dp[i-1]
    if ans < cal:
        ans = cal


print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
S = [[0, 0, 0] for i in range(N + 2)]
L = [[0, 0, 0] for i in range(N + 2)]
R = [[0, 0, 0] for i in range(N + 2)]
for i in range(N):
  x, v = map(int, input().split())
  S[i + 1] = [v, x, C - x]
  L[i + 1][0] = L[i][0] - x + S[i][1] + v
  L[i + 1][1] = L[i + 1][0] - x
  L[i + 2][2] = max(L[i + 1][2], L[i + 1][1])
for i in range(N, 0, -1):
  R[i][0] = R[i + 1][0] - S[i][2] + S[i + 1][2] + S[i][0]
  R[i][1] = R[i][0] - S[i][2]
  R[i - 1][2] = max(R[i][2], R[i][1])
ans = 0
for i in range(N + 1):
  ans = max(L[i][0] + R[i][2], L[i][2] + R[i][0], ans)
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right,bisect_left
N,C=map(int,input().split())
S=[[int(i) for i in input().split()] for i in range(N)]
Way1=[S[0][1]-S[0][0]]
p1=[]
if Way1[0]>0:
  p1.append(0)
for i in range(1,N):
  Way1.append(Way1[i-1]+S[i][1]-(S[i][0]-S[i-1][0]))
  if p1==[] and Way1[i]>0:
    p1.append(i)
  elif p1!=[]:
    if Way1[p1[-1]]<Way1[i]:
      p1.append(i)
    
Way2=[S[-1][1]-(C-S[-1][0])]
p2=[]
if Way2[0]>0:
  p2.append(N-1)
for i in range(1,N):
  Way2.append(Way2[i-1]+S[N-i-1][1]+(S[N-i-1][0]-S[N-i][0]))
  if p2==[] and Way2[i]>0:
    p2.append(N-i-1)
  elif p2!=[]:
    if Way2[N-1-p2[-1]]<Way2[i]:
      p2.append(N-i-1)
Way2.reverse()
p2.reverse()

ans=0
for i in p1:
  if i!=N-1:
    if bisect_right(p2,i+0.1)<len(p2):
      j=p2[bisect_right(p2,i+0.1)]
      ans=max(ans,Way1[i],Way1[i]-S[i][0]+Way2[j])
    else:
      ans=max(ans,Way1[i])
  else:
    ans=max(ans,Way1[i])
for j in p2:
  if j!=0:
    if bisect_left(p1,j-0.1)>0:
      i=p1[bisect_left(p1,j-0.1)-1]
      ans=max(ans,Way2[j],Way1[i]-(C-S[j][0])+Way2[j])
    else:
      ans=max(ans,Way2[j])
  else:
    ans=max(ans,Way2[j])
    
print(ans)

Submission status: Accepted

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

XV.sort()

def g():
    t_n = [(0, 0)] * (N + 1)
    ans = 0
    score = 0
    pos = 0
    for i, (x, v) in enumerate(XV, 1):
        score += v - (x - pos)
        pos = x
        ans = max(ans, score)
        t_n[i] = (pos, ans)
    
    t_r = [(0, 0)] * (N + 1)
    ans = 0
    score = 0
    pos = C
    for i, (x, v) in enumerate(reversed(XV), 1):
        score += v - (pos - x)
        pos = x
        ans = max(ans, score)
        t_r[i] = (pos, ans)
    
    ans = 0
    for i in range(1, N+1):
        ans = max(
                ans,
                t_n[i][1],
                t_r[i][1],
                t_n[i][1] -      t_n[i][0]  + t_r[N - i][1],
                t_r[i][1] - (C - t_r[i][0]) + t_n[N - i][1],
                )

    return ans

print(g())

Submission status: Accepted

Solution code:
N, C = map( int, input().split())
S = [ list( map( int, input().split())) for _ in range(N)]
X = [0]*(N+1)
RX = [0]*(N+1)
CX = [-C]*(N+1)
RCX = [-C]*(N+1)
now = 0
M = -C
m = -C
for i in range(N):
    X[i+1] = X[i] + S[i][1] - S[i][0] + now
    now = S[i][0]
    M = max(M, X[i+1])
    CX[i+1] = M
now = 0
for i in range(N):
    x, v = S[-i-1]
    x = C - x
    RX[i+1] = RX[i] + v - x + now
    now = x
    m = max(m, RX[i+1])
    RCX[i+1] = m
ans = 0
CX[0] = 0
RCX[0] = 0
RS = S[::-1]
S.insert(0,[0,0])
RS.insert(0,[C,0])

for i in range(N+1):
    ans = max( ans, X[i] + max(RCX[N-i] - S[i][0], 0))
    ans = max( ans, RX[i] + max(CX[N-i] - (C - RS[i][0]),0))
print(ans)

Submission status: Accepted

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


kyori=[0]*(n+2)
kyori[n+1]=c
calo=[0]*(n+2)
ans=[0]
tmp=0

for i in range(1,n+1):
    x,v=map(int,input().split())
    kyori[i]=x
    calo[i]=v
    tmp+=v-(x-kyori[i-1])
    ans.append(tmp)


tmp=0
for i in range(n):
    tmp+=calo[-2-i] - (kyori[-1-i]-kyori[-2-i])
    ans.append(tmp)


i=1
rmax=0
tmpmax=0
tmp=0
while(2*kyori[i]< c and i<=n):
    tmp+=calo[i]-2*(kyori[i] -kyori[i-1])
    if(tmpmax<tmp):
        tmpmax=tmp
        rmax=i
    i+=1


tmp=0
tmpmax_max=0
i=0
while(rmax < -i+n):
    tmp+=calo[-2-i] - (kyori[-1-i] - kyori[-2-i])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    i+=1
ans.append(tmpmax+ tmpmax_max)


now=tmpmax+ tmp
for i in range(rmax):
    tmpmax+= -calo[rmax-i]+2*(kyori[rmax-i] - kyori[rmax-i-1])
    tmp+=calo[rmax-i] -(kyori[rmax+1-i]-kyori[rmax-i])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    ans.append(tmpmax+tmpmax_max)




i=0
lmax=0
tmpmax=0
tmp=0
while(2*kyori[-2-i] > c and i<n):
    tmp+=calo[-2-i]-2*(kyori[-1-i] -kyori[-2-i])
    if(tmpmax<tmp):
        tmpmax=tmp
        lmax=-i+n
    i+=1
if(lmax==0):
    lmax=n+1
tmp=0
tmpmax_max=0
i=1
while(i < lmax):
    tmp+=calo[i] - (kyori[i] - kyori[i-1])
    if(tmpmax_max <tmp):
        tmpmax_max=tmp
    i+=1

ans.append(tmpmax+ tmpmax_max)



now=tmpmax+ tmp
for i in range(n-lmax):
    tmpmax+= -calo[lmax+i]+2*(kyori[lmax+i+1] - kyori[lmax+i])
    tmp+=calo[lmax+i] -(kyori[lmax+i]-kyori[lmax+i-1])
    if(tmpmax_max<tmp):
        tmpmax_max=tmp
    ans.append(tmpmax+tmpmax_max)





print(max(ans))

Submission status: Accepted

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

cumsumr = [0]
cummaxr = [0]
cummaxr2 = [0]
px = 0
for x,v in src:
    cumsumr.append(cumsumr[-1] + v-(x-px))
    cummaxr.append(max(cummaxr[-1], cumsumr[-1]))
    cummaxr2.append(max(cummaxr2[-1], cumsumr[-1]-x))
    px = x

cumsuml = [0]
cummaxl = [0]
cummaxl2 = [0]
px = C
for x,v in src[::-1]:
    cumsuml.append(cumsuml[-1] + v-(px-x))
    cummaxl.append(max(cummaxl[-1], cumsuml[-1]))
    cummaxl2.append(max(cummaxl2[-1], cumsuml[-1]-(C-x)))
    px = x

ans = max(cummaxr[-1], cummaxl[-1])
for i in range(N):
    ans = max(ans, cummaxr2[i] + cummaxl[N-i])
    ans = max(ans, cummaxl2[i] + cummaxr[N-i])
print(ans)

Submission status: Accepted

Solution code:
def run(N, C, XV):
    '''
    左回りでxまで食べた後に、右回りのyまで食べると考える
    yは、xの次の皿まで食べることが可能なので、事前に最大
    となる食べ方を計算しておく
    逆回りも同様に計算して最大のものをとる
    '''
    # ある位置まで食べた時のカロリー
    cal_l = [0]
    cal_r = [0]
    # ある位置までの中で最大のカロリーとなるカロリー
    cal_max_l = [0]
    cal_max_r = [0]
    cal = 0
    for i in range(N):
        cal += XV[i][1]
        cal_l.append(cal-XV[i][0]*2)
        cal_max = cal_max_l[i]
        if cal_max < cal-XV[i][0]:
            cal_max = cal-XV[i][0]
        cal_max_l.append(cal_max)
    cal = 0
    for i in range(N):
        cal += XV[N-i-1][1]
        cal_r.append(cal-(C-XV[N-i-1][0])*2)
        cal_max = cal_max_r[i]
        if cal_max < cal-C+XV[N-i-1][0]:
            cal_max = cal-C+XV[N-i-1][0]
        cal_max_r.append(cal_max)

    ret = 0
    # 左回りが先
    for i in range(len(cal_l)):
        ret = max(ret, cal_l[i]+cal_max_r[N-i])
    # 右回りが先
    for i in range(len(cal_r)):
        ret = max(ret, cal_r[i]+cal_max_l[N-i])
    return ret


def main():
    N, C = map(int, input().split())
    XV = []
    for i in range(N):
        XV.append(list(map(int, input().split())))
    print(run(N, C, XV))


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

RIGHTSUM=[0]

for x,v in XV:
    RIGHTSUM.append(RIGHTSUM[-1]+v)

LEFTSUM=[0]

for x,v in XV[::-1]:
    LEFTSUM.append(LEFTSUM[-1]+v)

RIGHT=[]

for i in range(N):
    RIGHT.append(RIGHTSUM[i+1]-XV[i][0])

LEFT=[]

for i in range(N):
    LEFT.append(LEFTSUM[i+1]-(C-XV[-i-1][0]))


RIGHTMAX=[RIGHT[0]]

for i in range(1,N):
    RIGHTMAX.append(max(RIGHTMAX[i-1],RIGHT[i]))

LEFTMAX=[LEFT[0]]

for i in range(1,N):
    LEFTMAX.append(max(LEFTMAX[i-1],LEFT[i]))

ANS=max(max(RIGHT),max(LEFT),0)
#print(ANS)
for i in range(N-1):
    #print(i,RIGHTSUM[i+1]-XV[i][0]*2+LEFTMAX[N-i-2],LEFTSUM[i+1]-(C-XV[-i-1][0])*2+RIGHTMAX[N-i-2])
    if ANS<(RIGHTSUM[i+1]-XV[i][0]*2)+LEFTMAX[N-i-2]:
        ANS=RIGHTSUM[i+1]-XV[i][0]*2+LEFTMAX[N-i-2]
    if ANS<LEFTSUM[i+1]-(C-XV[-i-1][0])*2+RIGHTMAX[N-i-2]:
        ANS=LEFTSUM[i+1]-(C-XV[-i-1][0])*2+RIGHTMAX[N-i-2]

print(ANS)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10**5)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from itertools import accumulate

n,c = li()
x_cw = []
v_cw = []
x_ccw = []
for _ in range(n):
    x,v = li()
    x_cw.append(x)
    v_cw.append(v)
    x_ccw.append(c-x)
    
x_ccw = [0] + sorted(x_ccw)
v_ccw = [0] + v_cw[::-1]
x_cw = [0] + x_cw
v_cw = [0] + v_cw
    
for i in range(1,n+1):
    v_cw[i] += (v_cw[i-1] - (x_cw[i]-x_cw[i-1]))
    v_ccw[i] += (v_ccw[i-1] - (x_ccw[i]-x_ccw[i-1]))
    
    
max_cw = [0]
max_ccw = [0]
mx_cw = [0]
mx_ccw = [0]
for i in range(1,n+1):
    max_cw.append(max(max_cw[-1], v_cw[i]))
    max_ccw.append(max(max_ccw[-1], v_ccw[i]))
    
    if max_cw[-1] != max_cw[-2]:
        mx_cw.append(x_cw[i])
    else:
        mx_cw.append(mx_cw[-1])

    if max_ccw[-1] != max_ccw[-2]:
        mx_ccw.append(x_ccw[i])
    else:
        mx_ccw.append(mx_ccw[-1])

ans = 0
for i in range(n+1):
    temp = max_cw[i] + max_ccw[n-i] - min(mx_cw[i], mx_ccw[n-i])
    ans = max(temp, ans)

        
print(ans)

Submission status: Accepted

Solution code:
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)

st1 = [0] * N
st2 = [0] * N
st1[0] = max(0, V[0] - X[0])
st2[0] = max(0, V[0] - 2 * X[0])
cur1, cur2 = V[0] - X[0], V[0] - 2 * X[0]
pre = X[0]
for i in range(1, N):
    cur1 += V[i] - (X[i] - pre)
    cur2 += V[i] - (X[i] - pre) * 2
    st1[i] = max(st1[i - 1], cur1)
    st2[i] = max(st2[i - 1], cur2)
    pre = X[i]

ba1 = [0] * N
ba2 = [0] * N
ba1[-1] = max(0, V[-1] - (C - X[-1]))
ba2[-1] = max(0, V[-1] - 2 * (C - X[-1]))
cur1, cur2 = V[-1] - (C - X[-1]), V[-1] - 2 * (C - X[-1])
pre = X[-1]
for i in range(N - 2, -1, -1):
    cur1 += V[i] - (pre - X[i])
    cur2 += V[i] - (pre - X[i]) * 2
    ba1[i] = max(ba1[i + 1], cur1)
    ba2[i] = max(ba2[i + 1], cur2)
    pre = X[i]

num = 0
num = max(st1[N - 1], ba1[0])
for i in range(N - 1):
    num = max(num, st1[i] + ba2[i + 1])

for i in range(1, N - 1):
    num = max(num, ba1[i] + st2[i - 1])

print(num)

Submission status: Accepted

Solution code:
from itertools import accumulate
n, c = list(map(int, input().split()))
xv = [list(map(int, input().split())) for _ in range(n)]

v_cum = [0]*(n+1)
for i in range(n):
    v_cum[i+1] = v_cum[i] + xv[i][1]

for_cal = [0] + [v_cum[i+1] - xv[i][0] for i in range(n)]
fb_cal = [0] + [v_cum[i+1] - 2*xv[i][0] for i in range(n)]

for_cum = [x for x in accumulate(for_cal, max)]
fb_cum = [x for x in accumulate(fb_cal, max)]

ans = 0
for i in range(n+1):
    # OA path
    j = n if i == 0 else i-1

    # OB path
    ob_x = 0 if i == 0 else c - xv[i-1][0]
    ob_v = v_cum[n] - v_cum[i-1]

    # for-back root
    ans = max(ans, fb_cum[j]+ob_v-ob_x)
    # back-for path
    ans = max(ans, for_cum[j]+ob_v-2*ob_x)

print(ans)