Problem:


Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.



Sample input:
3 20
2 80
9 120
16 1


Sample output:
191

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from itertools import accumulate
INF = float("inf")


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

    # 時計回りターンなし
    nt_cost = x
    nt_benefit = list(accumulate(v))
    nt_callory = [b-c for c, b in zip(nt_cost, nt_benefit)]
    nt_callory_acc = list(accumulate(nt_callory, max)) + [0]
    # [0]はモンキーパッチ。後に負の参照をした場合に参照させる用
    # print(nt_callory)
    # print(nt_callory_acc)

    # 反時計回りターンなし
    rnt_cost = list((reversed([C-v for v in x])))
    rnt_benefit = list(accumulate(reversed(v)))
    rnt_callory = [b-c for c, b in zip(rnt_cost, rnt_benefit)]
    rnt_callory_acc = list(accumulate(rnt_callory, max)) + [0]
    # print(rnt_callory)
    # print(rnt_callory_acc)

    # 時計回り
    m = -INF
    for i in range(N):
        # i番目でターン
        callory = max(nt_callory[i]-nt_cost[i]+rnt_callory_acc[N-i-2],
                      nt_callory[i])
        # print(i, callory)
        m = max(m, callory)

    # 反時計回り
    for i in range(N):
        # i番目でターン
        callory = max(rnt_callory[i]-rnt_cost[i]+nt_callory_acc[N-i-2],
                      rnt_callory[i])
        # print(i, callory)
        m = max(m, callory)

    print(max(0, m))
    return


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())
x = []
v = []
for _ in range(N):
    xi, vi = map(int, input().split())
    x.append(xi)
    v.append(vi)
vsp = [0] * (N + 1)
vsn = [0] * (N + 1)
dprp = [0] * (N + 1)
dprn = [0] * (N + 1)
dpsp = [0] * (N + 1)
dpsn = [0] * (N + 1)
for i in range(N):
    vsp[i + 1] = vsp[i] + v[i]
    vsn[i + 1] = vsn[i] + v[N - 1 - i]
    dprp[i + 1] = max(dprp[i], vsp[i + 1] - 2 * x[i])
    dpsp[i + 1] = max(dpsp[i], vsp[i + 1] - x[i])
    dprn[i + 1] = max(dprn[i], vsn[i + 1] - 2 * (C - x[N - 1 - i]))
    dpsn[i + 1] = max(dpsn[i], vsn[i + 1] - (C - x[N - 1 - i]))
ans = max([max(dprp[i] + dpsn[N - i], dprn[i] + dpsp[N - i])
           for i in range(N + 1)])
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
x = []
v = []
for _ in range(N):
    xi, vi = map(int, input().split())
    x.append(xi)
    v.append(vi)
vsp = [0] * (N + 1)
vsn = [0] * (N + 1)
dprp = [0] * (N + 1)
dprn = [0] * (N + 1)
dpsp = [0] * (N + 1)
dpsn = [0] * (N + 1)
for i in range(N):
    vsp[i + 1] = vsp[i] + v[i]
    vsn[i + 1] = vsn[i] + v[N - 1 - i]
    dprp[i + 1] = max(dprp[i], vsp[i + 1] - 2 * x[i])
    dpsp[i + 1] = max(dpsp[i], vsp[i + 1] - x[i])
    dprn[i + 1] = max(dprn[i], vsn[i + 1] - 2 * (C - x[N - 1 - i]))
    dpsn[i + 1] = max(dpsn[i], vsn[i + 1] - (C - x[N - 1 - i]))
ans = max(max(dprp[i] + dpsn[N - i], dprn[i] + dpsp[N - i])
          for i in range(N + 1))
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
x = []
v = []
for _ in range(N):
    xi, vi = map(int, input().split())
    x.append(xi)
    v.append(vi)
