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:
n, c = map(int, input().split())
XV = [list(map(int, input().split())) for _ in range(n)]
X, V = zip(*XV)
dp_I_r = [0]*n
dp_U_r = [0]*n
dp_I_l = [0]*n
dp_U_l = [0]*n
dp_I_r[0] = V[0] - X[0]
dp_U_r[0] = V[0] - 2*X[0]
dp_I_l[n-1] = V[n-1] - (c - X[n-1])
dp_U_l[n-1] = V[n-1] - 2*(c - X[n-1])
for i in range(n-1):
  dp_I_r[i+1] = dp_I_r[i] + V[i+1] - (X[i+1] - X[i])
  dp_U_r[i+1] = dp_U_r[i] + V[i+1] - 2*(X[i+1] - X[i])
  dp_I_l[n-2-i] = dp_I_l[n-1-i] + V[n-2-i] - (X[n-1-i] - X[n-2-i])
  dp_U_l[n-2-i] = dp_U_l[n-1-i] + V[n-2-i] - 2*(X[n-1-i] - X[n-2-i])
for i in range(n-1):
  dp_I_r[i+1] = max(dp_I_r[i], dp_I_r[i+1])
  dp_U_r[i+1] = max(dp_U_r[i], dp_U_r[i+1])
  dp_I_l[n-2-i] = max(dp_I_l[n-1-i], dp_I_l[n-2-i])
  dp_U_l[n-2-i] = max(dp_U_l[n-1-i], dp_U_l[n-2-i])
ans = 0
for i in range(n):
  ans = max(ans, dp_I_r[i])
  ans = max(ans, dp_I_l[i])
  if i < n-1:
    ans = max(ans, dp_U_r[i] + dp_I_l[i+1])
  if i > 0:
    ans = max(ans, dp_U_l[i] + dp_I_r[i-1])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

F=[0]
rF=[0]
s=0
for i in range(n):
    s+=S[i][1]
    F.append(max(s-S[i][0],F[-1]))
    rF.append(max(s-2*S[i][0],rF[-1]))

S=list(reversed(S))
R=[0]
rR=[0]
s=0
for i in range(n):
    s+=S[i][1]
    R.append(max(s+S[i][0]-c,R[-1]))
    rR.append(max(s+2*(S[i][0]-c),rR[-1]))
    
R=list(reversed(R))
rR=list(reversed(rR))

ans=0
for i in range(n+1):
    ans=max(F[i]+rR[i],ans)
    ans=max(R[i]+rF[i],ans)
    
print(ans)

Submission status: Accepted

Solution code:




N,C = map(int, input().split())

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


# 時計回りと反時計回りで得られるカロリーの累積和を取っておく
accum_clockwise = [None] * N
accum_clockwise[0] = xv[0]
tmp = xv[0][1]
for i in range(1,N):
    tmp += xv[i][1]
    accum_clockwise[i] = (xv[i][0], tmp)

accum_anticlockwise = [None] * N
accum_anticlockwise[0] = (C - xv[-1][0], xv[-1][1])
tmp = xv[-1][1]
for i in range(1, N):
    tmp += xv[N-1-i][1]
    accum_anticlockwise[i] = (C - xv[N-1-i][0], tmp)


# 時計回りと反時計回りについて、i個目まで食べに行って初期値に戻ってくるときに得られる、最高カロリーを記録しておく
# 反時計回りにx個まで食べに行ったとき（引き返さない方）、時計回りにはN-x個まで食べられるので、N-x番目のいずれかまで食べに行って戻った時の最高カロリーを事前に求めておいて、
# 反時計回りにそれぞれの寿司まで食べに行った時の点と合わせる（O(N^2)から前処理でO(N)に分解）
max_clockwise = [0] * (N+1)
for i in range(N):
    max_clockwise[i+1] = max(max_clockwise[i], accum_clockwise[i][1] - accum_clockwise[i][0] * 2)


max_anticlockwise = [0] * (N+1)
for i in range(N):
    max_anticlockwise[i+1] = max(max_anticlockwise[i], accum_anticlockwise[i][1] - accum_anticlockwise[i][0] * 2)



