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:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, C = MAP()
x = [0] * N
v = [0] * N
for i in range(N):
	x[i], v[i] = MAP()

A = [0] * N
v_tmp = 0
for i in range(N):
	v_tmp += v[i]
	A[i] = v_tmp - x[i]

B = [0] * N
v_tmp = 0
for i in range(N-1, -1, -1):
	v_tmp += v[i]
	B[i] = v_tmp - (C-x[i])

gA = [0] * N
gA[0] = A[0]
for i in range(1, N):
	gA[i] = max(gA[i-1], A[i])

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

a = max(A)
b = max(B)
c, d = 0, 0
if N > 1:
	c = max([A[i]-x[i]+gB[i+1] for i in range(N-1)])
	d = max([B[i]-(C-x[i])+gA[i-1] for i in range(N-1, 0, -1)])

print(max(a, b, c, d, 0))

Submission status: Accepted

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

l1 = [xv[i][1] for i in range(N)]
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])

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

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




arr = [0]
counter_arr = [0]
round_arr = [0]
round_counter_arr = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    counter_ret += value[-i - 1]
    arr.append(max(arr[i], ret - clock_pos[i]))
    round_arr.append(ret - clock_pos[i] * 2)
    counter_arr.append(max(counter_arr[i], counter_ret - (c - clock_pos[-i - 1])))
    round_counter_arr.append(counter_ret - (c - clock_pos[-i - 1]) * 2)



ans = max(arr[-1], counter_arr[-1])
for j in range(n):
    ans = max(ans, round_arr[j] + counter_arr[n - j], round_counter_arr[j] + arr[n - j])


print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




arr = [0]
counter_arr = [0]
round_arr = [0]
round_counter_arr = [0]
ret = 0
counter_ret = 0
for i in range(n):
    ret += value[i]
    a = arr[i - 1]
    arr.append(max(arr[i], ret - clock_pos[i]))
    round_arr.append(ret - clock_pos[i] * 2)
    counter_ret += value[-i - 1]
    counter_arr.append(max(counter_arr[i], counter_ret - (c - clock_pos[-i - 1])))
    round_counter_arr.append(counter_ret - (c - clock_pos[-i - 1]) * 2)



ans = max(arr[-1], counter_arr[-1])
clock_pos = [0] + clock_pos  + [0]
for j in range(n):
    ans = max(ans, round_arr[j] + counter_arr[n - j], round_counter_arr[j] + arr[n - j])



print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, c = LI()
clock_pos = []
value = []
for i, j in LIR(n):
    clock_pos += [i]
    value += [j]




counter_clock_pos = [0] + [c - i for i in clock_pos][::-1]
clock_pos = [0] + clock_pos
clock_cumsum = list(accumulate([0] + value))
counter_clock_cumsum = [0] + list(accumulate(value[::-1]))
# counterではどこまで行くべきか
counter_limit = [0] * (n + 1)
last_max_index = 0
ret = 0
for k in range(n + 1):
    remain = counter_clock_cumsum[k] - counter_clock_pos[k]
    if remain > ret:
        ret = remain
        last_max_index = k
    counter_limit[k] = last_max_index


ans = 0
for i in range(n + 1):
# 時計まわりでとった数がi
    ans = max(ans, clock_cumsum[i] - clock_pos[i] * 2 + counter_clock_cumsum[
        counter_limit[n - i]] - counter_clock_pos[counter_limit[n - i]])


limit = [0] * (n + 1)
last_max_index = 0
ret = 0
for k in range(n + 1):
    remain = clock_cumsum[k] - clock_pos[k]
    if remain > ret:
        ret = remain
        last_max_index = k
    limit[k] = last_max_index


for j in range(n + 1):
    ans = max(ans, counter_clock_cumsum[j] - counter_clock_pos[j] * 2 + clock_cumsum[limit[n - j]] - clock_pos[
        limit[n - j]])



for m in range(n + 1):
    ans = max(ans, clock_cumsum[m] - clock_pos[m])


for p in range(n + 1):
    ans = max(ans, counter_clock_cumsum[p] - counter_clock_pos[p])


print(ans)

Submission status: Accepted

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

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

ans = 0

