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:
n, c = map(int, input().split())

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

normal = [s[0][1] - s[0][0]] # 
cur = normal[0]
n_max = max(0, normal[0])

for (s1_pos, s1_cal), (s2_pos, s2_cal) in zip(s, s[1:]):
    cur = cur + s2_cal - (s2_pos - s1_pos)
    if n_max < cur:
        n_max = cur
    normal.append(n_max)

reverse = [s[-1][1] - (c - s[-1][0])]
cur = reverse[0]
r_max = max(0, reverse[0])
         
for (s1_pos, s1_cal), (s2_pos, s2_cal) in zip(s[::-1], s[-2::-1]):
    cur = cur + s2_cal - (s1_pos-s2_pos)
    if r_max < cur:
        r_max = cur
    reverse.append(r_max)
         
res = 0
for i, (pos, cal) in enumerate(s[:-1]):
    res = max(res, normal[i], normal[i]-pos+reverse[n-2-i])
for i, (pos, cal) in enumerate(s[:0:-1]):
    res = max(res, reverse[i], reverse[i]-(c-pos)+normal[n-2-i])
res = max(res, normal[-1], reverse[-1])
         
print(res)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
xvs = [tuple(map(int, input().split())) for _ in range(n)]
mx1 = [0]
acc = 0
prv = 0
for x, v in xvs:
    acc += v - (x-prv)
    prv = x
    mx1.append(max(acc, mx1[-1]))
mx2 = [0]
acc = 0
prv = c
for x, v in xvs[::-1]:
    acc += v - (prv-x)*2
    prv = x
    mx2.append(max(acc, mx2[-1]))
ans1 = 0
for i in range(n+1):
    ans1 = max(ans1, mx1[n-i]+mx2[i])
mx1 = [0]
acc = 0
prv = 0
for x, v in xvs:
    acc += v - (x-prv)*2
    prv = x
    mx1.append(max(acc, mx1[-1]))
mx2 = [0]
acc = 0
prv = c
for x, v in xvs[::-1]:
    acc += v - (prv-x)
    prv = x
    mx2.append(max(acc, mx2[-1]))
ans2 = 0
for i in range(n+1):
    ans2 = max(ans2, mx1[n-i]+mx2[i])
print(max(ans1, ans2))

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X = []; V = []
for i in range(N):
    x, v = map(int, input().split())
    X.append(x); V.append(v)
P0 = []; P1 = []
ma0 = cu0 = ma1 = cu1 = 0
pos = 0
for i in range(N):
    cu0 += V[i]-(X[i]-pos)
    cu1 += V[i]-(X[i]-pos)*2
    ma0 = max(ma0, cu0)
    ma1 = max(ma1, cu1)
    P0.append(ma0)
    P1.append(ma1)
    pos = X[i]
Q0 = []; Q1 = []
ma0 = cu0 = ma1 = cu1 = 0
pos = C
for i in range(N):
    cu0 += V[-i-1]-(pos-X[-i-1])
    cu1 += V[-i-1]-(pos-X[-i-1])*2
    ma0 = max(ma0, cu0)
    ma1 = max(ma1, cu1)
    Q0.append(ma0)
    Q1.append(ma1)
    pos = X[-i-1]
ans = max(P0[N-1], Q0[N-1])
for i in range(N-1):
    ans = max(ans, P0[i] + Q1[-i-2], P1[-i-2] + Q0[i])
print(ans)

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)

gain_right = [0] * N
gain_right[0] = V[0] - X[0]
for i in range(1, N):
    gain_right[i] = gain_right[i-1] + V[i] - (X[i] - X[i-1])

gain_left = [0] * N  # 時計回りに並んでることに注意
gain_left[N-1] = V[N-1] - (C - X[N-1])
for i in reversed(range(N-1)):
    gain_left[i] = gain_left[i+1] + V[i] - (X[i+1] - X[i])

opt_right = [0] * N
opt_left = [0] * N