ans_clockwise = 0
for i in range(N):
    ans_clockwise = max(ans_clockwise, accum_clockwise[i][1] - accum_clockwise[i][0] + max_anticlockwise[N-1-i])

ans_anticlockwise = 0
for i in range(N):
    ans_anticlockwise = max(ans_anticlockwise, accum_anticlockwise[i][1] - accum_anticlockwise[i][0] + max_clockwise[N-1-i])

print(max(ans_clockwise, ans_anticlockwise))

Submission status: Accepted

Solution code:




N,C = map(int, input().split())

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

accum_clockwise = [None] * N
accum_clockwise[0] = xv[0]
tmp = xv[0][1]
for i in range(1,N):
    tmp += xv[i][1]
    accum_clockwise[i] = (xv[i][0], tmp)


accum_anticlockwise = [None] * N
accum_anticlockwise[0] = (C - xv[-1][0], xv[-1][1])
tmp = xv[-1][1]
for i in range(1, N):
    tmp += xv[N-1-i][1]
    accum_anticlockwise[i] = (C - xv[N-1-i][0], tmp)


max_clockwise = [0] * (N+1)
for i in range(N):
    max_clockwise[i+1] = max(max_clockwise[i], accum_clockwise[i][1] - accum_clockwise[i][0] * 2)


max_anticlockwise = [0] * (N+1)
for i in range(N):
    max_anticlockwise[i+1] = max(max_anticlockwise[i], accum_anticlockwise[i][1] - accum_anticlockwise[i][0] * 2)


ans_clockwise = 0
for i in range(N):
    ans_clockwise = max(ans_clockwise, accum_clockwise[i][1] - accum_clockwise[i][0] + max_anticlockwise[N-1-i])

ans_anticlockwise = 0
for i in range(N):
    ans_anticlockwise = max(ans_anticlockwise, accum_anticlockwise[i][1] - accum_anticlockwise[i][0] + max_clockwise[N-1-i])

print(max(ans_clockwise, ans_anticlockwise))

Submission status: Accepted

Solution code:
import itertools
N, C = map(int, input().split())
X = []
V = []
for n in range(N):
    x, v = map(int,input().split())
    X.append(x)
    V.append(v)
Xr = X[::-1]
Vr = V[::-1]
Xl = [0] + X
Vl = [0] + V
Xr = [0] + [C-x for x in Xr] # 逆に回るのでCから引く
Vr = [0] + Vr

Vl = list(itertools.accumulate(Vl)) # xは累積した値なので、vも累積和に統一
Vr = list(itertools.accumulate(Vr))

def update_mx(ls):
    mx = 0
    for i in range(len(ls)):
        mx = max(mx, ls[i])
        ls[i] = mx
    return ls

def create(V,X,k):
    ls = []
    for n in range(N+1):
        ls.append(V[n]-k*X[n]) # 往復する場合はk=2
    return update_mx(ls)

L = create(Vl,Xl,1) # 最良の値[左端として許容される位置]（片道）
Lt = create(Vl,Xl,2) # 最良の値[左端として許容される位置]（往復）
R = create(Vr,Xr,1)
Rt = create(Vr,Xr,2)

ans = 0
for n in range(N+1):
    #print (n,N-n)
    ans = max(ans, Lt[n] + R[N-n])
    ans = max(ans, Rt[n] + L[N-n])
print (ans)

Submission status: Accepted

Solution code:
n,c = map(int,input().split())
a = [(0,0)]
for _ in range(n):
  x,v = map(int,input().split())
  a += [(x,v)]
a += [(0,0)]
max_r, max_l = [0], [0]
s = 0
for i in range(1, n+1):
  s += a[i][1]
  max_r += [max(max_r[i-1], s-a[i][0])]
max_r += [0]
s = 0
for i in range(1, n+1):
  s += a[-i-1][1]
  max_l += [max(max_l[i-1], s-c+a[-i-1][0])]
max_l += [0]
max_l.reverse()
ans = 0
for i in range(1, n+1):
  ans = max(ans, max_r[i], max_l[i], max_r[i]+max_l[i+1]-a[i][0], max_r[i-1]+max_l[i]-c+a[i][0])
