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: Time Limit Exceeded

Solution code:
N,C=[int(i) for i in input().split()]
x,v=[[],[]]
for i in range(N): 
	data=input().split()
	x.append(int(data[0]))
	v.append(int(data[1]))
Er=[sum([v[j] for j in range(i+1)])-x[i] for i in range(N)]
El=[sum([v[j] for j in range(i,N)])-C+x[i] for i in range(N)]
Elrback=[El[j]+max([Er[i]-x[i] for i in range(j)]+[0]) for j in range(N)]
Erlback=[Er[j]+max([El[i]-C+x[i] for i in range(j+1,N)]+[0]) for j in range(N)]
print(max(0,max(Elrback),max(Erlback), max(Er), max(El)))

Submission status: Time Limit Exceeded

Solution code:
n, c = map(int, input().split())
xv = [[int(x) for x in input().split()] for _ in range(n)]
n += 1
oa = [0] * n
ob = [0] * n
xv.insert(0, [0, 0])
maxcal = 0
for i in range(1,n):
    oa[i] = oa[i-1] + xv[i][1]
ob[n-1] = xv[i][1]
for i in reversed(range(0,n-1)):
    ob[i] = xv[i][1] + ob[i+1]
for i in range(n):
    for j in range(n):
        cal = oa[i]
        d = 0
        if i != j:
            cal += ob[j]
            d = xv[i][0] * 2 + (c - xv[j][0])
            d2 = xv[i][0] + (c - xv[j][0]) * 2
            d = min(d, d2)
        else:
            d = xv[i][0]
        if d < c:
            maxcal = max(maxcal, cal - d)
print(maxcal)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, c = map(int, input().split())
x_cw = np.empty(n)
v = np.empty(n)

for i in range(n):
    x_cw[i], v[i] = map(int, input().split())
    
x_ccw = c - x_cw[::-1]
sv_cw = v.cumsum() - x_cw
sv_ccw = v[::-1].cumsum() - x_ccw

imax = sv_cw.argmax()
ans = 0
for i in range(imax+1):
    if i == n-1:
        ans = max(ans, sv_cw[i])
    elif i == n-2:
        ans = max(ans, sv_cw[i] + max(0, (sv_ccw-x_ccw)[:n-i-1]))
    else:
        ans = max(ans, sv_cw[i] + max(0, (sv_ccw-x_ccw)[:n-i-1].max()))

imax = sv_ccw.argmax()
for i in range(imax+1):
    if i == n-1:
        ans = max(ans, sv_ccw[i])
    elif i == n-2:
        ans = max(ans, sv_ccw[i] + max(0, (sv_cw-x_cw)[:n-i-1]))
    else:
        ans = max(ans, sv_ccw[i] + max(0, (sv_cw-x_cw)[:n-i-1].max()))
        
print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
n, c = map(int, input().split())
xv = [[int(x) for x in input().split()] for _ in range(n)]
n += 1
xv.insert(0, [0, 0])
maxcal = 0

for i in range(n):
    for j in range(n):
        cal = 0
        d = 0
        for k in range(0, i + 1):
            cal += xv[k][1]
        if i != j:
            for k in range(j, n):
                cal += xv[k][1]
            d = xv[i][0] * 2 + (c - xv[j][0])
            d2 = xv[i][0] + (c - xv[j][0]) * 2
            d = min(d, d2)
        else:
            d = xv[i][0]
        if d < c:
            maxcal = max(maxcal, cal - d)
print(maxcal)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

# 右行って左に引き返す

a_list = [0]

for i in range(0, len(v_list)):
    if i > 0:
        l = a_list[i] + v_list[i] - (x_list[i] - x_list[i - 1])
        a_list.append(l)
    elif i == 0:
        l = v_list[i] - (x_list[i])
        a_list.append(l)

a_accum_max = [max(a_list[:x+1]) for x in range(0, len(a_list))]


b_list = [0]

for i in reversed(range(0, len(v_list))):
    if i == N-1:
        l = v_list[i] - 2 * (C - x_list[i])
        b_list.append(l)
    elif i < N-1:
        l = b_list[N - i - 1] + v_list[i] - 2 * (x_list[i+1] -x_list[i])
        b_list.append(l)

first_list = []
for i in range(0, len(b_list)):
    first_list.append(a_accum_max[N-i] + b_list[i])

