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:
#95d　高速化・整理
N,C = map(int, input().split())

#左右の折り返し毎に計算すると　2**(N-1) で地球爆発する。折り返しは無駄なので1回のみにする。
#すると、折り返し点N通り、時計回り・反時計回り2通り、計2Nの計算でOKとなる

#入力を読み込みつつ、時計回りの移動のカロリーを計算
xv_list = [(0,0)]
total_cal_list_cw = [0] #時計回りに進んだ時のカロリーリスト
max_total_cal_list_cw = [0] #時計回りに進んだ時、i以下最大のカロリーリスト
max_total_cal_cw = 0

for i in range(1,N+1): #10**5
    x,v = map(int, input().split())
    xv_list.append((x,v))
    total_cal_cw = total_cal_list_cw[i-1] + v - x + xv_list[i-1][0]
    total_cal_list_cw.append(total_cal_cw)
    
    if max_total_cal_cw < total_cal_cw:
        max_total_cal_cw = total_cal_cw
        
    max_total_cal_list_cw.append(max_total_cal_cw)

#半時計回り移動のカロリーを計算
rev_xv_list = [(0,0)] + [(C - xv[0],xv[1]) for xv in xv_list[:-(N+1):-1]] #xv_kistを逆順に読み込み、xは原点から反時計回り時の距離にする
total_cal_list_acw = [0] #反時計回り時のカロリーリスト。以下同様。
max_total_cal_list_acw = [0]
max_total_cal_acw = 0

for i in range(1,N+1): #10**5
    x,v = rev_xv_list[i][0],rev_xv_list[i][1]
    total_cal_acw = total_cal_list_acw[i-1] + v - x + rev_xv_list[i-1][0]
    total_cal_list_acw.append(total_cal_acw)
    
    if max_total_cal_acw < total_cal_acw:
        max_total_cal_acw = total_cal_acw
    
    max_total_cal_list_acw.append(max_total_cal_acw)    

    
#準備ができたので、最大に摂取できるカロリーを求める。
ans = 0

for i in range(1,N+1): #10**5
    #a.先に時計回りをする場合
    #折り返さない場合
    if ans < total_cal_list_cw[i]:
        ans = total_cal_list_cw[i]
    #折り返す場合
    total_cal = total_cal_list_cw[i] - xv_list[i][0] #原点まで戻る
    if total_cal > 0:
        total_cal += max_total_cal_list_acw[N-i]
        if ans < total_cal:
            ans = total_cal
    
    #b.先に反時計回りをする場合
    #折り返さない場合
    if ans < total_cal_list_acw[i]:
        ans = total_cal_list_acw[i]
    #折り返す場合
    total_cal = total_cal_list_acw[i] - rev_xv_list[i][0] #原点まで戻る
    if total_cal > 0:
        total_cal += max_total_cal_list_cw[N-i]
        if ans < total_cal:
            ans = total_cal
        
print(ans)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate
import bisect
n, c = [int(i) for i in sys.stdin.readline().split()]
x_ls = []
inv_x_ls = []
v_ls = []
for i in range(n):
    x, v = [int(i) for i in sys.stdin.readline().split()]
    x_ls.append(x)
    inv_x_ls.append(c - x)
    v_ls.append(v)
inv_v_ls = v_ls[::-1]
inv_x_ls = inv_x_ls[::-1]
v_ls = [0] + [v - x for v, x in zip(accumulate(v_ls), x_ls)]
inv_v_ls = [0] + [v - x for v, x in zip(accumulate(inv_v_ls), inv_x_ls)]
x_ls = [0] + x_ls
inv_x_ls = [0] + inv_x_ls
best_v = 0
best_inv_v = 0
for i in range(n + 1):
    best_v = max(best_v, v_ls[i])
    best_inv_v = max(best_inv_v, inv_v_ls[i])
    v_ls[i] = best_v
    inv_v_ls[i] = best_inv_v

best = 0
for tokei in range(n+1):
    tokei_dis = x_ls[tokei]
    hantokei = max(0, inv_v_ls[n - tokei] - tokei_dis)
    res = v_ls[tokei] + hantokei
    best = max(best, res)