print(ans)

Submission status: Accepted

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

xvl = []
for _ in range(n):
    x,v = map(int,input().split())
    xvl.append((x,v))

get_l = []
sum_v = 0
for x, v in xvl:
    sum_v += v
    get_l.append(sum_v - x)

import itertools
get_l_ac = list(itertools.accumulate(get_l, max))
get_r = []
sum_v = 0
for x, v in xvl[::-1]:
    sum_v += v
    get_r.append(sum_v - (c - x))


ans = 0
x = 0
for i in range(n):
    tmp = 0
    if i > 0:
        x = c - xvl[-i][0]
        tmp += get_r[i-1]
    ans = max(tmp, tmp - x + get_l_ac[n - i - 1], ans)

get_r_ac = list(itertools.accumulate(get_r, max))
x = 0
for i in range(n):
    tmp = 0
    if i > 0:
        x = xvl[i-1][0]
        tmp += get_l[i-1]
    ans = max(tmp, tmp - x + get_r_ac[n - i - 1], ans)

print(ans)

Submission status: Accepted

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

Y = [[C - i, v] for i, v in X[::-1]]

# Cumsum
x_cs = [[0, 0] for _ in range(N + 1)]
y_cs = [[0, 0] for _ in range(N + 1)]
for i in range(N):
    x_cs[i + 1][0] = X[i][0]
    x_cs[i + 1][1] = x_cs[i][1] + X[i][1]

    y_cs[i + 1][0] = Y[i][0]
    y_cs[i + 1][1] = y_cs[i][1] + Y[i][1]

fx = [v - x for x, v in x_cs]
fy = [v - x for x, v in y_cs]

gx = [0] * (N + 1)
gy = [0] * (N + 1)
for i in range(N):
    gx[i + 1] = max(gx[i], fx[i + 1])
    gy[i + 1] = max(gy[i], fy[i + 1])

X = [[0, 0]] + X
Y = [[0, 0]] + Y
ans = max(gx + gy)
for i in range(N + 1):
    ans = max(ans, gx[i] + gy[N - i] - X[i][0],
              gx[N - i] + gy[i] - Y[i][0])

print(ans)

Submission status: Accepted

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

# 時計回りに寿司を食べていく
eat = 0
walk = 0
now = 0
clockwise = [(0, 0)]
for x, v in XV:
    eat += v
    walk += x-now
    clockwise.append((eat, walk))
    now = x

# 半時計周りに食べていく
eat = 0
walk = 0
now = C
counter_clockwise = [(0, 0)]
for x, v in XV[::-1]:
    eat += v
    walk += now - x
    counter_clockwise.append((eat, walk))
    now = x

# 前処理
best_left_go = [e - w for e, w in counter_clockwise]
best_left_go = list(accumulate(best_left_go, func=max))
best_left_back = [e - 2 * w for e, w in counter_clockwise]
best_left_back = list(accumulate(best_left_back, func=max))
best_right_go = [e - w for e, w in clockwise]
best_right_go = list(accumulate(best_right_go, func=max))
best_right_back = [e - 2 * w for e, w in clockwise]
best_right_back = list(accumulate(best_right_back, func=max))

# 時計回りして戻って反時計回りに食べる
ans = 0
for i, rb in enumerate(best_right_back):
    calorie = rb + best_left_go[N - i]
    ans = max(ans, calorie)
# 反時計回りして戻って時計回りに食べる
for i, lb in enumerate(best_left_back):
    calorie = lb + best_right_go[N - i]
    ans = max(ans, calorie)

print(ans)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
XV = [tuple(map(int, input().split())) for i in range(n)]
X = [x for x, v in XV]
V = [v for x, v in XV]
S = [0]
for i in range(n):
    S.append(S[-1]+V[i])
# 右回りから行く場合
A = [0]
for i in range(1, n+1):
    A.append(max(A[-1], S[i]-2*X[i-1]))
B = []
for i in range(n):
    B.append(S[n]-S[i]-(c-X[i]))
B.append(0)
ans0 = max([A[i]+B[i] for i in range(n+1)])
# 左回りから行く場合
A = [0]
for i in range(1, n+1):
    A.append(max(A[-1], S[i]-X[i-1]))