cand1 = [0] * n
v_sum = 0
for i in range(n):
    v_sum += sushi[i][1]
    cand1[i] = v_sum - sushi[i][0]
    if i > 0:
        cand1[i] = max(cand1[i], cand1[i-1])

cand2 = [0] * n
v_sum = 0
for i in reversed(range(n)):
    v_sum += sushi[i][1]
    cand2[i] = v_sum - (c - sushi[i][0])
    if i != n - 1:
        cand2[i] = max(cand2[i], cand2[i+1])

ans = max(ans, max(cand1), max(cand2))

v_sum = 0
for i in reversed(range(1, n)):
    v_sum += sushi[i][1]
    ans = max(ans, v_sum - (c - sushi[i][0]) * 2 + cand1[i-1])

v_sum = 0
for i in range(n-1):
    v_sum += sushi[i][1]
    ans = max(ans, v_sum - sushi[i][0] * 2 + cand2[i+1])

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

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

N,C = II()
x,v = Line(N)

#時計のみ
ans1 = 0
a = []
for i in range(N):
    a.append([x[i],v[i]])
a2 = sorted(a,key=lambda x:x[0])
temp = 0
for i in range(N):
    temp += a2[i][1]
    if temp-a2[i][0]>ans1:
        ans1 = temp-a2[i][0]

#反時計のみ
ans2 = 0
temp = 0
for i in range(N)[::-1]:
    temp += a2[i][1]
    if temp-(C-a2[i][0])>ans2:
        ans2 = temp-(C-a2[i][0])

ans = max(ans1,ans2)

#時計>=反時計
b = [] #反時計向きの個数,得
temp = 0
for i in range(N)[::-1]:
    temp += a[i][1]
    b.append([N-i,temp-2*(C-a[i][0])])
b.sort(key=lambda x:-x[1])
now = 0
a_temp = 0
for i in range(N):
    a_temp += a[i][1]
    while now<=N-1:
        if b[now][0]+i+1>N:
            now += 1
        else:
            temp = b[now][1]+a_temp-a[i][0]
            if temp>ans:
                ans = temp
            break

#時計<反時計
b = [] #時計向きの個数,得
temp = 0
for i in range(N):
    temp += a[i][1]
    b.append([i+1,temp-2*a[i][0]])
b.sort(key=lambda x:-x[1])
now = 0
a_temp = 0
for i in range(N)[::-1]:
    a_temp += a[i][1]
    while now<=N-1:
        if b[now][0]+N-i>N:
            now += 1
        else:
            temp = b[now][1]+a_temp-(C-a[i][0])
            if temp>ans:
                ans = temp
            break

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate as acc
N, C = map(int, input().split())
ds, vs = [], []
for i in range(N):
  d, v = map(int, input().split())
  ds.append(d)
  vs.append(v)
rvcs = list(acc(vs))
lvcs = list(acc(vs[:: -1]))
rds = ds
lds = [C - d for d in ds[:: -1]]
re = [v - d for d, v in zip(rds, rvcs)]
le = [v - d for d, v in zip(lds, lvcs)]
remax = [0]
lemax = [0]
for i in range(N):
  remax.append(max(remax[-1], re[i]))
  lemax.append(max(lemax[-1], le[i]))
res = 0
#i個のスシを補給する時、右回り直進、左回り直進、右回り反転左回り、左回り反転右回りがある
#反転の際はエネルギー累積maxを使わないと同じスシを２回食べちゃうかも
#反転しない際は取れるだけ取らせてみてもいい
for i in range(N):
  res = max(res, re[i], le[i], re[i] + lemax[N - i - 1] - rds[i], le[i] + remax[N - i - 1] - lds[i])
print(res)

Submission status: Accepted