maxx = 0
maxx_idx = -1   # -1 は動かない
for i in range(N):
    if gain_right[i] > maxx:
        maxx = gain_right[i]
        maxx_idx = i
    opt_right[i] = maxx_idx

maxx = 0
maxx_idx = -1  # -1 は動かない
for i in reversed(range(N)):
    if gain_left[i] > maxx:
        maxx = gain_left[i]
        maxx_idx = i
    opt_left[i] = maxx_idx

# 左に行ってから右に行く場合
if opt_right[N-1] == -1:
    opt_cal = 0
else:
    opt_cal = gain_right[opt_right[N-1]]  # 全く左に行かないとき

for i in reversed(range(1, N)):
    cal = gain_left[i] - (C - X[i]) + gain_right[opt_right[i-1]]
    opt_cal = max(cal, opt_cal)

# 右に行ってから左に行く場合
# 全く右に行かないとき
if opt_left[0] == -1:
    opt_cal = max(opt_cal, 0)
else:
    opt_cal = max(gain_left[opt_left[0]], opt_cal)  # 全く右に行かないとき
for i in range(N-1):
    cal = gain_right[i] - X[i] + gain_left[opt_left[i+1]]
    opt_cal = max(cal, opt_cal)

print(opt_cal)

Submission status: Accepted

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]


fAs = [0] * N
fAs[0] = vs[0]
for A in range(1, N):
    fAs[A] = fAs[A - 1] + vs[A]
for A in range(N):
    fAs[A] -= xs[A]

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


fBs = [0] * N
fBs[N - 1] = vs[N - 1]
for B in range(0, N - 1)[::-1]:
    fBs[B] = fBs[B + 1] + vs[B]

for B in range(N):
    fBs[B] -= C - xs[B]

gBs = [0] * N
gBs[N - 1] = 0
for B in range(0, N - 1)[::-1]:
    gBs[B] = max(gBs[B + 1], fBs[B + 1])


ans = 0

# 初手：時計回り
for A in range(N):
    ans1 = fAs[A]

    # 2手目：反時計回り
    ans2 = max(0, gBs[A] - xs[A])

    ans = max(ans, ans1 + ans2)


# 初手：反時計回り
for B in range(N):
    ans1 = fBs[B]

    # 2手目：時計回り
    ans2 = max(0, gAs[B] - (C - xs[B]))

    ans = max(ans, ans1 + ans2)

print(ans)

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X, V = [], []
for i in range(N):
    xi, vi = map(int, input().split())
    X.append(xi)
    V.append(vi)

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

# 折り返さないパターン and 折り返してどこまでいくのか
r_straight = r_cal.copy()
l_straight = l_cal.copy()

for i in range(1, N+1):
    r_straight[i] -= X[i-1]
    l_straight[i] -= (C - X[N-i])

# 折り返すパターン
for i in range(1, N+1):
    r_cal[i] -= 2*X[i-1]
    l_cal[i] -= 2*(C - X[N-i])

# 折り返した後どこまで行くのが最適か
r_max = [0]
l_max = [0]
for i in range(1, N+1):
    r_max.append(max(r_max[-1], r_straight[i]))
    l_max.append(max(l_max[-1], l_straight[i]))

ans = max(r_max[-1], l_max[-1])
for i in range(N):
    ans = max(ans, r_cal[i] + l_max[N-i])
    ans = max(ans, l_cal[N-i] + r_max[i])
    
print(ans)

Submission status: Accepted

Solution code:
N, C = (int(i) for i in input().split())

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


l_cal = [0] * (N + 1)
r_cal = [0] * (N + 1)
l_cal[1] = V[1] - 2 * (X[1] - X[0])
r_cal[1] = V[-1] - 2 * (C - X[-1])
for i in range(2, N+1):
    l_cal[i] = l_cal[i-1] + V[i] - 2 * (X[i] - X[i-1])
    r_cal[i] = r_cal[i-1] + V[-i] - 2 * (X[-i+1] - X[-i])