B = []
for i in range(n):
    B.append(S[n]-S[i]-2*(c-X[i]))
B.append(0)
ans1 = max([A[i]+B[i] for i in range(n+1)])
print(max(ans0, ans1))

Submission status: Accepted

Solution code:
def main():
    from collections import namedtuple
    import sys
    input = sys.stdin.readline

    Sushi = namedtuple('Sushi', 'x cal')

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

    a = []
    for _ in range(n):
        x, v = map(int, input().split())
        a.append(Sushi(x=x, cal=v))
    # x昇順ソート済

    clock = [0] * (n + 1)  # 注目する寿司以前で離脱する最大摂取カロリー
    clock_to_0 = [0] * (n + 1)  # 時計回り->初期位置の最大摂取カロリー
    ma = 0  # 注目する寿司以前で離脱する最大摂取カロリー
    ma0 = 0  # 時計回り->初期位置の最大摂取カロリー
    curr = 0  # 現在のカロリー(移動によるカロリー消費を無視)
    for i, s in enumerate(a, start=1):
        curr += s.cal
        ma = max(ma, curr - s.x)
        ma0 = max(ma0, curr - s.x * 2)
        clock[i] = ma
        clock_to_0[i] = ma0

    anti = [0] * (n + 1)  # 注目する寿司以前で離脱する最大摂取カロリー
    anti_to_0 = [0] * (n + 1)  # 反時計回り->初期位置の最大摂取カロリー
    ma = 0  # 注目する寿司以前で離脱する最大摂取カロリー
    ma0 = 0  # 時計回り->初期位置の最大摂取カロリー
    curr = 0  # 現在のカロリー(移動によるカロリー消費を無視)
    for i, s in zip(range(n, -1, -1), reversed(a)):
        curr += s.cal
        ma = max(ma, curr - (c - s.x))
        ma0 = max(ma0, curr - (c - s.x) * 2)
        anti[i] = ma
        anti_to_0[i] = ma0

    ans = 0
    for exit_pos in range(1, n + 1):
        ans = max(
            ans,
            clock_to_0[exit_pos - 1] + anti[exit_pos],
            anti_to_0[(exit_pos + 1) % (n + 1)] + clock[exit_pos]
        )

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from collections import namedtuple
    import sys
    input = sys.stdin.readline

    Sushi = namedtuple('Sushi', 'x cal')

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

    a = []
    for _ in range(n):
        x, v = map(int, input().split())
        a.append(Sushi(x=x, cal=v))
    # x昇順ソート済

    clock = [0] * (n + 1)  # 注目する寿司以前で離脱する最大摂取カロリー
    clock_to_0 = [0] * (n + 1)  # 時計回り->初期位置
    ma = 0  # 注目する寿司以前で離脱する最大摂取カロリー
    curr = 0  # 現在のカロリー(移動によるカロリー消費を無視)
    for i, s in enumerate(a, start=1):
        curr += s.cal
        ma = max(ma, curr - s.x)
        clock[i] = ma
        clock_to_0[i] = curr - s.x * 2

    anti = [0] * (n + 1)  # 注目する寿司以前で離脱する最大摂取カロリー
    anti_to_0 = [0] * (n + 1)  # 反時計回り->初期位置
    ma = 0  # 注目する寿司以前で離脱する最大摂取カロリー
    curr = 0  # 現在のカロリー(移動によるカロリー消費を無視)
    for i, s in zip(range(n, -1, -1), reversed(a)):
        curr += s.cal
        ma = max(ma, curr - (c - s.x))
        anti[i] = ma
        anti_to_0[i] = curr - (c - s.x) * 2

    ans = 0
    for exit_pos in range(1, n + 1):
        ans = max(
            ans,
            clock_to_0[exit_pos - 1] + anti[exit_pos],
            anti_to_0[(exit_pos + 1) % (n + 1)] + clock[exit_pos]
        )

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

xv = [tuple(map(int, input().split())) for i in range(N)]
xv2 = [(C - x, v)for x, v in xv[::-1]]