max_fir = max(first_list)

# 左行って右に引き返す

c_list = [0]

for i in range(0, len(v_list)):
    if i > 0:
        l = c_list[i] + v_list[i] - 2 * (x_list[i] - x_list[i - 1])
        c_list.append(l)
    elif i == 0:
        l = v_list[i] - 2 * (x_list[i])
        c_list.append(l)

c_accum_max = [max(c_list[:x+1]) for x in range(0, len(c_list))]

d_list = [0]

for i in reversed(range(0, len(v_list))):
    if i == N-1:
        l = v_list[i] - (C - x_list[i])
        d_list.append(l)
    elif i < N-1:
        l = d_list[N - i - 1] + v_list[i] - (x_list[i+1] -x_list[i])
        d_list.append(l)

second_list = []
for i in range(0, len(d_list)):
    second_list.append(c_accum_max[N-i] + d_list[i])

max_sec = max(second_list)
max_num = max([max_fir, max_sec, 0])
print(max_num)

Submission status: Time Limit Exceeded

Solution code:
#!python
# -*- coding: utf-8 -*-


N, C = list(map(int, input().split(' ')))
X = []
V = []
for n in range(N):
    X_, V_ = list(map(int, input().split(' ')))
    X.append(X_)
    V.append(V_)

P = [0] + X + [C]

R_sushi_sum = [0]
L_sushi_sum = [0]
for i in range(N):
    R_sushi_sum.append(V[i] + R_sushi_sum[i])
    L_sushi_sum.append(V[-1 - i] + L_sushi_sum[i])

ANS = 0

for a in range(len(P) - 1):
    OA = P[a]
    SUSHI = R_sushi_sum[a]
    v = SUSHI - OA
    ANS = max(ANS, v)

for b in range(len(P) - 1):
    OB = C - P[-1 - b]
    SUSHI = L_sushi_sum[b]
    v = SUSHI - OB
    ANS = max(ANS, v)

for a in range(len(P) - 1):
    for b in range(a + 1, len(P) - 1):
        OA = P[a]
        OB = C - P[b]
        SUSHI = R_sushi_sum[a] + L_sushi_sum[len(P) - 1 - b]
        v_a = SUSHI - (OA * 2 + OB)
        v_b = SUSHI - (OA + OB * 2)
        ANS = max(ANS, v_a, v_b)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
def solve(sushi, n, c):
    max_val = -1
    for last_cw in xrange(n):
        for last_ccw in xrange(last_cw + 1, n):
            cw_value = sublist_cw[last_cw]
            ccw_value = sublist_ccw[last_ccw]
            walking = min(sushi[last_cw][0] * 2 + (c - sushi[last_ccw][0]),
                          (c - sushi[last_ccw][0]) * 2 + sushi[last_cw][0])
            val = cw_value + ccw_value - walking
            if val > max_val:
                max_val = val

    # no cw
    for last_ccw in xrange(n):
        ccw_value = sublist_ccw[last_ccw]
        walking = c - sushi[last_ccw][0]
        val = ccw_value - walking
        if val > max_val:
            max_val = val

    #no ccw
    for last_cw in xrange(n):
        cw_value = sublist_cw[last_cw]
        walking = sushi[last_cw][0]
        val = cw_value - walking
        if val > max_val:
            max_val = val

    return max(max_val, 0)


n,c  = map(int, raw_input().split())
sushi = []
for _ in xrange(n):
    sushi.append(tuple(map(int, raw_input().split())))

sublist_cw = [sushi[0][1]]
for i in xrange(1, len(sushi)):
    sublist_cw.append(sublist_cw[-1] + sushi[i][1])

sublist_ccw = [sushi[-1][1]]
for i in xrange(len(sushi) - 2, -1, -1):
    sublist_ccw.insert(0, sublist_ccw[0] + sushi[i][1])

print solve(sushi, n, c)

Submission status: Time Limit Exceeded

Solution code:
nc = list(map(int,input().split()))
xv = []
for i in range(nc[0]):
    xv.append(list(map(int, input().split())))

cal1 = [xv[0][1] - xv[0][0]]
for i in range(1, nc[0]):
    cal1.append(cal1[i - 1] + xv[i][1] - (xv[i][0] - xv[i - 1][0]))
cal1 = max(cal1)

