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: Wrong Answer

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

N, C, *xv = map(int, read().split())
x, v = zip(*zip(*[iter(xv)] * 2))
v = np.array(v, np.int64)
x = np.array(x, np.int64)
ax = C - x
ax = ax[::-1]
cx = np.array(x, np.int64)
cx[1:] -= cx[:-1]
acx = C - np.array(x, np.int64)
acx[:-1] -= acx[1:]

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

answer = [0]
answer.append(clockwise.max())
answer.append(anticlockwise.max())

for i in range(N - 1):
    anti_max = np.where(anticlockwise[:N - i - 1] == anticlockwise[:N - i - 1].max())[0]
    anti_max = anti_max[0]
    answer.append(clockwise[i] - x[i] + anticlockwise[anti_max])

    con_max = np.where(clockwise[:N - i - 1] == clockwise[:N - i - 1].max())[0]
    con_max = con_max[0]
    answer.append(anticlockwise[i] - ax[i] + clockwise[con_max])

print(max(answer))

Submission status: Wrong Answer

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

N, C, *xv = map(int, read().split())
x, v = zip(*zip(*[iter(xv)] * 2))
v = np.array(v, np.int64)
x = np.array(x, np.int64)
ax = C - x
ax = ax[::-1]
cx = np.array(x, np.int64)
cx[1:] -= cx[:-1]
acx = C - np.array(x, np.int64)
acx[:-1] -= acx[1:]

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

answer = [0]
answer.append(clockwise.max())
answer.append(anticlockwise.max())

for i in range(N - 1):
    anti_max = np.where(anticlockwise[:N - i - 1] == anticlockwise[:N - i - 1].max())[0]
    anti_max = anti_max[0]
    answer.append(clockwise[i] - x[i] + anticlockwise[anti_max])

for i in range(N - 1):
    _max = np.where(clockwise[:N - i - 1] == clockwise[:N - i - 1].max())[0]
    _max = _max[0]
    answer.append(anticlockwise[i] - ax[i] + clockwise[_max])

print(max(answer))

Submission status: Wrong Answer

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 for _ in range(N)]
A[0] = V[0]-X[0]
B = [0 for _ in range(N)]
B[0] = max(0,A[0])
for i in range(1,N):
    A[i] = A[i-1]+V[i]-X[i]+X[i-1]
    B[i] = max(A[i],B[i-1])
cmax = B[-1]
v =0
for i in range(1,N):
    v += V[-i]
    cmax = max(cmax,v-(C-X[-i]),v-2*(C-X[-i])+B[-i-1])
cmax = max(cmax,v+V[0]-(C-X[-N]))
print(cmax)

Submission status: Wrong Answer

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 for _ in range(N)]
A[0] = V[0]-X[0]
B = [0 for _ in range(N)]
B[0] = A[0]
for i in range(1,N):
    A[i] = A[i-1]+V[i]-X[i]+X[i-1]
    B[i] = max(A[i],B[i-1])
cmax = B[-1]
v =0
for i in range(1,N):
    v += V[-i]
    cmax = max(cmax,v-(C-X[-i]),v-2*(C-X[-i])+B[-i-1])
cmax = max(cmax,v+V[0]-(C-X[-N]))
print(cmax)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
N,C = [int(x) for x in input().split()]
xv =[]
append1 = xv.append
su = [0]*(N)
su1 = [0]*(N+1)
suh = [0]*(N+1)
suh1 = [0]*(N)
for i in range(N):
  x1,v1 = [int(x) for x in input().split()]
  append1([x1,v1])
xv.sort()
v = [xv[i][1] for i in range(N)]
vl =  [xv[i][1] for i in range(N-1,-1,-1)]
vc = list(accumulate(v))
vh = list(accumulate(vl))
#print(vh)
#print(xv)
for i in range(N):
  su1[i]= vc[i]-2*xv[i][0]
  su[i]= vc[i]-xv[i][0]

for i in range(N):
  suh[i]= vh[i]-2*(20-xv[N-1-i][0])
  suh1[i]= vh[i]-(20-xv[N-1-i][0])

l =[]
l1 = []
for i in range(1,N):
  l.append(max(max(su[:-i]),0))
  l1.append(max(max(suh1[:-i]),0))