l_max = [0] * (N + 1)
r_max = [0] * (N + 1)
for i in range(1, N+1):
    l_max[i] = max(l_max[i-1], l_cal[i])
    r_max[i] = max(r_max[i-1], r_cal[i])

l_ans = l_max[-1]
r_ans = r_max[-1]
for i in range(1, N+1):
    l_ans = max(l_ans, l_max[-1-i] + r_cal[i] + (C - X[-i]))
    r_ans = max(r_ans, r_max[-1-i] + l_cal[i] + X[i])
print(max(l_ans, r_ans))

Submission status: Accepted

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_m=0
t_md_m=0
g_tk_m=0
g_md_m=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_m = max(t_tk_m,t_tk_r)
  t_md_m = max(t_md_m,t_md_r)
  t_tk.append(t_tk_m)
  t_md.append(t_md_m)
  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_m = max(g_tk_m,g_tk_r)
  g_md_m = max(g_md_m,g_md_r)
  g_tk.append(g_tk_m)
  g_md.append(g_md_m)
  d1=(c-d0) 
mx=max(max(t_tk),max(g_tk),0)

for i in range(n-1):
  mx=max(mx,t_tk[i]+g_md[n-2-i],t_md[i]+g_tk[n-i-2])
print(mx)

Submission status: Accepted

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

# N,Cを取得
n, c = map(int, input().split())

# x1, v1..xN, vNを取得
xs = []
vs = []
for _i in range(n):
    x, v = map(int, input().split())
    xs.append(x)
    vs.append(v)

r1, r2, l1, l2 = [[], [], [], []]
r_sum, l_sum = [0, 0]
for i in range(n):
    r_sum += vs[i]
    r1.append(r_sum - xs[i])
    r2.append(r_sum - 2 * xs[i])

    i_rev = n - i - 1
    l_sum += vs[i_rev]
    l1.append(l_sum - (c - xs[i_rev]))
    l2.append(l_sum - 2 * (c - xs[i_rev]))

r1_max, r2_max = [0, 0]
l1_max, l2_max = [0, 0]
r1_maxs, r2_maxs = [[0], [0]]
l1_maxs, l2_maxs = [[0], [0]]
for i in range(n):
    r1_max = max(r1_max, r1[i])
    r1_maxs.append(r1_max)
    r2_max = max(r2_max, r2[i])
    r2_maxs.append(r2_max)
    l1_max = max(l1_max, l1[i])
    l1_maxs.append(l1_max)
    l2_max = max(l2_max, l2[i])
    l2_maxs.append(l2_max)

r1_l2_max = 0
l1_r2_max = 0
for i in range(0, n + 1):
    r1_l2_max = max(r1_l2_max, r1_maxs[i] + l2_maxs[n - i])
    l1_r2_max = max(l1_r2_max, l1_maxs[i] + r2_maxs[n - i])

total_max = max(r1_l2_max, l1_r2_max)

# 結果を出力
print("{}".format(total_max))

Submission status: Accepted

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]

r = []
state = 0
rmax = -9999999999
for i in range(n):
    s = sushi[i]
    state += s[1]

    if state-s[0]>rmax:
        rmax = state-s[0]
    r.append(rmax)

state = 0
ret1 = r[-1]
for i in range(n-1,0,-1):
    s = sushi[i]
    state += s[1]

    s = state-2*(c-s[0]) + r[i-1]
    if s>ret1:
        ret1 = s




l = [0 for _ in range(n)]
state = 0
lmax = -9999999999999
for i in range(n-1,-1,-1):
    s = sushi[i]
    state += s[1]

    if state-(c-s[0])>lmax:
        lmax = state-(c-s[0])
    l[i] = lmax

state = 0
ret2 = l[0]
for i in range(n-1):
    s = sushi[i]
    state += s[1]

    s = state-2*s[0] + l[i+1]
    if s>ret2:
        ret2 = s

print(max(ret1,ret2,0))

Submission status: Accepted

Solution code:
import random