vsp = [0] * (N + 1)
vsn = [0] * (N + 1)
dprp = [0] * (N + 1)
dprn = [0] * (N + 1)
dpsp = [0] * (N + 1)
dpsn = [0] * (N + 1)
for i in range(N):
    vsp[i + 1] = vsp[i] + v[i]
    vsn[i + 1] = vsn[i] + v[N - 1 - i]
    dprp[i + 1] = max(dprp[i], vsp[i + 1] - 2 * x[i])
    dpsp[i + 1] = max(dpsp[i], vsp[i + 1] - x[i])
    dprn[i + 1] = max(dprn[i], vsn[i + 1] - 2 * (C - x[N - 1 - i]))
    dpsn[i + 1] = max(dpsn[i], vsn[i + 1] - (C - x[N - 1 - i]))
ans = 0
for i in range(N + 1):
    ans = max(ans, dprp[i] + dpsn[N - i], dprn[i] + dpsp[N - i])
print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
x = []
v = []
for _ in range(N):
    xi, vi = map(int, input().split())
    x.append(xi)
    v.append(vi)
vsp = [0] * (N + 1)
vsn = [0] * (N + 1)
dprp = [0] * (N + 1)
dprn = [0] * (N + 1)
dpsp = [0] * (N + 1)
dpsn = [0] * (N + 1)
for i in range(N):
    vsp[i + 1] = vsp[i] + v[i]
    vsn[i + 1] = vsn[i] + v[N - 1 - i]
    dprp[i + 1] = max(dprp[i], vsp[i + 1] - 2 * x[i])
    dpsp[i + 1] = max(dpsp[i], vsp[i + 1] - x[i])
    dprn[i + 1] = max(dprn[i], vsn[i + 1] - 2 * (C - x[N - 1 - i]))
    dpsn[i + 1] = max(dpsn[i], vsn[i + 1] - (C - x[N - 1 - i]))
ans = max(dpsp[N], dpsn[N])
for i in range(N + 1):
    ans = max(ans, dprp[i] + dpsn[N - i], dprn[i] + dpsp[N - i])
print(ans)

Submission status: Accepted

Solution code:
from copy import deepcopy
from itertools import accumulate

n, c = map(int, input().split())
x = []
v = []
# print(n, c)
# c //= 100000000
for _ in range(n):
    _x, _v = map(int, input().split())
    # _x //= 100000000
    # _v //= 100000000
    x.append(_x)
    v.append(_v)
# print(x, v)
v1 = list(accumulate(v)) # CW
v2 = list(accumulate(v[::-1])) # CCW
# print(v1, v2)
f1 = [0] * (n + 1)
f2 = [0] * (n + 1)
for i in range(n):
    f1[i + 1] = v1[i] - x[i]
    f2[i + 1] = v2[i] - (c - x[n - 1 - i])
# print(f1, f2)
g1 = [0] * (n + 1)
g2 = [0] * (n + 1)
for i in range(n):
    g1[i + 1] = max(g1[i], f1[i + 1])
    g2[i + 1] = max(g2[i], f2[i + 1])
# print(g1, g2)
ans = 0
ans = max(ans, g1[n]) # CW only
ans = max(ans, g2[n]) # CCW only
for j in range(n): # CCW then CW
    cal = 0
    cal -= (c - x[n - 1 - j]) * 2
    cal += v2[j]
    cal += g1[n - 1 - j]
    ans = max(ans, cal)
    # print(j, (c - x[n - 1 - j]) * 2, v2[j], g1[n - 1 - j], cal)
for j in range(n): # CW then CCW
    cal = 0
    cal -= (x[j]) * 2
    cal += v1[j]
    cal += g2[n - 1 - j]
    ans = max(ans, cal)
    # print(j, x[j] * 2, v1[j], g2[n - 1 - j], cal)
print(ans)

Submission status: Accepted