ans = 0
for i in range(N-1):
  ans = max(ans,suh[i]+l[i],suh1[i])
  ans = max(ans,su1[i]+l1[i],su[i])
print(ans)

Submission status: Wrong Answer

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]] - counter_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: Wrong Answer

Solution code:
#累積和から累積maxを作る
N, C = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(N)]
csv = [0] * (N + 1)
csvd = [0] * (N + 1)
cmv = [0] * (N + 1)
cmvr = [0] * (N + 1)
s.sort()
res = 0
for i in range(N):
  csv[i + 1] = csv[i] + s[i][1]
  csvd[i + 1] = csv[i + 1] - s[i][0]
  cmv[i + 1] = max(cmv[i], csvd[i])
  cmvr[N - i - 1] = max(cmvr[i], csv[N] - csv[i] - (C - s[i][0]))
#print(csv, csvd, cmv, cmvr)
for l in range(N):
  a = cmv[l] + csv[-1] - csv[l] - (C - s[l][0]) * 2
  b = cmvr[l] + csvd[l + 1] - s[l][0]
  res = max(res, a, b, cmv[l + 1], cmvr[l + 1])
print(res)

Submission status: Wrong Answer

Solution code:
#累積和から累積maxを作る
N, C = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(N)]
csv = [0] * (N + 1)
csvd = [0] * (N + 1)
cmv = [0] * (N + 1)
cmvr = [0] * (N + 1)
s.sort()
res = 0
for i in range(N):
  csv[i + 1] = csv[i] + s[i][1]
  csvd[i + 1] = csv[i + 1] - s[i][0]
  cmv[i + 1] = max(cmv[i], csvd[i])
  cmvr[N - i - 1] = max(cmvr[i], csv[N] - csv[i] - (C - s[i][0]))
#print(csv, csvd, cmv, cmvr)
for l in range(N):
  a = cmv[l] + csv[-1] - csv[l] - (C - s[l][0]) * 2
  b = cmvr[l] + csvd[l + 1] - s[l][0]
  res = max(res, a, b, cmv[l + 1])
print(res)

Submission status: Wrong Answer

Solution code:
#lの位置は線形探索、rの位置はさぶたん
N, C = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(N)]
csv = [0] * (N + 1)
s.sort()
for i in range(N):
  csv[i + 1] = csv[i] + s[i][1]
res = 0
for l in range(N):
  rlim = N - 1
  llim = 0
  x1 = (rlim - llim) // 3
  x2 = 2 * x1
  while x2 - x1 > 3:
    x1 = (rlim - llim) // 3 + llim
    x2 = 2 * ((rlim - llim) // 3) + llim
    xres = [0, 0]
    i = 0
    #print(l, llim, x1, x2, rlim)
    for r in (x1, x2):
      if l > r:
        a = (C - s[l][0]) * 2 + s[r][0]
        b = (C - s[l][0]) + s[r][0] * 2
        xres[i] = csv[r + 1] + (csv[-1] - csv[l]) - min(a, b)
      else:
        xres[i] = csv[r + 1] - csv[l] - s[r][0]
      i += 1
    #print(xres)
    if xres[0] > xres[1]:
      res = max(xres[0], res)
      rlim = x2
    else:
      res = max(xres[1], res)
      llim = x1
  for r in range(llim, rlim + 1):
    if l > r:
      a = (C - s[l][0]) * 2 + s[r][0]
      b = (C - s[l][0]) + s[r][0] * 2
      res = max(res, csv[r + 1] + (csv[-1] - csv[l]) - min(a, b))
    else:
      res = max(res, csv[r + 1] - csv[l] - s[r][0])
print(res)

Submission status: Wrong Answer

Solution code:
#lの位置は線形探索、rの位置はさぶたん
N, C = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(N)]
csv = [0] * (N + 1)
s.sort()
for i in range(N):
  csv[i + 1] = csv[i] + s[i][1]