def slv(N, C, X, V):
    ans_l = [(0, 0)]
    ans_l_ = [0]
    for x, v in zip(X, V):
        ans_l_.append(max(ans_l_[-1], ans_l[-1][1] + v - x))
        ans_l.append((x, ans_l[-1][1] + v))
    ans_l_.pop(0)
    ans_l.pop(0)

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

    # print('p1')

    ans_l_r = []
    for i, a in enumerate(ans_l[:-1], 1):
        # print(ans_r_[N-i-1],  a[1]-2*a[0])
        ans_l_r.append(ans_r_[N-i-1] + a[1]-2*a[0])

    # print('p2')
    ans_r_l = []
    for i, a in enumerate(ans_r[:-1], 1):
        # print(ans_l_[N-i-1],  a[1]-2*a[0])
        ans_r_l.append(ans_l_[N-i-1] + a[1]-2*a[0])

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

    # print(ans_l)
    # print(ans_l_)
    # print(ans_r)
    # print(ans_r_)

    # print(l, r, lr, rl)
    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)

    # N = 100000
    # C = 1000000000000
    # X = [1]
    # V = [100]
    # for _ in range(N):
    #     X.append(X[-1]+random.randint(1, 10000))
    #     V.append(random.randint(1, 10000))

    print(slv(N, C, X, V))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
#N=int(input())
#a = list(map(int,input().split()))

#x = []
#y = []
#for i in range(5):
#    x1,y1=[int(i) for i in input().split()]
#    x.append(x1)
#    y.append(y1)

N,C=[int(i) for i in input().split()]

x = [0]
v = [0]
for i in range(N):
    x1,v1=[int(i) for i in input().split()]
    x.append(x1)
    v.append(v1)

x.append(C)
v.append(0)

s = [0]*(N+1)
g = [0]*(N+2)
m1=0;m2=0

for i in range(1,N+1):
    s[i] = s[i-1]+v[i]-(x[i]-x[i-1])

for i in reversed(range(1,N+1)):
    g[i] = g[i+1]+v[i]+(x[i]-x[i+1])

j=N+1
M=0
jj=N+2
for i in reversed(range(N+1)):
    val = s[i] + g[j] -(C-x[j])
    jj=jj-1
    newval = s[i] + g[jj] - (C-x[jj])
    if newval >= val:
        val = newval
        j=jj
#    print(i,j,val)
    M=max(M,val)


j=N+1
jj=N+2
for i in reversed(range(N+1)):
    val = s[i] + g[j] -(x[i])
    jj=jj-1
    newval = s[i] + g[jj] - (x[i])
    if newval >= val:
        val = newval
        j=jj
#    print(i,j,val)
    M=max(M,val)

#print(s,g)
print(M)

Submission status: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n, c = f.read_int_list()
    x = [f.read_int_list() for _ in xrange(n)]

    sl = [0] * n
    mal = [None] * n
    sr = [0] * n
    mar = [None] * n

    pos = 0
    for i in xrange(n):
        if i > 0: sl[i] = sl[i-1]
        sl[i] += x[i][1] - (x[i][0] - pos)
        pos = x[i][0]
        if i > 0:
            if sl[i] > mal[i-1][0]:
                mal[i] = (sl[i], i)
            else:
                mal[i] = mal[i-1]
        else:
            mal[i] = (sl[i], i)

    pos = c
    for i in xrange(n-1,-1,-1):
        if i < n-1: sr[i] = sr[i+1]
        sr[i] += x[i][1] - (pos - x[i][0])
        pos = x[i][0]
        if i < n-1:
            if sr[i] > mar[i+1][0]:
                mar[i] = (sr[i], i)
            else:
                mar[i] = mar[i+1]
        else:
            mar[i] = (sr[i], i)

    # print sl, mal, sr, mar

    ans = 0
    for i in xrange(n):
        ans = max(ans, sl[i])
        if n > 1 and i < n-1: ans = max(ans, sl[i] - x[i][0] + mar[i+1][0])
    for i in xrange(n-1,-1,-1):
        ans = max(ans, sr[i])
        if n > 1 and i > 0: ans = max(ans, sr[i] - (c-x[i][0]) + mal[i-1][0])

    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Submission status: Accepted

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