Solution code:
def solve(c, sushis):
    cw_maxs, cw_rets = create_accs(sushis, c, True)
    ccw_maxs, ccw_rets = create_accs(reversed(sushis), c, False)
    cw_max = cw_maxs[-1]
    ccw_max = ccw_maxs[-1]
    cw_ccw_max = turn_max(cw_rets, ccw_maxs)
    ccw_cw_max = turn_max(ccw_rets, cw_maxs)
    return max(cw_max, ccw_max, cw_ccw_max, ccw_cw_max)


def turn_max(rets, maxs):
    m = 0
    for i, r in enumerate(rets):
        ind = len(maxs) - 2 - i
        add = maxs[ind] if ind >= 0 else 0
        v = r + add
        if m < v:
            m = v
    return m


def create_accs(sushis, c, cw):
    maxs, vs_ret = [], []
    v_sum, v_max = 0, 0
    for d, v in sushis:
        v_sum += v
        dist = d if cw else c - d
        v_cur = v_sum - dist
        if v_max < v_cur:
            v_max = v_cur
        maxs.append(v_max)
        vs_ret.append(v_sum - dist*2)
    return maxs, vs_ret


n, c = map(int, input().split())
sushis = []
for _ in range(n):
    sushis.append([int(x) for x in input().split()])
print(solve(c, sushis))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

# A
"""
s = input()
sum = 700
for i in range(3):
    if s[i] == "o":
        sum += 100
print(sum)
"""
# B
"""
n, x = map(int, input().split(" "))
m = [0 for i in range(n)]
sum = 0
for i in range(n):
    m[i] = int(input())
m.sort()
for i in range(n):
    x -= m[i]
    sum += 1
sum += (x//m[0])
print(sum)
"""
# C
"""
a,b,c,x,y = map(int, input().split(" "))
sum = 0
if a+b >= c*2:
    v = min(x, y)
    for i in range(v):
        sum += 2*c
    x -= v
    y -= v

if a < c*2:
    sum += a*x
if b < c*2:
    sum += b*y
if a >= c*2:
    sum += 2*c*x
if b >= c*2:
    sum += 2*c*y
print(sum)
"""
# D
n,c = LI()
l = [0]
r = []
v = [0]
for i in range(n):
    a,b = LI()
    l.append(a)
    r.append(c-a)
    v.append(b)
r.append(0)
r = r[::-1]
sl = defaultdict(int)
sr = defaultdict(int)
sl[0] = 0
sr[0] = 0
for i in range(n):
    sl[i+1] = sl[i]+v[i+1]-l[i+1]+l[i]
for i in range(n):
    if sl[i+1] < sl[i]:
        sl[i+1] = sl[i]
for i in range(n):
    sr[i+1] = sr[i]+v[-i-1]-r[i+1]+r[i]
for i in range(n):
    if sr[i+1] < sr[i]:
        sr[i+1] = sr[i]
ans = 0
x = 0
for i in range(n+1):
    x += v[i]
    j = n-i
    m = max(x-l[i],x-2*l[i]+sr[j])
    ans = max(ans,m)

x = 0
for i in range(n+1):
    x += v[-i]
    j = n-i
    m = max(x-r[i],x-2*r[i]+sl[j])
    ans = max(ans,m)
print(ans)

Submission status: Accepted

Solution code:
import sys

#+++++
	