cal2 = [xv[-1][1] - (nc[1] - xv[-1][0])]
for i in range(1, nc[0]):
    cal2.append(cal2[i - 1] + xv[nc[0] - i - 1][1] - (xv[nc[0] - i][0] - xv[nc[0] - i - 1][0]))
cal2 = max(cal2)

cal3 = [[0 for i in range(nc[0])] for j in range(nc[0])]
cal_r = [0]
for i in range(nc[0]):
    cal_r.append(cal_r[i] + xv[i][1])
cal_l = [0]
for i in range(nc[0]):
    cal_l.append(cal_l[i] + xv[- i - 1][1])
for i in range(nc[0]):
    for j in range(nc[0] - i - 1):
        cal3[i][j] = cal_r[i + 1] + cal_l[j + 1] - xv[i][0] * 2 - (nc[1] - xv[- j - 1][0])
cal3 = max(max(i) for i in cal3)

cal4 = [[0 for i in range(nc[0])] for j in range(nc[0])]
for i in range(nc[0]):
    for j in range(nc[0] - i - 1):
        cal4[i][j] = cal_l[i + 1]+ cal_r[j + 1] - (nc[1] - xv[- i - 1][0]) * 2 - xv[j][0]
cal4 = max(max(i) for i in cal4)
cal = max(cal1, cal2, cal3, cal4, 0)
print(cal)

Submission status: Time Limit Exceeded

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


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

x=[0]+x
v=[0]+v

Cal=[0 for i in range((N+2)**2)]
ind=0

for R in range(N+1):
    for L in range(N-R+1):
        if R==0:
            CalR=0
        else:
            CalR=sum(v[:R+1])-x[R]
        
        if L==0:
            CalL=0
            d=0
        else:
            CalL=sum(v[N-L+1:])-(C-x[N-L+1])
            d=C-x[N-L+1]
        
        Cal[ind]=max(CalR+CalL-x[R],CalR+CalL-d)
        ind=ind+1

print(max(Cal))

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())
xv = [list(map(int, input().split())) for _ in range(N)]
xv_rev = list(reversed(xv))
xv = [[0,0]]+xv
xv_rev = [[0,0]] + xv_rev
for i in range(1,N+1):
    xv[i] = [xv[i][0],xv[i-1][1]+xv[i][1]+xv[i-1][0]-xv[i][0]]
    xv_rev[i] = [C-xv_rev[i][0],xv_rev[i-1][1]+xv_rev[i][1]+xv_rev[i-1][0]-(C-xv_rev[i][0])]

right = max(xv,key=lambda x:x[1])
left = max(xv_rev,key=lambda x:x[1])
both = 0

for i in range(N+1):
    for j in range(N+1-i):
        both = max(both,xv[i][1]+xv_rev[j][1]-min(xv[i][0],xv_rev[j][0]))

print(max(right[1],left[1],both))

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())
xs = []
vs = []
for i in range(N):
    x, v = map(int, input().split())
    xs += [x]
    vs += [v]

sumVtos = [vs[0]]
for i in range(1, N):
    sumVtos += [sumVtos[-1] + vs[i]]

sumV = sumVtos[-1]
sumVfrs = [sumV]
for i in range(1, N):
    sumVfrs += [sumVfrs[-1] - vs[i - 1]]

# 初手：時計回り
ans = 0
for i in range(N):
    ans1 = sumVtos[i] - xs[i]

    # 2手目：反時計回り
    ans2 = 0
    for j in range(i + 1, N):
        ans2 = max(ans2, sumVfrs[j] - (xs[i] + C - xs[j]))

    ans = max(ans, ans1 + ans2)

# 初手：反時計回り
for i in range(N):
    ans1 = sumVfrs[i] - (C - xs[i])

    # 2手目：時計回り
    ans2 = 0
    for j in range(i):
        ans2 = max(ans2, sumVtos[j] - (C - xs[i] + xs[j]))

    ans = max(ans, ans1 + ans2)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())
sushi_m_kcal = []
for i in range(N):
    sushi_m_kcal.append(list(map(int, input().split())))