for hantokei in range(n+1):
    hantokei_dis = inv_x_ls[hantokei]
    tokei = max(0, v_ls[n - hantokei] - hantokei_dis)
    res = inv_v_ls[hantokei] + tokei
    best = max(best, res)
print(best)

Submission status: Accepted

Solution code:
N, C = map(int,input().split())
sushi = list(list(map(int,input().split()))for i in range(N))
r1,l1,r2,l2 = [0]*(N+1),[0]*(N+1),[0]*(N+1),[0]*(N+1)

eat = 0
for i in range(N):
    a,b = sushi[i]
    eat += b
    r1[i+1] = max(r1[i],eat-a)
    r2[i+1] = max(r2[i],eat-a*2)
eat = 0
for i in range(N-1,-1,-1):
    a,b = sushi[i]
    eat += b
    l1[i] = max(l1[i+1],eat-(C-a))
    l2[i] = max(l2[i+1],eat-(C-a)*2)

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

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from itertools import accumulate

def rightTrip(x,v,N,C)->int:
    accum_v = list(accumulate(v))
    ## スタート位置から左回りの距離
    left_v = v[::-1]
    left_accum_v = list(accumulate(left_v))

    ## v - 2x
    rightRoundTrip = [accum_v[i]-2*x[i] for i in range(N)]
    """
    右行って左
    """
    dp_left = [0]*(N)
    dp_left[0] = left_v[0] - (C-x[N-1])
    ## dp_left[i] = 左i番目までの最大
    for i in range(1,N):
        dp_left[i] = max(left_accum_v[i]-(C-x[N-i-1]),dp_left[i-1])
    
    answer = 0
    # rightがjまで行ったとき左からはN-2-jまでいける

    for i in range(0,N-1):
        r = rightRoundTrip[i]
        l = dp_left[N-2-i]
        answer = max(r+l,answer)
    
    """
    右行って退店
    """
    rightTrip = [accum_v[i]-x[i] for i in range(N)]
    answer = max(answer,max(rightTrip))
    return answer

def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    ## 右行って左→どこまで右行くのがいいか全探索
    ## 右行って退店
    ## 左行って右
    ## 左行って退店
    left_v = v[::-1]
    left_x = [C-x[i] for i in range(N-1,-1,-1)]
    print(max(rightTrip(x,v,N,C),rightTrip(left_x,left_v,N,C)))
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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))
    solve(N, C, x, v)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
V = [0]
X = [0]
Y = []
for i in range(N):
  x, v = map(int, input().split())
  X += [x]
  Y += [C-x]
  V += [v]
Y += [0]
f = [0]
g = [0]
for i in range(1,N+1):
  f += [f[-1]+X[i-1]+V[i]-X[i]]
  g += [g[-1]+Y[N-i+1]+V[N-i+1]-Y[N-i]]
g = g[::-1]

m = -1
ans1 = 0
for i in range(N+1):
  if m<f[i]:
    m = f[i]
  ans1 = max(ans1, m+g[i]-Y[i])

m = -1
ans2 = 0
for i in range(N, -1, -1):
  if m<g[i]:
    m = g[i]
  ans2 = max(ans2, m+f[i]-X[i])

print(max(ans1, ans2))

Submission status: Accepted

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

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

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

lm=[0]*N
lm[0]=l[0]
for i in range(1,N):
  lm[i]=max(lm[i-1],l[i])
  
rm=[0]*N
rm[0]=r[0]
for i in range(1,N):
  rm[i]=max(rm[i-1],r[i])

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