res = 0
for l in range(N):
  rlim = N - 1
  llim = 0
  x1 = (rlim - llim) // 3
  x2 = 2 * x1
  while x2 - x1 > 3:
    x1 = (rlim - llim) // 3 + llim
    x2 = 2 * (rlim - llim) // 3 + llim
    xres = [0, 0]
    i = 0
    #print(l, llim, x1, x2, rlim)
    for r in (x1, x2):
      if l > r:
        a = (C - s[l][0]) * 2 + s[r][0]
        b = (C - s[l][0]) + s[r][0] * 2
        xres[i] = csv[r + 1] + (csv[-1] - csv[l]) - min(a, b)
      else:
        xres[i] = csv[r + 1] - csv[l] - s[r][0]
      i += 1
    #print(xres)
    if xres[0] > xres[1]:
      res = max(xres[0], res)
      rlim = x2
    else:
      res = max(xres[1], res)
      llim = x1
  for r in range(llim, rlim + 1):
    if l > r:
      a = (C - s[l][0]) * 2 + s[r][0]
      b = (C - s[l][0]) + s[r][0] * 2
      res = max(res, csv[r + 1] + (csv[-1] - csv[l]) - min(a, b))
    else:
      res = max(res, csv[r + 1] - csv[l] - s[r][0])
print(res)

Submission status: Wrong Answer

Solution code:
#lの位置は線形探索、rの位置はさぶたん
N, C = map(int, input().split())
#s = [list(map(int, input().split())) for _ in range(N)]
s = [[i, i + 1] for i in range(1, N + 1)]
csv = [0] * (N + 1)
s.sort()
for i in range(N):
  csv[i + 1] = csv[i] + s[i][1]
res = 0
for l in range(N):
  rlim = N - 1
  llim = 0
  x1 = (rlim - llim) // 3
  x2 = 2 * x1
  while x2 - x1 > 3:
    x1 = (rlim - llim) // 3 + llim
    x2 = 2 * (rlim - llim) // 3 + llim
    xres = [0, 0]
    i = 0
    #print(l, llim, x1, x2, rlim)
    for r in (x1, x2):
      if l > r:
        a = (C - s[l][0]) * 2 + s[r][0]
        b = (C - s[l][0]) + s[r][0] * 2
        xres[i] = csv[r + 1] + (csv[-1] - csv[l]) - min(a, b)
      else:
        xres[i] = csv[r + 1] - csv[l] - s[r][0]
      i += 1
    #print(xres)
    if xres[0] > xres[1]:
      res = max(xres[0], res)
      rlim = x2
    else:
      res = max(xres[1], res)
      llim = x1
  for r in range(llim, rlim + 1):
    if l > r:
      a = (C - s[l][0]) * 2 + s[r][0]
      b = (C - s[l][0]) + s[r][0] * 2
      res = max(res, csv[r + 1] + (csv[-1] - csv[l]) - min(a, b))
    else:
      res = max(res, csv[r + 1] - csv[l] - s[r][0])
print(res)

Submission status: Wrong Answer

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] - 2*XV[i][0]
    if ans < tmp + hidariM[N-1-i]:
        ans = tmp + hidariM[N-1-i]
        
tmp = 0
for i in range(N):
    tmp = tmp + XV[N-1-i][1] - 2*XV[N-1-i][0]
    if ans < tmp + migiM[N-1-i]:
        ans = tmp + migiM[N-1-i]
        
print(ans)

Submission status: Wrong Answer

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

ans1=max(max(L[i][0],L[i][0]+R[j][1]) for i in range(n) for j in range(n-i-1))
ans2=max(max(R[i][0],R[i][0]+L[j][1]) for i in range(n) for j in range(n-i-1))
print(max(ans1,ans2))

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
xvs = []
for i in range(N):
  x, v = map(int, input().split())
  xvs.append((x, v))
rs = []
cv = 0
for x, v in xvs:
  cv += v
  r = cv-x
  rs.append(r)
cv = 0
for x, v in reversed(xvs):
  cv += v
  r = cv-(C-x)
  rs.append(r)
r = max(rs)
print(r)

Submission status: Wrong Answer

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
A_max = [0] * N
A_max_d = [0] * N

a_max = 0
a_max_d = 0
for i in range(N):
  A[i] = sum(V[:i + 1]) - X[i]
  if A[i] > a_max:
    a_max = A[i]
    a_max_d = X[i]
  A_max_d[i] = a_max_d
  A_max[i] = a_max