def main():
	n, c = map(int, input().split())
	
	ll=[]
	for i in range(n):
		x,v=map(int, input().split())
		ll.append([x,v])
		
	ll.sort(key=lambda x:x[0])
	for i,v in enumerate(ll):
		ll[i].append(c - v[0])
	all_cal=sum([v[1] for v in ll])
	
	tw=0
	tc=0
	max_c=0
	max_cr=0
	for i,v in enumerate(ll):
		ptw=tw
		tw=v[0]
		tc+=v[1]
		
		#ll[i].append(v[1]-v[0]+ptw)
		cc=tc-tw
		max_c=max(cc,max_c)
		crc=tc-2*tw
		max_cr=max(crc, max_cr)
		#ll[i].append(cc)
		ll[i].append(max_c)
		#ll[i].append(crc)
		ll[i].append(max_cr)

	ll.sort(key=lambda x:-x[0])
	tw=0
	tc=0
	max_c=0
	max_cr=0
	for i,v in enumerate(ll):
		ptw=tw
		tw=v[2]
		tc+=v[1]
		
		#ll[i].append(v[1]-v[0]+ptw)
		cc=tc-tw
		max_c=max(cc,max_c)
		crc=tc-2*tw
		max_cr=max(crc, max_cr)
		#ll[i].append(cc)
		ll[i].append(max_c)
		#ll[i].append(crc)
		ll[i].append(max_cr)
		
	ll.sort(key=lambda x:x[0])
	ret_max=0
	for l in ll:
		#print(l)
		pass
	
	for l,lp in zip(ll,ll[1:]):
		r=l[3]+lp[6]
		ret_max=max(r,ret_max)
		
	for l,lp in zip(ll[-1::-1],ll[-2::-1]):
		r=l[5]+lp[4]
		ret_max=max(r,ret_max)
		
	ret_max=max(ret_max, ll[-1][3])
	ret_max=max(ret_max, ll[0][5])
				
	print(ret_max)
	
	
#+++++

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
	else:
		input = sys.stdin.readline
		
	ret = main()
	if ret is not None:
		print(ret)
		
	if sys.platform =='ios':
		sys.stdin.close()

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())
xv = [list(map(int,input().split())) for _ in range(N)]
x = [xv[i][0] for i in range(N)]
v = [xv[i][1] for i in range(N)]

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

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

ans = 0
for i in range(N):
    ans = max(ans,C1[i],D1[i])

for i in range(N-1):
    ans = max(ans,C2[i]+D1[N-i-2],D2[i]+C1[N-i-2])

print(ans)

Submission status: Accepted

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

x_cum_L = [0] * (N+1)
v_cum_L = [0] * (N+1)
x_cum_R = [0] * (N+1)
v_cum_R = [0] * (N+1)
for i in range(1, N+1):
    x_cum_L[i] = x[i-1]
    v_cum_L[i] = v_cum_L[i-1] + v[i-1]
    x_cum_R[i] = C - x[-i]
    v_cum_R[i] = v_cum_R[i-1] + v[-i]

reward_L = [0] * (N+1)
reward_R = [0] * (N+1)
for i in range(N+1):
    reward_L[i] = v_cum_L[i] - x_cum_L[i]
    reward_R[i] = v_cum_R[i] - x_cum_R[i]

reward_max_L = [0] * (N+1)
reward_max_R = [0] * (N+1)
for i in range(1, N+1):
    reward_max_L[i] = max(reward_max_L[i-1], reward_L[i])
    reward_max_R[i] = max(reward_max_R[i-1], reward_R[i])

ans = 0
for i in range(N+1):
    ans_L = reward_L[i] - x_cum_L[i] + reward_max_R[N - i]
    ans_R = reward_R[i] - x_cum_R[i] + reward_max_L[N - i]
    ans = max(ans, ans_L, ans_R)

print(ans)

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
xv=[(0,0)]
xv_=[]
for i in range(N):
    x,v=map(int,input().split())
    xv.append((x,v))
    xv_.append((x,v))
xv_.append((C,0))
xv_.reverse()
r=[0]*(N+1)
r_=[0]*(N+1)
for i in range(N):
    r[i+1]=r[i]-(xv[i+1][0]-xv[i][0])+xv[i+1][1]
    r_[i+1]=max(r_[i],r[i+1]-xv[i+1][0])
l=[0]*(N+1)
l_=[0]*(N+1)
for i in range(N):
    l[i+1]=l[i]-abs(xv_[i+1][0]-xv_[i][0])+xv_[i+1][1]
    l_[i+1]=max(l_[i],l[i+1]-(C-xv_[i+1][0]))