Submission status: Accepted

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

    left = []
    right = []
    left_append = left.append
    right_append = right.append
    for _ in range(N):
        x, v = map(int, input().split())
        left_append([x, v])
        right_append([C - x, v])

    tmp1 = max(0, left[0][1] - left[0][0])
    left_value = [0, tmp1]
    tmp2 = max(0, left[0][1] - 2 * left[0][0])
    left_value_back = [0, tmp2]
    left_value_append = left_value.append
    left_value_back_append = left_value_back.append
    for i in range(1, N):
        left[i][1] += left[i - 1][1]
        tmp1 = max(tmp1 ,left[i][1] - left[i][0])
        left_value_append(tmp1)
        tmp2 = max(tmp2 ,left[i][1] - 2 * left[i][0])
        left_value_back_append(tmp2)

    tmp1 = max(0, right[N - 1][1] - right[N - 1][0])
    right_value = [0, tmp1]
    tmp2 = max(0, right[N- 1][1] - 2 * right[N - 1][0])
    right_value_bakc = [0, tmp2]
    right_value_append = right_value.append
    right_value_bakc_append = right_value_bakc.append
    for i in range(N- 2, -1, -1):
        right[i][1] += right[i + 1][1]
        tmp1 = max(tmp1, right[i][1] - right[i][0])
        right_value_append(tmp1)
        tmp2 = max(tmp2, right[i][1] - 2 * right[i][0])
        right_value_bakc_append(tmp2)

    # print (left)
    # print (left_value)
    # print (left_value_back)
    # print ()
    # print (right)
    # print (right_value)
    # print (right_value_bakc)

    ans = 0
    for i in range(N + 1):
        tmp = max(left_value[i], right_value[N - i])
        tmp = max(tmp, left_value_back[i] + right_value[N - i], left_value[i] + right_value_bakc[N - i])
        ans = max(ans, tmp)

    print (ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

tmp1 = max(0, left[0][1] - left[0][0])
left_value = [0, tmp1]
tmp2 = max(0, left[0][1] - 2 * left[0][0])
left_value_back = [0, tmp2]
for i in range(1, N):
    left[i][1] += left[i - 1][1]
    tmp1 = max(tmp1 ,left[i][1] - left[i][0])
    left_value.append(tmp1)
    tmp2 = max(tmp2 ,left[i][1] - 2 * left[i][0])
    left_value_back.append(tmp2)

tmp1 = max(0, right[N - 1][1] - right[N - 1][0])
right_value = [0, tmp1]
tmp2 = max(0, right[N- 1][1] - 2 * right[N - 1][0])
right_value_bakc = [0, tmp2]
for i in range(N- 2, -1, -1):
    right[i][1] += right[i + 1][1]
    tmp1 = max(tmp1, right[i][1] - right[i][0])
    right_value.append(tmp1)
    tmp2 = max(tmp2, right[i][1] - 2 * right[i][0])
    right_value_bakc.append(tmp2)

# print (left)
# print (left_value)
# print (left_value_back)
# print ()
# print (right)
# print (right_value)
# print (right_value_bakc)

ans = 0
for i in range(N + 1):
    tmp = max(left_value[i], right_value[N - i])
    tmp = max(tmp, left_value_back[i] + right_value[N - i], left_value[i] + right_value_bakc[N - i])
    ans = max(ans, tmp)

print (ans)

Submission status: Accepted

Solution code:
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
import queue
#import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i*factorial(i-1)
 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)




def main(): #startline--------------------------------------------
    N,C = map(int,input().split())
    xv = [tuple(map(int,input().split())) for i in range(N)]
    r1,r2,l1,l2= [0]*(N+1),[0]*(N+1),[0]*(N+1),[0]*(N+1)
    ans = 0
    dis = 0
    for i in range(N):
        r1[i+1] = r1[i]+xv[i][1]-(xv[i][0]-dis)
        r2[i+1] = r2[i]+xv[i][1]-2*(xv[i][0]-dis)
        dis = xv[i][0]
    dis = C
    for i in reversed(range(N)):
        l1[N-i]=l1[N-i-1]+xv[i][1]-(dis-xv[i][0])
        l2[N-i]=l2[N-i-1]+xv[i][1]-2*(dis-xv[i][0])
        dis = xv[i][0]
    for i in range(N):
        l1[i+1] = max(l1[i+1],l1[i])
        r1[i+1] = max(r1[i+1],r1[i])
    for i in range(N+1):
        subans = max(r2[i]+l1[N-i],l2[i]+r1[N-i])
        ans = max(ans,subans)
    print(ans)