sorted_sushi = sorted(sushi_m_kcal)
reversed_sushi = sorted(sushi_m_kcal, reverse=True)
sorted_result = []
reversed_result = []
for i in range(N):
    sorted_kcal = 0
    reversed_kcal = 0
    for j in range(-i, N - i):
        sorted_kcal += sorted_sushi[j][1]
        reversed_kcal += reversed_sushi[j][1]
        if i != 0:
            sorted_result.append(sorted_kcal - sorted_sushi[j][0] + 2 * (sorted_sushi[-i][0] - C))
            reversed_result.append(reversed_kcal - C + reversed_sushi[j][0] - 2 * reversed_sushi[-i][0])
        else:
            sorted_result.append(sorted_kcal - sorted_sushi[j][0])
            reversed_result.append(reversed_kcal - C + reversed_sushi[j][0])

print(max(0, max(sorted_result), max(reversed_result)))

Submission status: Time Limit Exceeded

Solution code:
n,c= [int(i) for i in input().split()]
t_tk_r=0
t_md_r=0
g_tk_r=0
g_md_r=0
t_tk=[]
t_md=[]
g_tk=[]
g_md=[]
a=[]
d1=0
for i in range(n):
  a.append([int(i) for i in input().split()])
for d0,v0 in a:
  t_tk_r+=v0-(d0-d1)
  t_md_r+=v0-(d0-d1)*2
  t_tk.append(t_tk_r)
  t_md.append(t_md_r)
  d1=d0
d1=0  
for d0,v0 in a[::-1]:
  g_tk_r+=v0-((c-d0)-d1)
  g_md_r+=v0-((c-d0)-d1)*2
  g_tk.append(g_tk_r)
  g_md.append(g_md_r)
  d1=(c-d0)
  
mx=max(max(t_tk),max(g_tk),0)
for i in range(1,n):
  mx=max(mx,max(t_tk[:i])+max(g_md[:n-i]),max(t_md[:i])+max(g_tk[:n-i]))
print(mx)

Submission status: Time Limit Exceeded

Solution code:
N, C = map(int, input().split())
xs = []
vs = []
for i in range(N):
    x, v = map(int, input().split())
    xs += [x]
    vs += [v]

# 初手：時計回り
ans = 0
for i in range(N):
    ans1 = sum(vs[:i + 1]) - xs[i]

    # 2手目：反時計回り
    ans2 = 0
    for j in range(i + 1, N):
        ans2 = max(ans2, sum(vs[j:]) - (xs[i] + C - xs[j]))

    ans = max(ans, ans1 + ans2)

# 初手：反時計回り
for i in range(N):
    ans1 = sum(vs[i:]) - (C - xs[i])

    # 2手目：時計回り
    ans2 = 0
    for j in range(i):
        ans2 = max(ans2, sum(vs[:j + 1]) - (C - xs[i] + xs[j]))

    ans = max(ans, ans1 + ans2)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,C = map(int, input().split())
dis = []
cal = []
for i in range(N):
    x,v = map(int, input().split())
    dis.append(x)
    cal.append(v)
r = [cal[0] - dis[0]]
for i in range(N-1):
    r.append(r[i] + dis[i] + cal[i+1] - dis[i+1])
l = [cal[-1] - (C - dis[-1])]
for i in range(N-1):
    l.append(l[i] - dis[-i-1] + cal[-i-2] + dis[-i-2])
r2 = [0]
l2 = [0]
for i in range(N):
    r2.append(r[i] - dis[i])
    l2.append(l[i] - (C - dis[-i-1]))
for i in range(N-1):
    r[i] = r[i] + max(l2[:-i-1])
    l[i] = l[i] + max(r2[:-i-1])
print(max(0,max(r),max(l)))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

line = input().split(" ")
n = int(line[0])
c = int(line[1])

sushi = []
for _ in range(n):
    line = input().split(" ")
    sushi.append([int(line[0]), int(line[1])]) #[x,v]

ret = 0

r1 = []
r2 = []
state = 0
for i in range(n):
    s = sushi[i]
    state += s[1]
    r1.append(state-2*s[0])
    r2.append(state-s[0])
    if state-s[0]>ret:
        ret = state-s[0]

l1 = []
l2 = []
state = 0
for i in range(n-1,-1,-1):
    s = sushi[i]
    state += s[1]
    l1.append(state-2*(c-s[0]))
    l2.append(state-(c-s[0]))
    if state-(c-s[0])>ret:
        ret = state-(c-s[0])