ans=0
for i in range(1,N+1):
    ans=max(r[i]+l_[N-i],ans)
    ans=max(l[i]+r_[N-i],ans)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
N, c = map(int, input().split())
S = [list(map(int, input().split())) for i in range(N)]

sum_ = 0
r = [0]
for x, v in S:
    sum_ += v
    r.append(sum_-x)

sum_ = 0
l = [0]
for x, v in S[::-1]:
    sum_ += v
    l.append(sum_ - (c-x))

def right():
    max_ = r[0]
    for i in r:
        if max_ < i:
            max_ = i
        yield max_
 
def left():
    max_ = l[0]
    for i in l:
        if max_ < i:
            max_ = i
        yield max_
 
rm = [[0, 0]] + S
lm = S + [[c, c]]
 
rpath = list(right())
lmax = max([l[i]+rpath[-(i+1)]-(c-lm[-(i+1)][0]) for i in range(N)])
 
lpath = list(left())
rmax = max([r[i]+lpath[-(i+1)]-rm[i][0] for i in range(N)])
 
 
print(max(rmax, lmax))

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
sushi=[]
for i in range(n):
    x,v=map(int,input().split())
    sushi.append([x,v])
sushi.sort()
cw=[0]
cw_s=[]
cw_sum=0
for i in range(n):
    x=sushi[i][0]
    v=sushi[i][1]
    cw_sum=cw_sum+v
    cw.append(max(cw[-1],cw_sum-x))
    cw_s.append(cw_sum-2*x)
acw=[0]
acw_s=[]
acw_sum=0
for i in range(n):
    x=c-sushi[n-1-i][0]
    v=sushi[n-1-i][1]
    acw_sum=acw_sum+v
    acw.append(max(acw[-1],acw_sum-x))
    acw_s.append(acw_sum-2*x)
ans=max(cw[n],acw[n])
for i in range(n):
    ans=max(ans,acw_s[i]+cw[n-1-i],cw_s[i]+acw[n-1-i])
print(ans)

Submission status: Accepted

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

N,C = map(int,input().split())
XV = np.array([input().split() for _ in range(N)],dtype=np.int64)
X = XV[:,0]
V = XV[:,1]

Xrev = C - X[::-1]
Vrev = V[::-1]

answer = 0

# ある方向に k in [0,N)個食べた後、逆方向に[1,N-k]個食べる
for X,V,Xrev,Vrev in [(X,V,Xrev,Vrev),(Xrev,Vrev,X,V)]:
  # 順方向に0個以上食べた後、逆方向に進む
  # 順方向に食べて戻ってくるまでの価値
  v1 = np.cumsum(V) - 2*X
  # 逆方向に食べる価値
  v2 = np.cumsum(Vrev) - Xrev
  # 逆方向に食べる番号の上限を決めた場合の最大価値
  v2 = np.maximum.accumulate(v2)
  # 順方向に0個
  x = v2.max()
  if answer < x:
    answer = x
  # 順方向に1～N-1個
  for k in range(1,N):
    x = v1[k-1] + v2[N-k-1]
    if answer < x:
      answer = x
print(answer)

Submission status: Accepted

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

def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    l_cum = [[0, 0] for _ in range(N + 1)]
    r_cum = [[0, 0] for _ in range(N + 1)]
    cal = 0
    for i in range(N):
        cal += v[i]
        val = cal - x[i]
        if val > l_cum[i][0]:
            l_cum[i + 1] = [val, x[i]]
        else:
            l_cum[i + 1] = l_cum[i]
    cal = 0
    for i in range(N - 1, -1, -1):
        cal += v[i]
        pos = C - x[i]
        val = cal - pos
        if val > r_cum[i + 1][0]:
            r_cum[i] = [val, pos]
        else:
            r_cum[i] = r_cum[i + 1]
    #print(l_cum)
    #print(r_cum)
    ret = 0
    for i in range(N + 1):
        ret = max(ret, l_cum[i][0] + r_cum[i][0] - min(l_cum[i][1], r_cum[i][1]))
    print(ret)
    return


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:
from itertools import accumulate
N, C = map(int, input().split())

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