L = [0]*N
ans = 0
for i, X in enumerate(xv):
    x, v = X
    L[i] = L[i-1] + v
R = [0]*N
for i in range(N):
    L[i] -= xv[i][0]
for i, X in enumerate(xv2):
    x, v = X
    R[i] = R[i-1] + v
for i in range(N):
    R[i] -= xv2[i][0]

LL = [0]*(N+1)
RR = [0]*(N+1)
for i in range(N):
    LL[i+1] = max(LL[i], L[i])
    RR[i+1] = max(RR[i], R[i])

ans = 0
ans = max(ans, LL[-1])
ans = max(ans, RR[-1])
for i in range(N):
    ans = max(ans, LL[N - 1 - i] + R[i] - xv2[i][0])
    ans = max(ans, RR[N - 1 - i] + L[i] - xv[i][0])
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/abc095/tasks/arc096_b
N, C = read_ints()
X, V = read_col(N)
# 遠くの寿司も見ないとダメそう(vがバカでかい可能性がある)
# とりあえず右スタートを前提に考える。歩く距離の最小は2パターン。
# 1. 右に進んで食べるだけ
# 2. 途中まで右に進んで途中で左に戻る


def ret_ans1(X, V):  # 右スタート想定
    sum_v = 0
    ans = -1
    for x, v in zip(X, V):
        sum_v += v
        ans = max(ans, sum_v - x)
    return ans


def ret_ans2(X, V):  # ただし右スタートを想定
    Z = []
    sum_v = 0
    for x, v in zip(X, V):
        sum_v += v
        Z.append(sum_v - 2 * x)

    Y = []
    sum_v = 0
    for x, v in reversed(list(zip(X, V))):
        sum_v += v
        Y.append(sum_v - (C - x))
    Y = list(reversed(Y))

    # optimize
    ans = max_sum(Z, Y)
    return ans


def max_sum(X, Y):
    # X_i + Y_j (i<j)を最大化する O(n)
    X_accum = [-10**15]
    for x in X:
        X_accum.append(max(x, X_accum[-1]))

    del X_accum[0]

    Y_accum = [-10**15]
    for y in reversed(Y):
        Y_accum.append(max(y, Y_accum[-1]))
    Y_accum = list(reversed(Y_accum))
    del Y_accum[-1]
    ret = 0
    for i in range(len(X) - 1):
        ret = max(ret, X_accum[i] + Y_accum[i + 1])
    return ret


ans = 0
ans = max(ans, ret_ans1(X, V))
ans = max(ans, ret_ans2(X, V))

# 左周りにスタートする
V = list(reversed(V))
X_r = []
for x in reversed(X):
    X_r.append(C - x)

ans = max(ans, ret_ans1(X_r, V))
ans = max(ans, ret_ans2(X_r, V))
print(ans)

Submission status: Accepted

Solution code:
N,C = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
V = [0 for _ in range(N)]
Vm = [0 for _ in range(N)]
V[0] = A[0][1]-A[0][0]
Vm[0] = V[0]
for i in range(1,N):
    V[i] = V[i-1]+A[i][1]-(A[i][0]-A[i-1][0])
    Vm[i] = max(V[i],Vm[i-1])
U = [0 for _ in range(N)]
Um = [0 for _ in range(N)]
U[0] = A[-1][1]-(C-A[-1][0])
Um[0] = U[0]
for j in range(2,N+1):
    U[j-1] = U[j-2]+A[-j][1]-(A[-(j-1)][0]-A[-j][0])
    Um[j-1] = max(U[j-1],Um[j-2])
ans = V[N-1]
for i in range(N-1):
    ans = max(ans,V[i],V[i]-A[i][0]+Um[N-2-i])
ans = max(ans,U[N-1])
for j in range(N-1):
    ans = max(ans,U[j],U[j]-(C-A[-(j+1)][0])+Vm[N-2-j])
print(max(ans,0))

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
x=[]
v=[]
rightvalue=[]
temp=0
for i in range(n):
  xi,vi=map(int,input().split())
  x.append(xi)
  v.append(vi)
  temp+=vi
  rightvalue.append(temp-xi)