if __name__ == "__main__":
    main() #endline===============================================

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
from collections import deque
def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math
import bisect
from logging import getLogger, StreamHandler, DEBUG, WARNING
logger = getLogger(__name__)
handler = StreamHandler()
handler.setLevel(DEBUG)
logger.setLevel(DEBUG)
handler.setLevel(WARNING)
logger.setLevel(WARNING)
logger.addHandler(handler)
logger.propagate = False


# class SegTree():
#     def __init__(self, n):
#         self.value = [0 for i in range(n*2)]

# MOD = 10 ** 9 + 7

# def getinvmod(n):
#     return [pow(i, MOD-2, MOD) for i in range(n+1)]

def main():
    n, m = getList()
    sushis = []
    for i in range(n):
        sushis.append(getList())

    tmp = 0
    acc = [(0, 0)]
    acc2 = [0]
    acc2idx = [0]

    for sushi in sushis:
        tmp += sushi[1]
        if tmp - sushi[0] > acc[-1][1]:
            acc.append((sushi[0], tmp - sushi[0]))
        if tmp - 2 * sushi[0] > acc2[-1]:
            acc2.append(tmp - sushi[0] * 2)
            acc2idx.append(sushi[0])

    tmp = 0
    racc = [(0, 0)]
    racc2 = [0]
    racc2idx = [0]

    for sushi in sushis[::-1]:
        tmp += sushi[1]
        dist = m - sushi[0]
        if tmp - dist > racc[-1][1]:
            racc.append((sushi[0], tmp - dist))
        if tmp - 2 * dist > racc2[-1]:
            racc2.append(tmp - 2 * dist)
            racc2idx.append(dist)


    ans = 0
    for asu in acc:
        tmp = asu[1]
        idx = bisect.bisect_left(racc2idx, m - asu[0])
        tmp += racc2[idx - 1]
        if tmp > ans:
            ans = tmp
            logger.info(asu, tmp, idx)

    for asu in racc:
        tmp = asu[1]
        idx = bisect.bisect_left(acc2idx, asu[0])
        tmp += acc2[idx - 1]
        if tmp > ans:
            ans = tmp
            logger.info(asu, tmp)

    print(ans)
    logger.info(acc, acc2)
    logger.info(racc, racc2, racc2idx)

    return
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#入力受け取り
def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	N, C = getlist()
	left1sum = [0]
	right1sum = [0]
	left2sum = [0]
	right2sum = [0]
	X = []
	V = []
	for i in range(N):
		x, v = getlist()
		X.append(x)
		V.append(v)
	for i in range(N):
		left1sum.append(left1sum[-1] + V[-1 - i])
		left2sum.append(left2sum[-1] + V[-1 - i])
		right1sum.append(right1sum[-1] + V[i])
		right2sum.append(right2sum[-1] + V[i])
	# print(right1sum)
	# print(right2sum)
	# print(left1sum)
	# print(left2sum)
	for i in range(N):
		right1sum[i + 1] -= X[i]
		right2sum[i + 1] -= 2 * X[i]
		left1sum[i + 1] -= C - X[-1 - i]
		left2sum[i + 1] -= 2 * (C - X[-1 - i])

	for i in range(N):
		right1sum[i + 1] = max(right1sum[i + 1], right1sum[i])
		right2sum[i + 1] = max(right2sum[i + 1], right2sum[i])
		left1sum[i + 1] = max(left1sum[i + 1], left1sum[i])
		left2sum[i + 1] = max(left2sum[i + 1], left2sum[i])
	# print(right1sum)
	# print(right2sum)
	# print(left1sum)
	# print(left2sum)
	ans = 0
	for i in range(N + 1):
		ans = max(ans, right1sum[i] + left2sum[N - i])
		ans = max(ans, right2sum[i] + left1sum[N - i])
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

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

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

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

lm=[0]*N
lm[0]=l[0]
for i in range(1,N):
  lm[i]=max(lm[i-1],l[i])
  