for (i,r) in enumerate(r1):
    for (j,l) in enumerate(l2):
        if i+j+2>n:
            continue
        if r+l>ret:
            ret = r+l

for (i,l) in enumerate(l1):
    for (j,r) in enumerate(r2):
        if i+j+2>n:
            continue
        if r+l>ret:
            ret = r+l


print(ret)

Submission status: Time Limit Exceeded

Solution code:
tmp = list(map(int, input().split()))
n,c = tmp[0],tmp[1]
xs, vs = [0],[]
ans = [0]
for i in range(n):
    tmp = list(map(int, input().split()))
    xs.append(tmp[0])
    vs.append(tmp[1])
xs_rev, vs_rev = [0],[]
for i in range(n):
    xs_rev.append(c-xs[-(i+1)])
    vs_rev.append(vs[-(i+1)])
def findmax(v_data,x_data,m,mode = True):
    vs1 = [0]
    for i in range(m):
        if mode:
            vs1.append(vs1[-1] + v_data[i] - x_data[i+1] + x_data[i])
        else:
            vs1.append(vs1[-1] + v_data[i] - x_data[i+1] * 2 + x_data[i] * 2)
    return(max(vs1))
ans.append(findmax(vs,xs,n))
ans.append(findmax(vs_rev,xs_rev,n))
sumv = []
for i in range(0,n):
    sumv.append(findmax(vs[:i],xs[:i+1],i) + findmax(vs_rev[:n-i],xs_rev[:n-i+1],n-i,mode = False))
if sumv != []:
    ans.append(max(sumv))
sumv = []
for i in range(0,n):
    sumv.append(findmax(vs[:i],xs[:i+1],i,mode = False) + findmax(vs_rev[:n-i],xs_rev[:n-i+1],n-i))
if sumv != []:
    ans.append(max(sumv))
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
def eval_cal(x,v,n):
    tmp=0
    maxtotal=0
    for i in range(n):
        if i ==0:
            dis=abs(x[0])
        else :
            dis=x[i]-x[i-1]
    
        tmp+=v[i]-dis
        #print(tmp)
        if tmp > maxtotal:
            maxtotal=tmp
    return maxtotal

n, c = map(int,input().split(' '))
x=[]
v=[]
for i in range(n):
    xt,vt = map(int,input().split(' '))
    x.append(xt)
    v.append(vt)

maxtotal=0
#時計回りの場合
for i in range(n,0,-1):
    if i < n:
        x.insert(0,x[n-1]-c)
        v.insert(0,v[n-1])
    tmp=eval_cal(x,v,n)
    if tmp > maxtotal:
        maxtotal=tmp

#反時計回りの場合
#設定
x.reverse()
v.reverse()
for i in range(n):
    x[i]=c-x[i]

for i in range(n,0,-1):
    if i < n:
        x.insert(0,x[n-1]-c)
        v.insert(0,v[n-1])
    tmp=eval_cal(x,v,n)
    if tmp > maxtotal:
        maxtotal=tmp

print(maxtotal)

Submission status: Time Limit Exceeded

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

def solve():
    # 時計回り進むだけ
    right_cal = []
    walked = 0
    sum_cal = 0
    for i in range(len(sushi)):
        now_cal = sushi[i][1]
        right_cal.append(now_cal + sum_cal - sushi[i][0])
        sum_cal += now_cal

    # 時計回り折り返し
    right_cal_r = []
    walked = 0
    sum_cal = 0
    for i in range(len(sushi)):
        now_cal = sushi[i][1]
        right_cal_r.append(now_cal + sum_cal - sushi[i][0]*2)
        sum_cal += now_cal


    # 反時計回り
    left_cal = []
    walked = 0
    sum_cal = 0
    for i in range(len(sushi)):
        left_index = len(sushi)-i-1
        now_cal = sushi[left_index][1]
        left_cal.append(now_cal + sum_cal - (C - sushi[left_index][0]))
        sum_cal += now_cal

    # 反時計回り折り返し
    left_cal_r = []
    walked = 0
    sum_cal = 0
    for i in range(len(sushi)):
        left_index = len(sushi)-i-1
        now_cal = sushi[left_index][1]
        left_cal_r.append(now_cal + sum_cal - (C - sushi[left_index][0])*2)
        sum_cal += now_cal

    #反時計周り→時計回りの場合
    left_right_cal = [max(left_cal)]
    for i in range(N):
        if N - i - 1 > 0:
            left_right_cal.append(right_cal_r[i] + max(left_cal[:N - i - 1]))
    #時計周り→反時計回りの場合
    right_left_cal = [max(right_cal)]
    for i in range(N):
        if N - i - 1 > 0:
            right_left_cal.append(left_cal_r[i] + max(right_cal[:N - i - 1]))

    print(max(max(left_right_cal), max(right_left_cal), 0))