Solution code:
def main():

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

    clock = [0]
    clock_r = [0]
    v = 0
    for i in range(N):
        v += A[i][1]
        clock.append(v-A[i][0])
        clock_r.append(v-2*A[i][0])
    prefix_clock = [0]
    prefix_clock_r = [0]
    for i in range(1, N+1):
        prefix_clock.append(max(prefix_clock[-1], clock[i]))
        prefix_clock_r.append(max(prefix_clock_r[-1], clock_r[i]))

    cclock = [0]
    cclock_r = [0]
    v = 0
    for i in range(N):
        v += A[N-1-i][1]
        cclock.append(v-(C-A[N-1-i][0]))
        cclock_r.append(v-2*(C-A[N-1-i][0]))
    prefix_cclock = [0]
    prefix_cclock_r = [0]
    for i in range(1, N+1):
        prefix_cclock.append(max(prefix_cclock[-1], cclock[i]))
        prefix_cclock_r.append(max(prefix_cclock_r[-1], cclock_r[i]))

    # print(A, C)
    # print(prefix_clock)
    # print(prefix_cclock)

    max_v = float('-inf')
    for i in range(N+1):
        v1 = prefix_clock_r[i]
        v2 = prefix_cclock[N-i]
        max_v = max(max_v, v1+v2)
        v3 = prefix_clock[i]
        v4 = prefix_cclock_r[N-i]
        max_v = max(max_v, v3+v4)
    return max_v


if __name__ == '__main__':
    print(main())

Submission status: Accepted

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

CR = []
cal = 0
for i in range(n):
    dis = XR[i][0]
    cal += XR[i][1]
    CR.append([cal-dis, dis])


CSR = [CR[0][0]]
for i in range(n-1):
    CSR.append(max(CSR[i], CR[i+1][0]))

CL = []
cal = 0
for i in range(n):
    dis = XL[i][0]
    cal += XL[i][1]
    CL.append([cal-dis, dis])


CSL = [CL[0][0]]
for i in range(n-1):
    CSL.append(max(CSL[i], CL[i+1][0]))


# print(CSR)
# print(CSL)
# print(CR)
# print(CL)

ans = max(max(CSR), max(CSL))
for i in range(n-1):
    # print(CL[i][0]-CL[i][1]+CSR[n-2-i], CL[i][0],CL[i][1],CSR[n-2-i])
    ans = max(ans, CL[i][0]-CL[i][1]+CSR[n-2-i])
    ans = max(ans, CR[i][0]-CR[i][1]+CSL[n-2-i])

print(max(ans, 0))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    s = S()
    s.append("o")
    a = s.count("o")-1
    print(700+a*100)
    return