# 右向き・左向きに進み、i番目の寿司までたどり着いた時点のコストを無視したエネルギー
R_v = list(accumulate(V))
L_v = list(accumulate(V[::-1]))

# 右向き・左向きに進み、i番目の寿司までたどり着いた時点のエネルギー
R_xv, L_xv = [], []
for i in range(N):
    R_xv.append(R_v[i] - X[i])
    L_xv.append(L_v[i] - (C - X[N - i - 1]))

# 右向き・左向きに進み、i番目の寿司までたどり着いた時点のエネルギーのmax累積和
R_xv_max = list(accumulate(R_xv, func=max))
L_xv_max = list(accumulate(L_xv, func=max))

ans = 0
for i in range(N):
    ans = max(ans, R_xv[i], L_xv[i])
    if i < N - 1:
        ans = max(ans,
                  R_xv[i] - X[i] + L_xv_max[N - i - 2],
                  L_xv[i] - (C - X[N - i - 1]) + R_xv_max[N - i - 2]
                  )

print(ans)

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools, random
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right; sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]#WideIntPoint
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]#HeightString
def mi(n): return [wi() for _ in range(n)]#MatrixInt
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]

n, c = wi()
xv = mi(n)
#下準備，時計回り
cwli = []; cal = 0
for i in range(n):
    cal += xv[i][1] - xv[i][0]
    if i > 0:
        cal += xv[i - 1][0]#戻す，復元
    cwli.append([cal, i])
#下準備，反時計回り
ccwli = []; cal = 0
for i in range(n - 1, -1, -1):
    cal += xv[i][1] - (c - xv[i][0])
    if i < n - 1:
        cal += (c - xv[i + 1][0])
    ccwli.append([cal, i])

cwli2 = sorted(cwli, reverse=True)
ccwli2 = sorted(ccwli, reverse=True)

#時計回りから
nowp = 0
#cwansli = [-INF] * n
for i in range(n):
    while nowp < n:
        if ccwli2[nowp][1] > i:
            ans = max(cwli[i][0] - xv[i][0] + ccwli2[nowp][0], ans)
            break
        else:
            nowp += 1
#反時計回りから
#ccwansli = [-INF] * n
nowp = 0
for i in range(n - 1, -1, -1):
    while nowp < n:
        if cwli2[nowp][1] < i:
            ans = max(ccwli[n - i - 1][0] - (c - xv[i][0]) + cwli2[nowp][0], ans)
            break
        else:
            nowp += 1

ans = max(cwli2[0][0], ccwli2[0][0], ans)

print(ans)

Submission status: Accepted

Solution code:
###############################################################################

from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)


###############################################################################


def main():
    n, c = intin()
    xvlist = [(0, 0)]
    xvlist.extend(intinl(n))
    xvlist.append((c, 0))

    leftrt = {-1: 0}
    leftmax = {-1: 0}
    rightrt = {-1: 0}
    rightmax = {-1: 0}

    leftxsum = 0
    leftvsum = 0
    rightxsum = 0
    rightvsum = 0

    for i in range(n + 1):
        leftx, leftv = xvlist[i]
        rightx, rightv = xvlist[n-i+1]

        leftxsum = leftx
        leftvsum += leftv
        rightxsum = c - rightx
        rightvsum += rightv

        leftrt[i] = max(leftrt[i-1], leftvsum - leftxsum * 2)
        leftmax[i] = max(leftmax[i-1], leftvsum - leftxsum)
        rightrt[i] = max(rightrt[i-1], rightvsum - rightxsum * 2)
        rightmax[i] = max(rightrt[i-1], rightvsum - rightxsum)

    ans = 0

    for i in range(n + 1):
        ans = max(ans, leftrt[i] + rightmax[n-i])
        ans = max(ans, rightrt[i] + leftmax[n-i])

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