if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def back(sushi, c, p, end):
    p += c
    h = 0
    buf = 0
    for i in range(len(sushi) - 1, end, -1):
        x, v = sushi[i]
        d = p - x
        if d < v + buf:
            h += buf + v - d
            p = x
            buf = 0
        else:
            buf += v
    return h


def forw(sushi, c, p, end):
    p -= c
    h = 0
    buf = 0
    for i in range(0, end, 1):
        x, v = sushi[i]
        d = x - p
        if d < v + buf:
            h += buf + v - d
            p = x
            buf = 0
        else:
            buf += v
    return h


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

    best_h = 0
    h = 0
    p = 0
    buf = 0
    for i in range(n):
        x, v = sushu[i]
        d = x - p
        if d < v + buf:
            h += buf + v - d
            p = x
            buf = 0
            hh = h + back(sushu, c, p, i)
            best_h = max(best_h, hh)
        else:
            buf += v
    h = 0
    p = c
    buf = 0
    for i in range(n - 1, -1, -1):
        x, v = sushu[i]
        d = p - x
        if d < v + buf:
            h += buf + v - d
            p = x
            buf = 0
            hh = h + forw(sushu, c, p, i)
            best_h = max(best_h, hh)
        else:
            buf += v

    print(best_h)


main()

Submission status: Time Limit Exceeded

Solution code:
from numpy import *
n,c = (int(i) for i in input().split())  
xs = []
ys = []

for j in range(n):
  x,y = (int(i) for i in input().split())  
  xs.append(x)
  ys.append(y)
left = [[0,0]]
right = [[0,0]]
for j in range(n):
  left.append([left[-1][0]+ys[j]-(xs[j]-left[-1][1]),xs[j]])

for j in range(n)[::-1]:
  right.append([right[-1][0]+ys[j]-(right[-1][1]+c-xs[j]),xs[j]-c])
anss = []
anss.append(max(l[0] for l in right))
anss.append(max(l[0] for l in left))

for i in range(1,n):
  anss.append(left[i][0]-xs[i-1]+max(l[0] for l in right[1:-i]))
for i in range(1,n):
  anss.append(right[i][0]+right[i][1]+max(l[0] for l in left[1:-i]))
print(max(anss))

Submission status: Time Limit Exceeded

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

def solve(C, xv):
    
    N = len(xv)

    def mk(xv):
        ts = []
        t = 0
        for i, _ in enumerate(xv):
            x, v = _
            t += v
            ts.append((t - x, x, i))
        return ts        

    ts1 = mk(xv)
    ts2 = mk([(C - x, v) for x, v in xv[::-1]])

    result = 0

    for i in range(N):
        r0 = ts1[i][0]
        result = max(result, r0)
        for j in range(N - i - 1):
            r = r0 + ts2[j][0] - ts2[j][1]
            result = max(result, r)

    for i in range(N):
        r0 = ts2[i][0]
        result = max(result, r0)
        for j in range(N - i - 1):
            r = r0 + ts1[j][0] - ts1[j][1]
            result = max(result, r)

    return result
    
print(solve(C, xv))

Submission status: Time Limit Exceeded

Solution code:
import random