rightmaxdouble=[]
currentmax=0
for i in range(n):
  if currentmax<rightvalue[i]-x[i]:
    currentmax=rightvalue[i]-x[i]
  rightmaxdouble.append(currentmax)
leftvalue=[]
temp=0
for i in range(n):
  temp+=v[n-1-i]
  leftvalue.append(temp-(c-x[n-1-i]))
leftmaxdouble=[]
currentmax=0
for i in range(n):
  if currentmax<leftvalue[i]-(c-x[n-1-i]):
    currentmax=leftvalue[i]-(c-x[n-1-i])
  leftmaxdouble.append(currentmax)
ans=0
for i in range(n):
  if n-i>=2:
    if rightvalue[i]+leftmaxdouble[n-i-2]>ans:
      ans=rightvalue[i]+leftmaxdouble[n-i-2]
  else:
    if rightvalue[i]>ans:
      ans=rightvalue[i]
for i in range(n):
  if n-i>=2:
    if leftvalue[i]+rightmaxdouble[n-i-2]>ans:
      ans=leftvalue[i]+rightmaxdouble[n-i-2]
  else:
    if leftvalue[i]>ans:
      ans=leftvalue[i]
print(ans)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,C=MI()
    XV=LLIN(N)
    DP1 = [0]*(N+1)
    DP2 = [0]*(N+1)
    before = 0
    for i,(x,v) in enumerate(XV):
        DP1[i+1]=DP1[i]+v-(abs(x-before))
        before = x
    before = C
    for i,(x,v) in enumerate(XV[::-1]):
        DP2[i+1]=DP2[i]+v-(abs(x-before))
        before = x
    ans = max(max(DP1),max(DP2))
    now = 0

    DP1_ = [d-XV[i][0] for i,d in enumerate(DP1[1:])]
    DP2_ = [d-(C-XV[~i][0]) for i,d in enumerate(DP2[1:])]
    for i in range(N-1):
        if(DP2_[i+1]<DP2_[i]):
            DP2_[i+1] = DP2_[i]
        if(DP1_[i+1]<DP1_[i]):
            DP1_[i+1] = DP1_[i]
    now1 = 0
    now2 = 0
    for i in range(N):
        idx = N-1-i
        # print(DP1[i],DP2_[idx])
        # print(DP2[i],DP1_[idx])
        ans = max(ans,DP1[i]+DP2_[idx])
        ans = max(ans,DP2[idx]+DP1_[i])
        # print(ans)
    # print(DP1)
    # print(DP2)
    # print(DP1_)
    # print(DP2_)
    print(ans)

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)]
XV.sort()

L = [0] * (N + 1)
S = 0
for i, (x, v) in enumerate(XV, start=1):
    S += v
    L[i] = max(L[i - 1], S - x)

R = [0] * (N + 1)
S = 0
for i, (x, v) in enumerate(XV[::-1], start=1):
    S += v
    R[i] = max(R[i - 1], S - (C - x))

ans = max(max(L), max(R))

S = 0
for i, (x, v) in enumerate(XV, start=1):
    S += v
    ans = max(ans, S - 2 * x + R[N - i])

S = 0
for i, (x, v) in enumerate(XV[::-1], start=1):
    S += v
    ans = max(ans, S - (C - x) * 2 + L[N - i])

print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N,C=map(int,input().split())

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

sushi_2=list(map(lambda x:[x[0]+C, x[1]] , sushi))

sushi+=sushi_2

cal=[[0,0] for i in range(2*N)]

pre_x=C
for i in range(N, 2*N):
    x, v = sushi[i][0], sushi[i][1]
    cal[i][0], cal[i][1] = v-(x-pre_x), v-2*(x-pre_x)
    pre_x=x


pre_x=C
for i in range(N)[::-1]:
    x, v = sushi[i][0], sushi[i][1]
    cal[i][0], cal[i][1] = v-(pre_x-x), v-2*(pre_x-x)
    pre_x=x

left=[[0,0] for i in range(N)]
right=[[0,0] for i in range(N)]

temp_0,temp_1=cal[N][0],cal[N][1]
right[0][0], right[0][1] = max(0,temp_0), max(0,temp_1)
for i in range(N+1,2*N):
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    right[i-N][0], right[i-N][1] = max(right[i-N-1][0],temp_0), max(right[i-N-1][1],temp_1)