frontS = []
# 前i個の中での累計MAX
frontMaxS = []
prevX = 0
v = 0
tmpMax = float('-inf')
for i in range(N):
  v = v + V[i] - (X[i] - prevX)
  frontS.append(v)
  tmpMax = max(tmpMax, v)
  frontMaxS.append(tmpMax)
  prevX= X[i]
frontMaxS.reverse()
frontMaxS.append(0)

backS = []
# 後ろi個の中での累計MAX
backMaxS = []
prevX = C
v = 0
tmpMax = float('-inf')
for i in range(N-1, -1, -1):
  v = v + V[i] - (prevX - X[i])
  backS.append(v)
  tmpMax = max(tmpMax, v)
  backMaxS.append(tmpMax)
  prevX = X[i]
backMaxS.reverse()
backMaxS.append(0)

ans = max(0, backMaxS[0], frontMaxS[0])
for i in range(N):
  # X個まで食べて、退出 or 引き返す
  ans = max(
    ans,
    frontS[i],
    frontS[i] - X[i] + backMaxS[i+1],
    backS[i],
    backS[i] - (C-X[-i-1]) + frontMaxS[i+1]
  )

print(ans)

Submission status: Accepted

Solution code:
import sys
from sys import stdin, stdout
import math
from copy import deepcopy
rem=10**9+7
sys.setrecursionlimit(10 ** 6)
take = lambda: map(int, stdin.readline().split())



n,c=take()
ans=[]
ans2=[]
ans1=[]
ans3=[]
u=[0]
f=[0]
all=[[0,0]]
rev=[[0,0]]
for i in range(n):
    a,b=take()
    all.append([a,b])
    rev.append([c-a,b])
all.sort()
rev.sort()
#print all,rev
tot=0
en=0
for i in all:
    a,b=i
    tot+=b
    en=tot
    ans.append(en-a)
    ans1.append(en-2*a)

tot=0
en=0
for i in rev:
    a,b=i
    tot += b
    en = tot
    ans2.append(en - a)
    ans3.append(en-2*a)

fin=0
#print all,rev
#print ans,ans2
t=0
k=0
for i in range(len(ans)):
    t=max(t,ans[i])
    u.append(t)
    k=max(k,ans2[i])
    f.append(k)

#print ans,ans1,ans2,ans3,f
for i in range(n+1):
    fin=max(fin,ans1[i]+f[n-i+1])
    fin=max(fin,ans3[i]+u[n-i+1])
print fin

Submission status: Accepted

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

V_tokei = []
V_hantokei = []
for i in range(N):
	if i == 0:
		V_tokei.append((v[i] - x[i], x[i]))
		V_hantokei.append(((v[N-i-1] - (C - x[N-i-1])), x[N-i-1]))
	else:
		V_tokei.append(((V_tokei[i-1][0] + v[i] - (x[i] - V_tokei[i-1][1])), x[i]))
		V_hantokei.append(((V_hantokei[i-1][0] + v[N-i-1] - (V_hantokei[i-1][1] - x[N-i-1]), x[N-i-1])))

# n <= i での V_hantokeiの最大値
V_hantokei_max = [V_hantokei[0][0]]
# n <= i での V_tokeiの最大値
V_tokei_max = [V_tokei[0][0]]
for i in range(1,N):
	V_hantokei_max.append(max(V_hantokei_max[i-1], V_hantokei[i][0]))
	V_tokei_max.append(max(V_tokei_max[i-1], V_tokei[i][0]))

v_mix_max = 0
for i in range(0, N-1):
	v_mix_max = max(v_mix_max, V_tokei[i][0] - V_tokei[i][1] + V_hantokei_max[N - i - 2])
	v_mix_max = max(v_mix_max, V_hantokei[i][0] - (C - V_hantokei[i][1]) + V_tokei_max[N - i - 2])