def slv(N, C, X, V):
    # cal_l = 0
    # move = 0
    # for x, v in zip(X, V):
    #     if x-move > v:
    #         break
    #     cal_l += v
    #     move = x
    # cal_l -= move

    # cal_r = 0
    # move = 0
    # tmp =list(zip(X, V))
    # for x, v in tmp[::-1]:
    #     if (C-x)-move > v:
    #         break
    #     cal_r += v
    #     move = C - x
    # cal_r -= move

    # print(cal_l, cal_r)

    ans_l = [(0, 0)]
    for x, v in zip(X, V):
        ans_l.append((x, ans_l[-1][1] + v))

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


    ans_l_r = []
    for i, a in enumerate(ans_l):
        tmp = 0
        for b in ans_r[:-i]:
            c = a[1] + b[1] - 2*a[0] - b[0]
            tmp = max(tmp, c)
        ans_l_r.append( tmp)
    ans_r_l = []
    for i, a in enumerate(ans_r):
        tmp = 0
        for b in ans_l[:-i]:
            c = a[1] + b[1] - 2*a[0] - b[0]
            tmp = max(tmp, c)
        ans_r_l.append( tmp)

    
    # print(ans_l)
    # print(ans_r)
    l = max([x[1]-x[0] for x in ans_l])
    r = max([x[1]-x[0] for x in ans_r])
    lr = max(ans_l_r)
    rl = max(ans_r_l)


    return max(l, r, lr, rl)



def main():
    N, C = list(map(int, input().split()))
    X = []
    V = []
    for _ in range(N):
        x, v = list(map(int, input().split()))
        X.append(x)
        V.append(v)
    print(slv(N, C, X, V))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

c1 = []
c2 = []
cumv = 0
for x,v in src:
    cumv += v
    c1.append(cumv - x)
    c2.append(cumv - 2*x)

r1 = []
r2 = []
cumv = 0
for x,v in reversed(src):
    cumv += v
    x = C-x
    r1.append(cumv - x)
    r2.append(cumv - 2*x)

ans = max(c1+r1+[0])
for i,c in enumerate(c2):
    for r in r1[:N-i-1]:
        ans = max(ans, c+r)
for i,r in enumerate(r2):
    for c in c1[:N-i-1]:
        ans = max(ans, c+r)

print(ans)

Submission status: Accepted

Solution code:
"""
カウンターの回り方はパターンが多すぎるので、考えない方がよい。
考え方１：
残っている寿司のうち、そこにたどり着くまでのエネルギー <= そこにたどり着くまでに摂取できる寿司のカロリー
となるような寿司があるかどうか。


考え方２：
二分探索。
X以上カロリーを得できるか、という二分探索。

考え方３：
動き方のパターンは4つある。
時計回りに動いて、どこかのタイミングで退店
半時計周りに動いて、どこかのタイミングで退店
時計回りに動いた後、反時計回りに動いて退店
反時計回りに動いた後、時計回りに動いて退店
それぞれのパターンで動く場合の最大価値を求める。
これで行こう
"""

N,C = map(int,input().split())
#sushi[i] => スタート地点から時計回りに動いたときにi番目にある寿司の情報
#sushiR[i] => スタート地点から反時計回りに動いたときにi番目にある寿司の情報
sushi = []
sushiR = []
for _ in range(N):
    x,v = map(int,input().split())
    sushi.append([x,v])
    sushiR.append([C-x,v])
sushiR = sushiR[::-1]

ans = 0
"""
まずは時計回りに動いてどこかのタイミングで退店する場合を考える。
これは、時計回りに寿司を見て行って、各寿司にたどり着いた時の、摂取カロリーの累積和と消費カロリーを求めればよい。
"""

cal = 0
for x,v in sushi:
    cal += v
    ans = max(ans,cal-x)

"""
次に反時計回りに動いてどこかのタイミングで退店する場合を考える。
"""
cal = 0
for x,v in sushiR:
    cal += v
    ans = max(ans,cal-x)


"""
時計回りに動いた後、反時計回りに動いて退店する場合を考える。
これは、時計回りでどこまで動くか（つまりどこで折り返すか）で場合わけし、
各地点で折り返す場合に、反時計回りでどこまで行くのがベストなのかをaccumSushiRをつかって判断する
"""
from heapq import heappop,heappush
sushiRQue = []
cal = 0
for i in range(N):
    x,v = sushiR[i]
    cal += v
    heappush(sushiRQue,(-(cal-x),i))

cal = 0
for i in range(N-1):
    x,v = sushi[i]
    cal += v
    while sushiRQue[0][1]+i >= N-1:
        heappop(sushiRQue)
    ans = max(ans,cal-x*2+(-sushiRQue[0][0]))

"""
時計回りに動いた後、反時計回りに動いて退店する場合を考える。
これは、時計回りでどこまで動くか（つまりどこで折り返すか）で場合わけし、
各地点で折り返す場合に、反時計回りでどこまで行くのがベストなのかをaccumSushiRをつかって判断する
"""
sushiQue = []
cal = 0
for i in range(N):
    x,v = sushi[i]
    cal += v
    heappush(sushiQue,(-(cal-x),i))