temp_0,temp_1=cal[N][0],cal[N][1]
right[0][0], right[0][1] = max(0,temp_0), max(0,temp_1)
for i in range(N+1,2*N):
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    right[i-N][0], right[i-N][1] = max(right[i-N-1][0],temp_0), max(right[i-N-1][1],temp_1)

temp_0, temp_1=cal[N-1][0], cal[N-1][1]
left[-1][0], left[-1][1] = max(0,temp_0), max(0,temp_1)
for i in range(N-1)[::-1]:
    temp_0+=cal[i][0]
    temp_1+=cal[i][1]
    left[i-N][0], left[i-N][1] = max(left[i-N+1][0],temp_0), max(left[i-N+1][1],temp_1)

"""
print(sushi)
print(cal)
print(right)
print(left)
"""

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

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


print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

n,c = map(int, input().split())
xv = [[0,0]]+[list(map(int, input().split())) for i in range(n)]
xv_rev = [[0,0]]+[[c-x,v] for x,v in xv][:0:-1]
cumsum = [i-x for i,(x,v) in zip(list(accumulate([v for x,v in xv])),xv)]
cumsum_rev = [i-x for i,(x,v) in zip(list(accumulate([v for x,v in xv_rev])),xv_rev)]
xv_max = [0]
xv_rev_max = [0]
now_v = 0
for k,(x,v) in enumerate(xv[:-1],1):
  xv_max.append(max(xv_max[-1], cumsum[k]))
for k,(x,v) in enumerate(xv_rev[:-1],1):
  xv_rev_max.append(max(xv_rev_max[-1], cumsum_rev[k]))
ans = 0
for i,j,(x,v) in zip(xv_max,cumsum_rev[::-1],xv_rev[::-1]):
  ans = max(ans,i+j-x)
for i,j,(x,v) in zip(xv_rev_max,cumsum[::-1],xv[::-1]):
  ans = max(ans,i+j-x)
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc095/tasks/arc096_b
# 16:55-17:08 chudan
# 12:45-13:08 done


def main():
    N, C = map(int, input().split())
    x = [None] * N
    v = [None] * N
    for i in range(N):
        x[i], v[i] = map(int, input().split())

    cal_clock = [None] * N
    cal = -x[0] + v[0]
    cal_clock[0] = cal if cal > 0 else 0
    for i in range(1, N):
        cal -= x[i] - x[i-1]
        cal += v[i]
        cal_clock[i] = cal if cal > cal_clock[i-1] else cal_clock[i-1]

    cal_anti = [None] * N
    cal = -(C-x[-1]) + v[-1]
    cal_anti[0] = cal if cal > 0 else 0
    for i in range(1, N):
        cal -= x[N-i] - x[N-1-i]
        cal += v[N-1-i]
        cal_anti[i] = cal if cal > cal_anti[i-1] else cal_anti[i-1]

    ans = max(cal_clock[-1], cal_anti[-1])  # 引き返さない場合
    for k in range(N-1):  # 途中で引き返す場合
        cand_1 = cal_clock[k] - x[k] + cal_anti[N-2-k]
        cand_2 = cal_anti[k] - (C-x[N-1-k]) + cal_clock[N-2-k]
        ans = max(ans, cand_1, cand_2)

    return ans


print(main())

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,C=map(int,input().split())
    x,v=[0]*N,[0]*N
    for i in range(N):
        x[i],v[i]=map(int,input().split())
    ans=0
    S=[0]*(N+1)
    for i in range(N):
        S[i+1]=S[i]+v[i]
    x2=[C-x[N-1-i] for i in range(N)]
    v2=list(reversed(v))
    S2=[0]*(N+1)
    for i in range(N):
        S2[i+1]=S2[i]+v2[i]
    
    MAX=[0]*(N+1)
    for i in range(N):
        MAX[i+1]=max(MAX[i],S[i+1]-x[i])
    MAX2=[0]*(N+1)
    for i in range(N):
        MAX2[i+1]=max(MAX2[i],S2[i+1]-x2[i])
    
    x.append(0)
    x2.append(0)
    for i in range(-1,N):
        ans=max(ans,S2[i+1]-x2[i]*2+MAX[-(i+2)],S[i+1]-x[i]*2+MAX2[-(i+2)])
    print(ans)
        

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n,c = map(int,readline().split())
xv = []
l1 = []
for i in range(n):
    x,v = map(int,readline().split())
    xv.append([x,v])
    l1.append(v)