print(max(max([v[0] for v in V_hantokei] + [0]), max([v[0] for v in V_tokei] + [0]), v_mix_max))

Submission status: Accepted

Solution code:
def solve():
    N, C = map(int, input().split())# {{{
    L = [0]*N
    R = [0]*N

    S = []
    for n in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    res = 0

    # left round
    pre_x = 0
    diff = 0
    M = 0
    for n in range(N):
        x, v = S[n]
        diff -= abs(x - pre_x)
        diff += v
        M = max(diff, M)
        res = max(res, M)
        L[n] = M
        pre_x = x

    # print(L)

    # right round
    pre_x = C
    diff = 0
    M = 0
    for n in range(1, N+1):
        x, v = S[-n]
        diff -= abs(x - pre_x)
        diff += v
        M = max(diff, M)
        res = max(res, M)
        R[-n] = M
        pre_x = x

    # print(R)
    # }}}

    # left, right
    diff = 0
    for n in range(N-1):
        res = max(res, L[n]-S[n][0] + R[n+1])

    # right, left
    diff = 0
    for n in range(1, N):
        res = max(res, R[-n]-(abs(C-S[-n][0])) + L[-n-1])

    print(res)

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

import sys, math, copy
# import fractions, itertools
# import numpy as np
# import scipy

HUGE = 2147483647
HUGEL = 9223372036854775807
ABC = "abcdefghijklmnopqrstuvwxyz"

def max_cal(xn, vn, twoway):
    n = len(xn)
    factor = 2 if twoway else 1
    mc = []
    res = vn[0] - factor * xn[0]
    mc.append(max(0, res))
    for i in range(1, n):
        res += vn[i] - factor * (xn[i] - xn[i - 1])
        mc.append(max(mc[-1], res))
    assert len(mc) == len(xn)
    return mc

def read_input():
    n, c = map(int, input().split())
    xn = []
    vn = []
    for i in range(n):
        x, v = map(int, input().split())
        xn.append(x)
        vn.append(v)
    xnr = list(reversed([c - x for x in xn]))
    vnr = list(reversed(vn))
    return n, c, xn, vn, xnr, vnr

def merge(xn, xnr, c, max_one, max_two):
    def array_j(mt, j):
        if j < 0:
            return 0
        return mt[j]

    n = len(xn)
    j = -1
    ma = 0
    for i in reversed(range(n)):
        x = xn[i]
        while j + 1 < n and xnr[j + 1] * 2 <= c - x:
            j += 1
        res = max_one[i] + array_j(max_two, j)
        ma = max(ma, res)
    return ma

def main():
    n, c, xn, vn, xnr, vnr = read_input()
    max_one_cw = max_cal(xn, vn, False)
    max_two_cw = max_cal(xn, vn, True)
    max_one_ccw = max_cal(xnr, vnr, False)
    max_two_ccw = max_cal(xnr, vnr, True)
    res = merge(xn, xnr, c, max_one_cw, max_two_ccw)
    res = max(res, merge(xnr, xn, c, max_one_ccw, max_two_cw))
    print(res)

main()

Submission status: Accepted

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

c1 = []
c2 = []
c1x = []
cumv = 0
c1max = -float('inf')
for x,v in src:
    cumv += v
    c1.append(cumv - x)
    c2.append(cumv - 2*x)
    c1max = max(c1max, c1[-1])
    c1x.append(c1max)

r1 = []
r2 = []
r1x = []
cumv = 0
r1max = -float('inf')
for x,v in reversed(src):
    cumv += v
    x = C-x
    r1.append(cumv - x)
    r2.append(cumv - 2*x)
    r1max = max(r1max, r1[-1])
    r1x.append(r1max)

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

print(ans)

Submission status: Accepted

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]]
lmax = [0]
rmax = [0]
for j in range(n):
  left.append([left[-1][0]+ys[j]-(xs[j]-left[-1][1]),xs[j]])
  lmax.append(max(lmax[-1],left[-1][0]))

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import numpy as np
N, C = map(int, input().split())
x = [0]*N
v = [0]*N
for i in range(N):
    x[i], v[i] = map(int, input().split())