rm=[0]*N
rm[0]=r[0]
for i in range(1,N):
  rm[i]=max(rm[i-1],r[i])

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,c=map(int,input().split())
    X=[0]*n; V=[0]*n
    for i in range(n):
        X[i],V[i]=map(int,input().split())

    revX=[c-x for x in X]
    revV=V[:]

    for i in range(n-1):
        V[i+1]+=V[i]
    for i in range(n):
        V[i]-=X[i]

    maxV=V[:]
    for i in range(n-1):
        maxV[i+1]=max(maxV[i+1],maxV[i])


    for i in range(n-1,0,-1):
        revV[i-1]+=revV[i]
    for i in range(n-1,-1,-1):
        revV[i]-=revX[i]

    maxrevV=revV[:]
    for i in range(n-1,0,-1):
        maxrevV[i-1]=max(maxrevV[i-1],maxrevV[i])

    # 片方向だけ使った場合の最大を取っておく
    ans=max(max(maxV),max(maxrevV),0)

    # forward に i, backwardに最大 i+1 まで行く時の場合を試す
    for i in range(n-1):
        ans=max(ans,V[i]+maxrevV[i+1]-X[i])

    # backward に i, forwardに最大 i-1 まで行く時の場合を試す
    for i in range(1,n):
        ans=max(ans,revV[i]+maxV[i-1]-revX[i])

    print(ans)
resolve()

Submission status: Accepted

Solution code:
def main():
    from itertools import accumulate as ac
    n,c=map(int,input().split())
    xv=[list(map(int,input().split())) for _ in [0]*n]
    rmemo=[0]*n
    lmemo=[0]*n
    rmemo[0]=xv[0][1]-xv[0][0]
    lmemo[n-1]=xv[n-1][1]-(c-xv[n-1][0])
    for i in range(1,n):
        rmemo[i]=rmemo[i-1]+xv[i][1]-xv[i][0]+xv[i-1][0]
    for i in range(n-2,-1,-1):
        lmemo[i]=lmemo[i+1]+xv[i][1]+xv[i][0]-xv[i+1][0]
    temp=rmemo[0]
    rmemo2=[temp]*(n)
    temp=lmemo[-1]
    lmemo2=[temp]*(n+1)
    lmemo2[-1]=0
    for i in range(1,n):
        rmemo2[i]=max(rmemo[i],rmemo2[i-1])
    for i in range(n-2,-1,-1):
        lmemo2[i]=max(lmemo[i],lmemo2[i+1])
    rmemo2=[0]+rmemo2
    ans=max(rmemo+lmemo+[0])
    for i in range(n):
        ans=max(ans,rmemo[i]+lmemo2[i+1]-xv[i][0])
        ans=max(ans,lmemo[i]+rmemo2[i]+xv[i][0]-c)
    print(ans)
main()

Submission status: Accepted

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

A = [0] * (N+1)
B = [0] * (N+1)
MAA = [0] * (N+1)
MAB = [0] * (N+1)

for i in range(N):
    A[i+1] = A[i] + X[i][0] - (X[i][1] - (X[i-1][1] if i else 0))
    MAA[i+1] = max(MAA[i], A[i+1])

for i in range(N)[::-1]:
    B[i] = B[i+1] + X[i][0] + (X[i][1] - (X[i+1][1] if i < N-1 else C))
    MAB[i] = max(MAB[i+1], B[i])

ma = max(max(MAA), max(MAB))
for i in range(N):
    ma = max(ma, A[i+1] + MAB[i+1] - X[i][1])
    ma = max(ma, B[i] + MAA[i] + X[i][1] - C)

print(ma)

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.read
readline = sys.stdin.readline

N, C = map(int, readline().split())
xv = np.array(read().split(), np.int64).reshape(N, 2)
v = xv[:, 1]
x = xv[:, 0]

ax = C - x[::-1]
cx = x.copy()
cx[1:] = cx[1:] - cx[:-1]
acx = C - x
acx[:-1] = acx[:-1] - acx[1:]

clockwise = np.cumsum(v - cx)
anticlockwise = v - acx
anticlockwise = np.cumsum(anticlockwise[::-1])

con_max = np.maximum.accumulate(clockwise)
anti_max = np.maximum.accumulate(anticlockwise)

answer = [0, con_max[-1], anti_max[-1]]

clockwise = clockwise - x
anti_max = anti_max[::-1]
clockwise[:-1] = clockwise[:-1] + anti_max[1:]
anticlockwise = anticlockwise - ax
con_max = con_max[::-1]
anticlockwise[:-1] = anticlockwise[:-1] + con_max[1:]