l2 = l1[::]
r1 = l1[::-1]
r2 = r1[::]


for i in range(1, n) :
    l1[i] += l1[i-1]
    l2[i] += l2[i-1]
    r1[i] += r1[i-1]
    r2[i] += r2[i-1]

for i in range(n) :
    x = xv[i][0]
    l1[i] -= x
    l2[i] -= 2 * x
    r1[n-1-i] -= c - x
    r2[n-1-i] -= 2 * (c - x)
 
for i in range(1, n) :
    l1[i] = max(l1[i], l1[i-1])
    r1[i] = max(r1[i], r1[i-1])
 
res = max(l1[-1], r1[-1])
for i in range(n-1) :
    res = max(res, l2[i] + r1[n-2-i])
    res = max(res, r2[i] + l1[n-2-i])
    
print(max(res, 0))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    n,C = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    xv.sort()
    a, b = [], []
    kcal = 0
    for x, v in xv:
        kcal += v
        a.append(kcal - x)
        b.append(kcal-2*x)
    xv.sort(reverse=True)
    c, d = [], []
    kcal = 0
    for x, v in xv:
        kcal += v
        x = C - x
        c.append(kcal - x)
        d.append(kcal-2*x)
    
    for v in [a,b,c,d]:
        for i in range(1, n):
            if v[i] < v[i-1]:
                v[i] = v[i-1]
    
    res = 0
    for i in range(n):
        res = max(res, a[i], c[i])
        if i < n-1:
            res = max(res, b[i]+c[-(i+2)], d[i]+a[-(i+2)])
    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
X=[]
for i in range(n):
  x,y=map(int,input().split())
  X.append((x,y))
SR,DR=[0]*(n+1),[0]*(n+1)
s,d=0,0
cur=0
for i in range(n):
  x,y=X[i]
  SR[i+1]=SR[i]+y-(x-cur)
  DR[i+1]=DR[i]+y-2*(x-cur)
  cur=x

SL,DL=[0]*(n+1),[0]*(n+1)
s,d=0,0
cur=c
for i in reversed(range(n)):
  x,y=X[i]
  SL[n-i]=SL[n-1-i]+y-(cur-x)
  DL[n-i]=DL[n-1-i]+y-2*(cur-x)
  cur=x

for i in range(n):
  SL[i+1]=max(SL[i+1],SL[i])
  SR[i+1]=max(SR[i+1],SR[i])
ans=0
for i in range(n+1):
  a=max(DR[i]+SL[n-i],DL[i]+SR[n-i])
  ans=max(ans,a)
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
n,c = map(int,input().split())
wv = [[0,0]]+[list(map(int,input().split())) for i in range(n)]+[[c,0]]
n += 2
ansls = []
ls1 = [0]*n
ls2 = [0]*n
ls3 = [0]*n
ls4 = [0]*n
for i in range(1,n):
  w,v = wv[i]
  w -= wv[i-1][0]
  ls1[i] = v-w*2
  ls2[i] = v-w
for i in range(n-2,-1,-1):
  w,v = wv[i]
  w -= wv[i+1][0]
  ls3[n-i-1] = v+w*2
  ls4[n-i-1] = v+w
als1 = list(accumulate(ls1))
als2 = list(accumulate(ls2))
als3 = list(accumulate(ls3))
als4 = list(accumulate(ls4))
als1 = list(accumulate(als1,max))
als2 = list(accumulate(als2,max))
als3 = list(accumulate(als3,max))
als4 = list(accumulate(als4,max))
for i in range(n-1):
  ansls.append(als1[i]+als4[n-2-i])
  ansls.append(als2[i]+als3[n-2-i])
print(max(ansls))