b_sum = 0
m = max(0, A_max[-1])
for i in range(N - 1):
  b_sum += V[N - 1 - i]
  da = A_max_d[N - 2 - i]
  db = C - X[N - 1 - i]
  s = b_sum - db + A_max[N - 2 - i]
  m = max(m, s - db, s - da)

print(m)

Submission status: Wrong Answer

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
A_max = [0] * N

for i in range(N):
  A[i] = sum(V[:i + 1]) - X[i]
  A_max[i] = max(A)

b_sum = 0
m = max(0, A_max[-1])
for i in range(N - 1):
  a_max = A_max[N - 2 - i]
  da = X[A_max.index(a_max)]
  b_sum += V[N - 1 - i]
  db = C - X[N - 1 - i]
  s = b_sum - db + a_max
  m = max(m, s - db, s - da)

print(m)

Submission status: Wrong Answer

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([0]+nt_callory, max))
    # 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([0]+rnt_callory, max))
    # print(rnt_callory)
    # print(rnt_callory_acc)

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

    # 反時計回り
    for i in range(N-1):
        # i番目でターン
        callory = max(rnt_callory[i]-rnt_cost[i]+nt_callory_acc[N-i-1],
                      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: Wrong Answer

Solution code:
def solve(c, sushis):
    return solve_one_direction(c, sushis, True)
    # counter = solve_one_direction(c, sushis[::-1], False)
    # return max(clockwise, counter)

def solve_one_direction(c, sushis, clockwise=True, already_turn=False):
    total_v = 0
    max_v = 0
    for i, sushi in enumerate(sushis):
        total_v += sushi[1]
        x = sushi[0] if clockwise else c - sushi[0]
        v = total_v - x
        if max_v < v:
            max_v = v
        if not already_turn and x <= c / 2:
            rev = v - x + solve_one_direction(c, sushis[i + 1::][::-1], not clockwise, True)
            if max_v < rev:
                max_v = rev

    return max_v


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: Wrong Answer

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)
				
	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: Wrong Answer

Solution code:
n, c = map(int, input().split())
location_power = []
cum = [0]
for _ in range(n):
    location_power.append([int(i) for i in input().split()])
for i in range(n):
    cum.append(cum[i] + location_power[i][1] - location_power[i][0])
print(max(cum))

Submission status: Wrong Answer

Solution code:
#ABC095-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n,c=IL()
Sushi=[IL() for i in range(n)]
inf=float("INF")
E=[0]+[-inf for i in range(n)]
e=0
for i in range(n):
    x,v=Sushi[i]
    e+=v
    E[i+1]=max(E[i],E[i+1],e-x)
ans=E[n]
e=0
for i in range(n):
    x,v=Sushi[-i-1]
    e+=v
    ans=max(ans,e-2*(c-x)+E[-i-2])

for i in range(n):
    Sushi[i][0]=c-Sushi[i][0]
Sushi.sort()

E=[0]+[-inf for i in range(n)]
e=0
for i in range(n):
    x,v=Sushi[i]
    e+=v
    E[i+1]=max(E[i],E[i+1],e-x)

e=0
for i in range(n):
    x,v=Sushi[-i-1]
    e+=v
    ans=max(ans,e-2*(c-x)+E[-i-2])
print(max(0,ans))

Submission status: Wrong Answer

Solution code:
#ABC095-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n,c=IL()
Sushi=[IL() for i in range(n)]
inf=float("INF")
E=[0]+[-inf for i in range(n)]
e=0
for i in range(n):
    x,v=Sushi[i]
    e+=v
    E[i+1]=max(E[i],E[i+1],e-x)
ans=E[n]
e=0
for i in range(n):
    x,v=Sushi[-i-1]
    e+=v
    ans=max(ans,e-2*(c-x)+E[-i-2])

for i in range(n):
    Sushi[i][0]=c-Sushi[i][0]
Sushi.sort()

E=[0]+[-inf for i in range(n)]
e=0
for i in range(n):
    x,v=Sushi[i]
    e+=v
    E[i+1]=max(E[i],E[i+1],e-x)