#B
def B():
    n, x = LI()
    m = IR(n)
    m.sort()
    msum = sum(m)
    print(n + (x - msum) // m[0])
    return

#C
def C():
    a, b, c, x, y = LI()
    if c * 2 > a + b:
        print(x * a + y * b)
        return
    if x > y:
        if c * 2 > a:
            print(c * 2 * y + (x - y) * a)
            return
        print(c * 2 * x)
        return
    if c * 2 > b:
        print(c * 2 * x + (y - x) * b)
        return
    print(c * 2 * y)

    return

#D
def D():
    n, c = LI()
    clock_wise = [0] * n
    clock_wise_max = [0] * n
    clock_wise_rev = [0] * n
    clock_wise_rev_max = [0] * n
    xv = LIR(n)
    clock_wise[0] = xv[0][1] - xv[0][0]
    clock_wise_rev[-1] = - c + xv[-1][1] + xv[-1][0]
    for i in range(1, n):
        clock_wise[i] = clock_wise[i - 1] + xv[i][1] - xv[i][0] + xv[i - 1][0]
        clock_wise_rev[-i - 1] = clock_wise_rev[-i] + xv[-i - 1][1] + xv[-i - 1][0] - xv[-i][0]
    clock_wise_max[0] = clock_wise[0]
    clock_wise_rev_max[-1] = clock_wise_rev[-1]
    for i in range(1,n):
        clock_wise_max[i] = max(clock_wise[i], clock_wise_max[i - 1])
        clock_wise_rev_max[-i - 1] = max(clock_wise_rev[-i - 1], clock_wise_rev_max[-i])
    ans = max(0, max(clock_wise), max(clock_wise_rev))
    for i in range(n - 1):
        ans = max(ans, clock_wise[i] + clock_wise_rev_max[i + 1] - xv[i][0])
        ans = max(ans, clock_wise_rev[-i - 1] + clock_wise_max[-i - 2] - (c - xv[-i - 1][0]))
    print(ans)
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Accepted

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

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

hidariM = [0]
tmp = 0
for i in range(N):
    tmp =  tmp + XV[N-i-1][1]
    hidariM.append(max(hidariM[-1],tmp-C+XV[N-i-1][0]))
    
ans = max(migiM[N],hidariM[N])
tmp = 0
for i in range(N):
    tmp = tmp + XV[i][1]
    if ans < tmp + hidariM[N-1-i] - 2*XV[i][0]:
        ans = tmp + hidariM[N-1-i] - 2*XV[i][0]
        
tmp = 0
for i in range(N):
    tmp = tmp + XV[N-1-i][1]
    if ans < tmp + migiM[N-1-i]  - 2*(C-XV[N-1-i][0]):
        ans = tmp + migiM[N-1-i] - 2*(C-XV[N-1-i][0])

#print(migiM,hidariM)
print(ans)

Submission status: Accepted

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

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

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


max_fa = [0] * (N+1)
max_fa[0] = 0
max_fa[1] = max(0,fa[0])
max_fb = [0] * (N+1)
max_fb[0] = 0
max_fb[1] = max(0,fb[0])
for i in range(2,N+1):
    max_fa[i] = max(max_fa[i-1], fa[i-1])
    max_fb[i] = max(max_fb[i-1], fb[i-1])

ans_a = ans_b = 0

for i in range(N):
    ans_a = max(ans_a, max_fa[N-1-i] + fb[i] - (C - xv[N-1-i][0]) )
    ans_b = max(ans_b, max_fb[N-1-i] + fa[i] - xv[i][0])

ans_a = max(ans_a, max_fa[-1]) # xbがスタート地点の時
ans_b = max(ans_b, max_fb[-1]) # xaがスタート地点の時
print(max(ans_a, ans_b))

Submission status: Accepted

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

value_right = [data[0][2]]
for x,y,z in data[1:]:
    value_right.append(value_right[-1]+z)

value_left = [data[n-1][2]]
for x,y,z in data[::-1][1:]:
    value_left.append(value_left[-1]+z)
value_left = value_left[::-1]

opt_right = []
now_opt = 0
for i in range(n):
    next_opt = max(now_opt,value_right[i]-data[i][0])
    opt_right.append(next_opt)
    now_opt = next_opt

#print(opt_right)
opt_left = []
now_opt = 0
for i in range(n-1,-1,-1):
    next_opt = max(now_opt,value_left[i]-data[i][1])
    opt_left.append(next_opt)
    now_opt = next_opt

#print(opt_left)

ans = 0
for turn in range(n):
    now = -data[turn][0] + value_right[turn]
    #print(now)
    ans = max(ans,now)
    now -= data[turn][0]
    if turn < n-1:
        #print(now + opt_left[n-2-turn])
        ans = max(ans,now + opt_left[n-2-turn])

for turn in range(n-1,-1,-1):
    now = -data[turn][1] + value_left[turn]
    #print(now)
    ans = max(ans,now)
    now -= data[turn][1]
    if turn > 0:
        #print(now + opt_right[turn-1])
        ans = max(ans,now + opt_right[turn-1])

print(ans)

Submission status: Accepted

Solution code:
n,c=[int(j) for j in input().split()]
xv=[]
for i in range(n):
    xv.append([int(j) for j in input().split()])
ll=[[xv[0][0],max(0,xv[0][1]-xv[0][0])]]
lr=[[c-xv[-1][0],max(0,xv[-1][1]-c+xv[-1][0])]]
tmp=xv[0][1]
for i in range(1,n):
    x,v=xv[i]
    tmp+=v
    ll.append([x,max(tmp-x,ll[-1][1])])
tmp=xv[-1][1]
for i in range(n-1)[::-1]:
    x,v=xv[i]
    x=c-x
    tmp+=v
    lr.append([x,max(tmp-x,lr[-1][1])])
ans=0
for i in range(n+1):
    if i==0:
        ans=max(ans,lr[n-1][1])
    elif i==n:
        ans=max(ans,ll[n-1][1])
    else:
        ans=max(ans,ll[i-1][1]+lr[n-i-1][1]-ll[i-1][0])
        ans=max(ans,ll[i-1][1]+lr[n-i-1][1]-lr[n-i-1][0])

print(ans)

Submission status: Accepted

Solution code:
n,c=map(int,input().split())
l=[list(map(int,input().split())) for _ in [0]*n]
if n==1:print(max(0,l[0][1]-l[0][0]));exit()
r=[[c-x[0],x[1]] for x in l[::-1]]

L=[[0]*2 for _ in range(n)]
L[0]=[l[0][1]-l[0][0],l[0][1]-l[0][0]*2]
for i in range(n-1):
    L[i+1][0]=L[i][0]+l[i+1][1]-(l[i+1][0]-l[i][0])
    L[i+1][1]=L[i][1]+l[i+1][1]-(l[i+1][0]-l[i][0])*2
for i in range(n-1):
    L[i+1][0]=max(L[i+1][0],L[i][0])

R=[[0]*2 for _ in range(n)]
R[0]=[r[0][1]-r[0][0],r[0][1]-r[0][0]*2]
for i in range(n-1):
    R[i+1][0]=R[i][0]+r[i+1][1]-(r[i+1][0]-r[i][0])
    R[i+1][1]=R[i][1]+r[i+1][1]-(r[i+1][0]-r[i][0])*2
for i in range(n-1):
    R[i+1][0]=max(R[i+1][0],R[i][0])

max1=max(L[n-1][0],max(R[i][1]+L[n-i-2][0] for i in range(n-1)))
max2=max(R[n-1][0],max(L[i][1]+R[n-i-2][0] for i in range(n-1)))
print(max(0,max1,max2))

Submission status: Accepted

Solution code:
import sys

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

# 右回りの累積和
s = 0
r = [0]*N
for i in range(N):
    s += V[i]
    r[i] = s - X[i]

# 左回りの累積わ
s = 0
l = [0]*N
for i in range(N):
    s += V[N-1-i]
    l[N - 1 - i] = s - (C - X[N - 1 - i])

# 原点～iのMax(R)
MaxR = [0] * N
MaxR[0] = r[0]
for i in range(1,N):
    MaxR[i] = max(MaxR[i-1], r[i])

# 原点～iのMax(L)
MaxL = [0] * N
MaxL[N-1] = l[N-1]
for i in range(1,N):
    MaxL[N-1-i] = max(MaxL[N-i], l[N-1-i])

a = max(r)
b = max(l)
c, d = 0, 0
if N>1:
    c = max([r[i] - X[i] + MaxL[i + 1] for i in range(N - 1)])
    d = max([l[i] - (C-X[i]) + MaxR[i - 1] for i in range(N - 1,0,-1)])

print(max([a,b,c,d,0]))

Submission status: Accepted

Solution code:
N,C=map(int,input().split())
xv=[list(map(int,input().split())) for i in range(N)]
from itertools import accumulate
vc=list(accumulate([v for x,v in xv]))
vc=[vc[i]-x for i,(x,v) in enumerate(xv)]
va=list(accumulate([v for x,v in xv[::-1]]))
va=[va[i]-C+x for i,(x,v) in enumerate(xv[::-1])]
mc=[0]*N
for i in range(N):
    mc[i]=i if vc[mc[i-1]]<vc[i] else mc[i-1]
ma=[0]*N
for i in range(N):
    ma[i]=i if va[ma[i-1]]<va[i] else ma[i-1]
r=max(0,vc[mc[-1]])
for i in range(N-1):
    r=max(r,va[i]+vc[mc[-i-2]]-C+xv[-i-1][0])
r=max(r,va[ma[-1]])
for i in range(N-1):
    r=max(r,vc[i]+va[ma[-i-2]]-xv[i][0])
print(r)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from itertools import *
from copy import *

N, C = map(int, input().split())
f1 = [list(map(int, input().split())) for i in range(N)]
f2 = deepcopy(f1)[::-1]
for i in range(N-1):
    f1[i+1][1] += f1[i][1]
    f2[i+1][1] += f2[i][1]
f1 = [[0, 0, 0]] + [(v-x, x, i) for i, (x, v) in enumerate(f1, 1)]
f2 = [[0, 0, 0]] + [(v-C+x, C-x, i) for i, (x, v) in enumerate(f2, 1)]
g1 = [0] * (N+1)
g2 = [0] * (N+1)
for i in range(1, N+1):
    g1[i] = max(f1[i][0], g1[i-1])
    g2[i] = max(f2[i][0], g2[i-1])
ans = 0
for i in range(N+1):
    ans = max(ans, f1[i][0]+g2[N-i]-f1[i][1], f2[i][0]+g1[N-i]-f2[i][1])
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, v = map(int, input().split())
    X[i] = x
    V[i] = v


answer = 0
R = [0] * N
score = 0
maxscore = 0
for i in range(N):
    score += V[i]
    R[i] = max(maxscore, score - X[i])
    maxscore = R[i]
    answer = max(answer, R[i])

L = [0] *N
score = 0
maxscore = 0
for i in range(N)[::-1]:
    score += V[i]
    L[i] = max(maxscore, score - (C - X[i]))
    maxscore = L[i]
    answer = max(answer, L[i])
L.append(0)

for i in range(N-1):
    answer = max(answer, R[i] - X[i] + L[i+1])

for i in range(1, N)[::-1]:
    answer = max(answer, L[i] - (C-X[i]) + R[i-1])

print(answer)

Submission status: Accepted

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

A = [0] * (N + 1)
A_max = [0] * (N + 1)
B = [0] * (N + 1)
B_max = [0] * (N + 1)
a_sum = 0
b_sum = 0
for i in range(N):
  a_sum += V[i]
  A[i + 1] = a_sum - X[i]
  A_max[i + 1] = max(A_max[i], A[i + 1])
  b_sum += V[- i - 1]
  B[i + 1] = b_sum - (C - X[- i - 1])
  B_max[i + 1] = max(B_max[i], B[i + 1])

X = [0] + X
V = [0] + V

m = max(0, A_max[-1], B_max[-1])
for i in range(1, N + 1):
  m = max(m, A[i] + B_max[N - i] - X[i], B[i] + A_max[N - i] - (C - X[N - i + 1]))

print(m)

Submission status: Accepted

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

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

# print(sushi_array)

left_max = 0
left_double_max = 0

left_array = [[0, 0] for _ in range(N+1)]

right_max = 0
right_double_max = 0

right_array = [[0, 0] for _ in range(N+1)]


left_sum = 0

for i, sushi in enumerate(sushi_array):
    left_sum += sushi[1]
    left_max = max(left_max, left_sum - sushi[0])
    left_double_max = max(left_double_max, left_sum - 2 * sushi[0])
    left_array[i+1][0] = left_max
    left_array[i+1][1] = left_double_max

right_sum = 0

for i, sushi in enumerate(sushi_array[::-1]):
    right_sum += sushi[1]
    right_max = max(right_max, right_sum - (C - sushi[0]))
    right_double_max = max(right_double_max, right_sum - 2 * (C - sushi[0]))
    right_array[N-i-1][0] = right_max
    right_array[N-i-1][1] = right_double_max

ans = 0

for left, right in zip(left_array, right_array):
    ans = max(ans, left[0]+right[1], left[1]+right[0])

print(ans)

Submission status: Accepted

Solution code:
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())
l_candi = [0]*N
for i in range(N):
    l_candi[i] = l[i] + rpath[-(i + 1)] - (c-lm[-(i + 1)][0])
lmax = max(l_candi)

lpath = list(left())
r_candi = [0]*N
for i in range(N):
    r_candi[i] = r[i] + lpath[-(i + 1)] -rm[i][0]
rmax = max(r_candi)

print(max(rmax, lmax))

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 = accumulate(v)
    nt_callory = [b-c for c, b in zip(nt_cost, nt_benefit)]
    nt_callory_acc = list(accumulate([0]+nt_callory, max))

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

    # 時計回り
    m = max(nt_callory_acc[-1], rnt_callory_acc[-1])
    for i in range(N-1):
        callory = nt_callory[i]-nt_cost[i]+rnt_callory_acc[N-i-1]
        m = max(m, callory)

    # 反時計回り
    for i in range(N-1):
        callory = rnt_callory[i]-rnt_cost[i]+nt_callory_acc[N-i-1]
        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()