x = np.array(x)
v = np.array(v)

gain_f = np.cumsum(v)-x
for i in range(1, N):
    gain_f[i] = max(gain_f[i-1], gain_f[i])

gain_b = np.cumsum(v[::-1])-(C-x[::-1])
for i in range(1, N):
    gain_b[i] = max(gain_b[i-1], gain_b[i])
    
turn_f = np.cumsum(v)-x*2
for i in range(1, N):
    turn_f[i] = max(turn_f[i-1], turn_f[i])

turn_b = np.cumsum(v[::-1])-(C-x[::-1])*2
for i in range(1, N):
    turn_b[i] = max(turn_b[i-1], turn_b[i])

turn_f = np.concatenate(([0], turn_f))
turn_b = np.concatenate(([0], turn_b))

ans = 0
for i in range(N):
    ans = max([ans, gain_f[i]+turn_b[N-1-i], gain_b[i]+turn_f[N-1-i]])

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return map(int, input().split())
N, C = inpl()

S = [tuple(inpl()) for _ in range(N)]

R1 = [0]*N
R2 = [0]*N
L1 = [0]*N
L2 = [0]*N

cal = 0
nak = 0
ans1 = 0
ans2 = 0
for i, (x, v) in enumerate(S):
    cal += v
    ans1 = max(ans1, cal-x)
    ans2 = max(ans2, cal-2*x)
    R1[i] = ans1
    R2[i] = ans2


cal = 0
nak = 0
ans1 = 0
ans2 = 0
for i, (x, v) in enumerate(S[::-1]):
    x = C-x
    cal += v
    ans1 = max(ans1, cal-x)
    ans2 = max(ans2, cal-2*x)
    L1[-1-i] = ans1
    L2[-1-i] = ans2


ans = 0

for i in range(N-1):
    ans = max(ans, R2[i]+L1[i+1], R1[i]+L2[i+1])

ans = max(ans, R1[-1], L1[0])
print(ans)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
xvs = [tuple(map(int, input().split())) for _ in range(n)]

forward_cals = [(0, 0, 0)]
for x, v in xvs:
    cal, max_cal, pos = forward_cals[-1]
    new_cal = cal + v - (x - pos)
    new_max_cal = max(max_cal, new_cal)
    forward_cals.append((new_cal, new_max_cal, x))

backward_cals = [(0, 0, c)]
for x, v in reversed(xvs):
    cal, max_cal, pos = backward_cals[-1]
    new_cal = cal + v - (pos - x)
    new_max_cal = max(max_cal, new_cal)
    backward_cals.append((new_cal, new_max_cal, x))

ans = max((forward_cals[-1][1], backward_cals[-1][1]))

for (cal, max_cal, pos), (_, back_max, __) in zip(forward_cals, reversed(backward_cals)):
    ans = max(ans, cal - pos + back_max)

for (__, for_max, _), (cal, max_cal, pos) in zip(reversed(forward_cals), backward_cals):
    ans = max(ans, cal - (c-pos) + for_max)

print(ans)

Submission status: Accepted

Solution code:
n,c=[int(k) for k in raw_input().split(" ")]
t=[]
for i in range(n):
    t+=[tuple([int(k) for k in raw_input().split(" ")])]

ts=sorted(t)
tot=sum([k[1] for k in t])
maxperf=0
mysum=0
mpcw=[0]*n
mpccw=[0]*n
mpcwab=[0]*n
mpccwab=[0]*n

k=0
for i in ts:
    mpccw[k]=tot-mysum - (c-i[0])
    mpccwab[k]=tot-mysum - (c-i[0])*2
    mysum+=i[1]
    mpcw[k]=mysum-i[0]
    mpcwab[k]=mysum-i[0]*2
    k+=1
    
#runningmaxes
 
mpucw=[0]*(n)
mpuccw=[0]*(n)