answer.append(anticlockwise.max())
answer.append(clockwise.max())

print(max(answer))

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.read
readline = sys.stdin.readline

N, C = map(int, readline().split())
xv = np.array(read().split(), np.int64).reshape(N, 2)
v = xv[:, 1]
x = xv[:, 0]

ax = C - x[::-1]
cx = x.copy()
cx[1:] = cx[1:] - cx[:-1]
acx = C - x
acx[:-1] = acx[:-1] - acx[1:]

clockwise = v - cx
np.cumsum(clockwise, out=clockwise)
anticlockwise = v - acx
anticlockwise = np.cumsum(anticlockwise[::-1])

con_max = np.maximum.accumulate(clockwise)
anti_max = np.maximum.accumulate(anticlockwise)

answer = [0, con_max[-1], anti_max[-1]]

for i in range(N - 1):
    answer.append(clockwise[i] - x[i] + anti_max[N - i - 2])
    answer.append(anticlockwise[i] - ax[i] + con_max[N - i - 2])

print(max(answer))

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
inf=float("inf")
n,c=map(int,input().split())
xv=[list(map(int,input().split())) for i in range(n)]

ra=[0]*(n+1)
ra[1]=xv[0][1]-xv[0][0]
for i in range(1,n):
    ra[i+1]=ra[i]+xv[i][1]-(xv[i][0]-xv[i-1][0])
mra=[0]*(n+1)
mra[1]=ra[1]
for i in range(1,n):
    mra[i+1]=max(mra[i],ra[i+1])
# print(ra)
# print(mra)

lb=[0]*(n+1)
lb[1]=xv[-1][1]-(c-xv[-1][0])
for i in range(1,n):
    lb[i+1]=lb[i]+xv[-1-i][1]-(xv[-i][0]-xv[-1-i][0])
mlb=[0]*(n+1)
mlb[1]=lb[1]
for i in range(1,n):
    mlb[i+1]=max(mlb[i],lb[i+1])
# print(lb)
# print(mlb)

ans=max(0,lb[0]+mra[n])
for i in range(1,n+1):
    ans=max(ans,lb[i]+mra[n-i]-(c-xv[-i][0]))
ans=max(ans,ra[0]+mlb[n])
for i in range(1,n+1):
    ans=max(ans,ra[i]+mlb[n-i]-xv[i-1][0])
print(ans)

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xy=[list(map(int,input().split())) for i in range(n)]
data=[0]*(n+1)
for i in range(n):
    x,y=xy[i]
    data[i+1]=data[i]+y
data1=[0]*(n+1)
data2=[0]*(n+1)
for i in range(n):
    x,y=xy[i]
    data1[i+1]=data[i+1]-x
    data2[i+1]=data[i+1]-2*x
data=[0]*(n+1)
for i in range(n):
    x,y=xy[n-1-i]
    data[i+1]=data[i]+y
data3=[0]*(n+1)
data4=[0]*(n+1)
for i in range(n):
    x,y=xy[n-1-i]
    data3[i+1]=data[i+1]-(c-x)
    data4[i+1]=data[i+1]-2*(c-x)
for i in range(1,n+1):
    data1[i]=max(data1[i],data1[i-1])
    data2[i]=max(data2[i],data2[i-1])
    data3[i]=max(data3[i],data3[i-1])
    data4[i]=max(data4[i],data4[i-1])
ans=-float("inf")
for i in range(0,n+1):
    a=data2[i]+data3[n-i]
    b=data4[i]+data1[n-i]
    ans=max(ans,a,b)
print(ans)

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,c = LI()
xv = [LI() for _ in range(n)]

l1 = [v for x,v in xv]
l2 = l1[:]
r1 = l1[::-1]
r2 = r1[:]

l1 = list(accumulate(l1))
l2 = list(accumulate(l2))
r1 = list(accumulate(r1))
r2 = list(accumulate(r2))