cum_col = [0 for _ in range(N+1)]
for i in range(N):
    cum_col[i+1] = cum_col[i] + sushi[i][1]

clockwise_dp = [None for _ in range(N)]
clockwise_best = [0, 0]
anti_clockwise_dp = [None for _ in range(N)]
anti_clockwise_best = [0, 0]
for i in range(N):
    if clockwise_best[0] < cum_col[i+1] - sushi[i][0]:
        clockwise_best = [cum_col[i+1]-sushi[i][0], sushi[i][0]]
    clockwise_dp[i] = clockwise_best

for i in range(N-1, -1, -1):
    if anti_clockwise_best[0] < cum_col[N] - cum_col[i] - C + sushi[i][0]:
        anti_clockwise_best = [
            cum_col[N]-cum_col[i]-C+sushi[i][0],
            C-sushi[i][0]
        ]
    anti_clockwise_dp[i] = anti_clockwise_best

ans = max(clockwise_dp[N-1][0], anti_clockwise_dp[0][0])
for i in range(N-1):
    ans = max(ans,
              clockwise_dp[i][0],
              anti_clockwise_dp[i+1][0],
              clockwise_dp[i][0]+anti_clockwise_dp[i+1][0]-min(clockwise_dp[i][1], anti_clockwise_dp[i+1][1])
              )

print(ans)

Submission status: Accepted

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

for i in range(N):
    x, v = list(map(int, input().split()))
    D.append(x)
    V.append(V[i] + v)

# clockwise
L = [0]
for i in range(N):
    L.append(max(L[i], V[i + 1] - D[i]))
L_ = max(L)
# counterclockwise
R = [0]
for i in range(N):
    R.append(max(R[i], V[N] - V[N - i - 1] - (C - D[-i - 1])))
R_ = max(R)
# clockwise - counterclockwise
LR = 0
for i in range(N - 1):
    LR = max(LR, V[i + 1] - D[i] * 2 + R[N - i - 1])

# counterclockwise - clockwise
RL = 0
for i in range(N - 1):
    RL = max(RL, V[N] - V[N - i - 1] - (C - D[-i - 1]) * 2 + L[N - i - 1])

print(max(L_, R_, LR, RL))

Submission status: Accepted

Solution code:
N,C = [ int(it) for it in input().split() ]
li = [ [ int(it) for it in input().split() ] for i in range(N) ]

dx = [0]*(N+1)
for i in range(N+1):
  if (i==0):
    dx[i]=li[i][0]-0
  elif(i==N):
    dx[i]=C-li[i-1][0]
  else:
    dx[i]=li[i][0]-li[i-1][0]

lic = [0]*(N+1)
for i in range(N):
  lic[i+1] = lic[i] + li[i][1] - dx[i]
liu = [0]*(N+1)
for i in range(N,0,-1):
  liu[i-1] = liu[i] + li[i-1][1] - dx[i]
lic2 = [0]*(N+1)
for i in range(N):
  lic2[i+1] = lic2[i] + li[i][1] - dx[i]*2
liu2 = [0]*(N+1)
for i in range(N,0,-1):
  liu2[i-1] = liu2[i] + li[i-1][1] - dx[i]*2
lic2ma = [0]*(N+1)
for i in range(1,N+1):
  lic2ma[i] = max(lic2ma[i-1],lic2[i])
liu2ma = [0]*(N+1)
for i in range(N-1,0,-1):
  liu2ma[i] = max(liu2ma[i+1],liu2[i])

if (False):
  
  print (dx)  
  print ( lic )
  print ( liu )  

  print (lic2)
  print (lic2ma)
  print (liu2)
  print (liu2ma)

ma = 0
for i in range(N+1):
  ma = max(ma, lic[i] + liu2ma[i] )
  ma = max(ma, liu[i] + lic2ma[i] )
  
print ( ma )