for i in range(0,n):
    mpucw[i]=max(mpucw[i-1],mpcwab[i]) #best i can get reaching < guy i cw then coming back
    

for i in range(-1,-n-1,-1):
    mpuccw[i]=max(mpuccw[i+1],mpccwab[i]) #best i can get reaching < guy i cw then coming back
    
for i in range(n):
    maxperf=max(maxperf, mpcw[i] + (mpuccw[i+1] if i<n-1 else 0) )
    maxperf=max(maxperf, mpccw[i] + (mpucw[i-1] if i>0 else 0) )

print maxperf

Submission status: Accepted

Solution code:
n, c = map(int, input().split())
a = [None] * n
for i in range(n):
    x, v = map(int, input().split())
    a[i] = (x, v)
l1 = [None] * n
l2 = [None] * n
r1 = [None] * n
r2 = [None] * n
b = 0
m = 0
for i in range(n):
    x, v = a[i]
    b += v - x
    m = max(m, b)
    r1[i] = m
    r2[i] = max(0, b - x)
    b += x
b = 0
m = 0
for i in range(n - 1, -1, -1):
    x, v = a[i]
    x = c - x
    b += v - x
    m = max(m, b)
    l1[n - i - 1] = m
    l2[n - i - 1] = max(0, b - x)
    b += x
m = max(r1[n - 1], l1[n - 1])
for i in range(n - 1): m = max(m, max(r2[n - i - 2] + l1[i], l2[n - i - 2] + r1[i]))
print(m)

Submission status: Accepted

Solution code:
import sys

cin = sys.stdin
# cin = open("in.txt", "r")

def line2N():
    return map(int, cin.readline().split())

n, c = line2N()
x = [0]*n
v = [0]*n
for i in range(n):
    x0, v0 = line2N()
    x[i] = x0
    v[i] = v0
c1 = [0]*n
m1 = [0]*(n+1)
c1[0] = -(x[0]-0) + v[0]
m1[0] = max(0, c1[0])
for i in range(1,n):
    c1[i] = c1[i-1] - (x[i]-x[i-1]) + v[i]
    m1[i] = max(m1[i-1], c1[i])
c2 = [0]*n
c2[n-1] = -(c - x[n-1]) + v[n-1]
m2 = [0]*(n+1)
m2[n-1] = max(0, c2[n-1])
for i in range(n-2, -1, -1):
    c2[i] = c2[i+1] - (x[i+1]-x[i]) + v[i]
    m2[i] = max(m2[i+1], c2[i])
ans0 = 0
for i in range(0, n-1):
    ans0 = max(ans0, c1[i] - x[i] + m2[i+1])
for i in range(n-1, 0, -1):
    ans0 = max(ans0, c2[i] - (c-x[i]) + m1[i-1])

print(max(ans0, m1[n-1], m2[0]))

Submission status: Accepted

Solution code:
import numpy as np


def get_max():
    a = 0

    def _max(x):
        nonlocal a
        a = max(a, x)
        return a

    return _max


def solve(fwd, bck):
    dp = []
    cur = 0
    for x, v in fwd:
        cur -= x
        cur += v
        dp.append(cur)

    dp = list(map(get_max(), dp))

    cur = 0
    ans = dp[-1]
    for i, (x, v) in enumerate(bck[:-1]):
        cur -= 2 * x
        cur += v
        # print(i, x, v, ans, cur, dp[n - i - 2])
        ans = max(ans, dp[n - i - 2] + cur)
        # print(i, x, v, ans, cur, dp[n - i - 2])

    return ans


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

fwd = np.array(sushi).T
fwd[0] = np.diff(np.concatenate(([0], fwd[0])))
fwd = fwd.T.tolist()

bck = np.array(sushi).T
bck[0] = np.diff(np.concatenate(([0], (c - bck[0])[::-1])))
bck[1] = bck[1][::-1]
bck = bck.T.tolist()

# print(fwd)
# print(bck)

print(max(solve(fwd, bck), solve(bck, fwd)))