e=0
for i in range(n):
    x,v=Sushi[-i-1]
    e+=v
    ans=max(ans,e-2*(c-x)+E[-i-2])
print(ans)

Submission status: Wrong Answer

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][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: Wrong Answer

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 = clockwise_dp[N-1][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: Wrong Answer

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

clockwise = [0] + [v[1] - v[0] for v in XV]
counterclockwise = [0] + [v[1] - (C-v[0]) for v in XV]
print(clockwise, counterclockwise)
clockwise = np.cumsum(clockwise)
counterclockwise = np.cumsum(counterclockwise)
cl = list(clockwise[:2])
for i in range(2, N+1):
    cl.append(clockwise[i]+XV[i-2][0])

ccl = list(counterclockwise[:2])
for i in range(2, N+1):
    ccl.append(counterclockwise[i]+XV[i-2][0])

print(cl, ccl)
ans = 0
for i in range(1, (N+1)//2+1):
    ans = max(ans, cl[i], ccl[i], cl[i] + ccl[i])
    print(ans)

print(ans)
"""

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

F = [0]
for i in range(N):
    f_new = F[-1] + XV[i][1]
    F.append(f_new)

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

F_counter = [0]
for i in range(N):
    f_new = F_counter[-1] + XV[-(i+1)][1]
    F_counter.append(f_new)

ans = 0
#print(F_counter, G)
for i in range(N):
    if i == 0:
        cur1 = G[N-i]
        cur2 = G[i]
    else:
        cur1 = - 2 * (C-XV[-i][0]) + F_counter[i] + G[N-i]
        cur2 = -XV[i][0] + F_counter[N-i] + G[i]
        #print(ans, cur1, cur2, F_counter[i], G[N-(i+1)])
    ans = max(ans, cur1, cur2)

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    x = [0] + x
    v = [0] + v
    bi = []
    best = -float('inf') 
    besti = -1
    acc_v = list(accumulate(v, lambda acc, vv: acc + vv))
    for ii, (xx, vv) in enumerate(zip(x, acc_v)):
        if best < vv - xx:
            besti = ii
            best = vv - xx
        bi.append(besti)

    ret = 0
    for b in range(len(bi) - 1, -1, -1):
        a = bi[b - 1]
        ca = max(0, acc_v[a] - x[a])
        cb = max(0, (acc_v[-1] - acc_v[b-1]) - ((C - x[b])) % C)
        c = ca + cb
        if 0 < ca and 0 < cb:
            c -= min(x[a], ((C - x[b]) % C))
        if ret < c:
            ret = c
    return ret

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))
    result = solve(N, C, x, v)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    x = [0] + x
    v = [0] + v
    bi = []
    best = -float('inf') 
    besti = -1
    acc_v = list(accumulate(v, lambda acc, vv: acc + vv))
    for ii, (xx, vv) in enumerate(zip(x, acc_v)):
        if best < vv - xx:
            besti = ii
            best = vv - xx
        bi.append(besti)

    ret = 0
    for b in range(len(bi)):
        a = bi[b - 1]
        ca = max(0, acc_v[a] - x[a])
        cb = max(0, (acc_v[-1] - acc_v[b-1]) - ((C - x[b])) % C)
        c = ca + cb
        if 0 < ca and 0 < cb:
            c -= min(x[a], ((C - x[b]) % C))
        if ret < c:
            ret = c
    return ret

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))
    result = solve(N, C, x, v)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    x = x
    v = v
    bi = []
    best = -float('inf') 
    besti = -1
    acc_v = list(accumulate(v, lambda acc, vv: acc + vv))
    for ii, (xx, vv) in enumerate(zip(x, acc_v)):
        if best < vv - xx:
            besti = ii
            best = vv - xx
        bi.append(besti)

    ret = 0
    for b in range(len(bi)):
        a = bi[b - 1]
        ca = max(0, acc_v[a] - x[a])
        cb = max(0, (acc_v[-1] - acc_v[b-1]) - (C - x[b]))
        c = ca + cb
        if 0 < ca and 0 < cb:
            c -= min(x[a], (C - x[b]))
        if ret < c:
            ret = c
    return ret

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))
    result = solve(N, C, x, v)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()