for i,(x,v) in enumerate(xv):
    l1[i] -= x
    l2[i] -= 2*x
    r1[-i-1] -= c - x
    r2[-i-1] -= 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])

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

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
xv = list(list(map(int, input().split())) for i in range(n))
vx=xv[::-1]
sushi1, max1, sushi2, max2 = [0], [0], [0], [0]
import numpy as np

sum1,sum2=0,0
for x,v in xv:
        sum1+=v
        sushi1.append(max(sum1 - x, sushi1[-1]))
        max1.append(max(sum1 - 2*x, max1[-1]))
for x, v in vx:
    sum2 += v
    sushi2.append(max(sum2 - (c-x), sushi2[-1]))
    max2.append(max(sum2 - 2*(c-x), max2[-1]))
ans1 = max(np.array(sushi1) + np.array(max2[::-1]))
ans2 = max(np.array(sushi2) + np.array(max1[::-1]))
print(max(0, ans1, ans2))

Submission status: Accepted

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
# from copy import deepcopy, copy

import queue
from collections import deque




def main():
    num_sushi, length = map(int, input().split())
    data = [list(map(int, input().split())) for i in range(num_sushi)]

    ans = 0
    right1 = [0 for i in range(num_sushi)]
    right1_max = [0 for i in range(num_sushi)]
    for i in range(num_sushi):
        x, v = data[i]
        if i == 0:
            right1[i] = v - x
            right1_max[i] = max(0, right1[i])
        else:
            right1[i] = right1[i - 1] + v - (x - data[i - 1][0])
            right1_max[i] = max(right1_max[i - 1], right1[i])
        ans = max(ans, right1_max[i])

    left1 = [0 for i in range(num_sushi)]
    left1_max = [0 for i in range(num_sushi)]
    for i in range(num_sushi)[::-1]:
        x, v = data[i]
        x = length - x
        if i == num_sushi - 1:
            left1[i] = v - x
            left1_max[i] = max(0, left1[i])
        else:
            left1[i] = left1[i + 1] + v - (data[i + 1][0] - data[i][0])
            left1_max[i] = max(left1_max[i + 1], left1[i])
        ans = max(ans, left1_max[i])

    right2 = [0 for i in range(num_sushi)]
    for i in range(num_sushi - 1):
        x, v = data[i]
        if i == 0:
            right2[i] = v - 2 * x
        else:
            right2[i] = right2[i - 1] + v - 2 * (data[i][0] - data[i - 1][0])
        # print(right2, x, v, data)
        ans = max(ans, right2[i] + left1_max[i + 1])

    left2 = [0 for i in range(num_sushi)]
    for i in range(1, num_sushi)[::-1]:
        x, v = data[i]
        x = length - x
        if i == num_sushi - 1:
            left2[i] = v - 2 * x
        else:
            left2[i] = left2[i + 1] + v - 2 * (data[i + 1][0] - data[i][0])
        ans = max(ans, left2[i] + right1_max[i - 1])

    print(ans)









if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate

N, C, *XV = map(int, open(0).read().split())

X = XV[::2] + [C]
A = [0] + list(accumulate(XV[1::2]))

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

    L = max(L, A[b] - X[b - 1])
    R = max(R, A[b] - 2 * X[b - 1])

    ans = max(ans, L + T - 2 * d, R + T - d)

print(ans)

Submission status: Accepted

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

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

    ans = 0

    R = [0]
    x0, v0 = 0, 0
    for i in range(N):
        x, v = XV[i]
        v0 += v-(x-x0)
        x0 = x
        R.append(max(v0, R[-1]))
        ans = max(ans, v0)

    L = [0]
    x0, v0 = C, 0
    for i in reversed(range(N)):
        x, v = XV[i]
        v0 += v-(x0-x)
        x0 = x
        L.append(max(v0, L[-1]))
        ans = max(ans, v0)

    x0, v0 = 0, 0
    for r in range(N):
        x, v = XV[r]
        v0 += v-2*(x-x0)
        x0 = x
        ans = max(ans, v0+L[N-1-r])

    x0, v0 = C, 0
    for l in reversed(range(N)):
        x, v = XV[l]
        v0 += v-2*(x0-x)
        x0 = x
        ans = max(ans, v0+R[l])

    print(ans)


if __name__ == "__main__":
    main()