cal = 0
for i in range(N-1):
    x,v = sushiR[i]
    cal += v
    while sushiQue[0][1]+i >= N-1:
        heappop(sushiQue)
    ans = max(ans,cal-x*2+(-sushiQue[0][0]))

print(ans)

Submission status: Accepted

Solution code:
n,c1 = map(int, input().split())
g = []
c = [0]
d = [0]
a = 0
ans=[]
m1=0
m2=0
for i in range(n):
  x,v = map(int, input().split())
  g.append([x,v])
  a+=v
  m1= max(a-x,m1)
  m2= max(a-2*x,m2)
  c.append(m1)
  d.append(m2)
b = 0
e = [0]
f = [0]
for i,j in reversed(g):
  b+=j
  e.append(b-(c1-i))
  f.append(b-2*(c1-i))
for i in range(n+1):
  ans.append(c[i]+f[-i-1])
  ans.append(d[i]+e[-i-1])
print(max(ans))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
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()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, C = MAP()
xv = [LIST() for _ in range(N)]

#左回り用
energy_left_1 = [0]
energy_left_2 = [0]
tmp_v = 0
for x, v in xv:
	tmp_v += v
	energy_left_1.append(tmp_v-x)
	energy_left_2.append(tmp_v-2*x)

#右周り用
energy_right_1 = [0]
energy_right_2 = [0]
tmp_v = 0 
for x, v in xv[::-1]:
	y = C-x
	tmp_v += v
	energy_right_1.append(tmp_v-y)
	energy_right_2.append(tmp_v-2*y)

energy_left_1_acc = list(accumulate(energy_left_1, max))
energy_left_2_acc = list(accumulate(energy_left_2, max))
energy_right_1_acc = list(accumulate(energy_right_1, max))
energy_right_2_acc = list(accumulate(energy_right_2, max))

ans = -INF
for i in range(N+1):
	ans = max(ans, energy_left_1_acc[i]+energy_right_2_acc[N-i])
	ans = max(ans, energy_left_2_acc[i]+energy_right_1_acc[N-i])
print(ans)

Submission status: Accepted

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

av = 0
fa1 = 0
bv = 0
fb1 = 0
fa = []
fb = []
ga = []
gb = []
for i in range(N):
    ax = xv[i][0]
    av += xv[i][1]
    bx = C - xv[-(i+1)][0]
    bv += xv[-(i+1)][1]
    fa1 = max(fa1, av-ax)
    fa.append(fa1)
    ga.append(av - 2*ax)
    fb1 = max(fb1, bv-bx)
    fb.append(fb1)
    gb.append(bv - 2*bx)

p = max(0, fa[-1], fb[-1])

for i in range(N-1):
    p = max(p, fa[i]+gb[N-i-2], ga[i]+fb[N-i-2])

print(p)

Submission status: Accepted

Solution code:
n,c = list(map(int,input().split()))
xv = [list(map(int,input().split())) for i in range(n)]

frontGet = [0]*n
frontRuiseki = [0]*(n+1)
backGet = [0]*n
backRuiseki = [0]*(n+1)

for i in range(n):
    frontRuiseki[i+1] = frontRuiseki[i]+xv[i][1] 
    frontGet[i] = frontRuiseki[i+1] - xv[i][0]
    idx = -1 - i
    backRuiseki[idx-1] = backRuiseki[idx]+xv[idx][1] 
    backGet[idx] = backRuiseki[idx-1] + xv[idx][0] - c

backGet.reverse()
frontGet = [0] + frontGet
backGet = [0] + backGet
xv = [[0,0]] + xv
frontMax = [0]*(n+1)
backMax = [0]*(n+1)

for i in range(n):
    frontMax[i+1] = max(frontMax[i],frontGet[i+1])
    backMax[i+1] = max(backGet[i+1],backMax[i])

ans = max(frontMax[-1],backMax[-1],0)
for i in range(n+1):
    front = frontGet[i] - xv[i][0]
    front += backMax[n - i]
    back = backGet[i] + xv[-i][0] - c
    back += frontMax[n - i]
    ans = max(ans,front,back)
print(ans)