Problem:


Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

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

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

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

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

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

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

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

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

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

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

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

Sample Input 4

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

Sample Output 4

6500000000

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



Sample input:
3 20
2 80
9 120
16 1


Sample output:
191

Submission status: Accepted

Solution code:
import collections


Point = collections.namedtuple('Sushi', ['position', 'value'])


def read_ints():
    return map(int, input().split())


def reverse_points(points, length):
    return [Point(length - p.position, p.value) for p in reversed(points)]


def solve_unidir(points, length):
    forward_peaks = [(-1, 0)]
    forward_accumulated_value = 0
    for i, p in enumerate(points):
        forward_accumulated_value += p.value
        forward_actual_value = forward_accumulated_value - p.position
        if forward_actual_value > forward_peaks[-1][1]:
            forward_peaks.append((i, forward_actual_value))
    best_value = forward_peaks[-1][1]
    backward_accumulated_value = 0
    for i, p in reversed(list(enumerate(points))):
        while forward_peaks[-1][0] >= i:
            forward_peaks.pop()
        backward_accumulated_value += p.value
        backward_actual_value = backward_accumulated_value - 2 * (length - p.position)
        best_value = max(best_value, backward_actual_value + forward_peaks[-1][1])
    return best_value


def solve(points, length):
    return max(solve_unidir(points, length),
               solve_unidir(reverse_points(points, length), length))


def main():
    n, length = read_ints()
    points = []
    for _ in range(n):
        position, value = read_ints()
        points.append(Point(position, value))
    print(solve(points, length))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

(N, C) = reads()

x, v = [], []
for _ in range(N):
  X, V = reads()
  x.append(X)
  v.append(V)

psumr = [0] * (N+1)
psuml = [0] * (N+1)

INF = 10**20

pmaxr = [0] * (N+1)
pmaxl = [0] * (N+1)

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

for i in range(N-1, -1, -1):
  psuml[i] = psuml[i+1] + v[i]
  pmaxl[i] = max(pmaxl[i+1], psuml[i] - (C - x[i]))

ans0 = max(pmaxr[N], pmaxl[0])
ans1 = max((psumr[i+1] - 2 * x[i] + pmaxl[i+1] for i in range(N)))
ans2 = max((psuml[i] - 2 * (C - x[i]) + pmaxr[i] for i in range(N)))
print(max(ans0, ans1, ans2))

Submission status: Accepted

Solution code:

def main():
    try:
        n, c = [int(i) for i in raw_input().strip().split()]
    except ValueError:
        return True
    except EOFError:
        return False
    d = [0 for i in xrange(n)]
    w = [0 for i in xrange(n)]
    for i in xrange(n):
        d[i], w[i] = [int(j) for j in raw_input().strip().split()]
    tot = sum(w)
    foo = 0
    foo = max(foo, tot-d[-1])
    foo = max(foo, tot-c+d[0])
    # <>>
    presum = 0
    suffix = tot
    prefer = 0
    for k in xrange(n-1):
        presum += w[k]
        prefer = max(prefer, presum - d[k])
        suffix -= w[k]
        foo = max(foo, prefer)
        tmp = c - d[k+1]
        foo = max(foo, prefer + suffix - tmp - tmp)
    # ><<
    presum = 0
    suffix = tot
    prefer = 0
    for k in xrange(n-1, 0, -1):
        presum += w[k]
        prefer = max(prefer, presum - (c - d[k]))
        suffix -= w[k]
        foo = max(foo, prefer)
        tmp = d[k-1]
        foo = max(foo, prefer + suffix - tmp - tmp)
    print foo
    return True
    
if __name__ == '__main__':
    while True:
        if not main():
            break

Submission status: Accepted

Solution code:
n, o = map(int, input().split())
x, v = [], []
for i in range(n):
    a, b = map(int, input().split())
    x.append(a)
    v.append(b)
c = 0

desno, lijevo, y = [], [], []
dd, ll = [0], [0]

tot = 0
for i in range(n):
    if i > 0:
        dd.append(max(dd[-1], desno[-1]))
    tot += v[i]
    desno.append(tot - x[i])

tot = 0
for i in range(n - 1, -1, -1):
    if i < n - 1:
        ll.append(max(ll[-1], lijevo[-1]))
    tot += v[i]
    lijevo.append(tot - (o - x[i]))
    y.append(o - x[i])

#print(desno, dd)
#print(lijevo, ll)

for i in range(n):
    kd = desno[i] - x[i] + ll[n - i - 1]
            #max([lijevo[j] for j in range(n - i - 1)] + [0])
    kl = lijevo[i] - y[i] + dd[n - i - 1]
            #max([desno[j] for j in range(n - i - 1)] + [0])
    #print(kd, kl)
    c = max(c, kd, kl, desno[i], lijevo[i])

print(c)

Submission status: Accepted

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

def solve():
  M = [0]*N
  m = 0
  c = 0
  for i in range(N):
    c += v[i]
    c -= (x[i] - (0 if i==0 else x[i-1]))*2
    m = max(m, c)
    M[i] = m
  a = M[N-1]
  c = 0
  for i in range(N)[::-1]:
    c += v[i]
    c -= (C if i==N-1 else x[i+1]) - x[i]
    a = max(a, c+(0 if i==0 else M[i-1]))
  return a

ans = solve()
for i in range(N):
  x[i] = C - x[i]
x = x[::-1]
v = v[::-1]
ans = max(ans, solve())
print ans

Submission status: Runtime Error

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

# A: Anti-clockwise, B: Clockwise, V: Values
n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    # Cumulative Values returning to Start
NMA, NMB = XA.max(), XB.max()


def ind(lis, maxi):
    for i, x in enumerate(lis):
        if x == maxi:
            return i


MRA2, MRB2 = max(RXA[:-1], default=0), max(RXB[:-1], default=0)
mrai = ind(RXA, MRA2)
mrbi = ind(RXB, MRB2)

if not mrai:
    mrai = 0
if not mrbi:
    mrbi = 0

MA2 = max(0, max(XA[:n - 1 - mrbi], default=0))
MB2 = max(0, max(XB[:n - 1 - mrai], default=0))
res = max(NMA, NMB, MA2 + MRB2, MB2 + MRA2)


for k in range(-1, -10 if n > 10 else -2, -1):
    MA3, MB3 = max(XA[:k], default=0), max(XB[:k], default=0)
    mai3 = ind(XA, MA3)
    mbi3 = ind(XB, MB3)

    MRA3 = max(0, max(RXA[:n - 1 - mbi3], default=0))
    MRB3 = max(0, max(RXB[:n - 1 - mai3], default=0))

    res = max(res, MA3 + MRB3, MB3 + MRA3)
print(res)

Submission status: Runtime Error

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

# A: Anti-clockwise, B: Clockwise, V: Values
n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]

XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RXA, RXB = XA - A, XB - B    # Cumulative Values returning to Start
NMA, NMB = XA.max(), XB.max()


def ind(lis, maxi):
    for i, x in enumerate(lis):
        if x == maxi:
            return i


MRA2, MRB2 = max(RXA[:-1], default=0), max(RXB[:-1], default=0)
mrai = ind(RXA, MRA2)
mrbi = ind(RXB, MRB2)

MA2 = max(0, max(XA[:n - 1 - mrbi], default=0))
MB2 = max(0, max(XB[:n - 1 - mrai], default=0))
res = max(NMA, NMB, MA2 + MRB2, MB2 + MRA2)


for k in range(-1, -10 if n > 10 else -1, -1):
    MA3, MB3 = max(XA[:k], default=0), max(XB[:k], default=0)
    mai3 = ind(XA, MA3)
    mbi3 = ind(XB, MB3)

    MRA3 = max(0, max(RXA[:n - 1 - mbi3], default=0))
    MRB3 = max(0, max(RXB[:n - 1 - mai3], default=0))

    res = max(res, MA3 + MRB3, MB3 + MRA3)
print(res)

Submission status: Runtime Error

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

n, c = map(int, input().split())
AV = np.array(list(map(int, input2().rsplit())), dtype=np.int64)
A, V = AV[::2], AV[1::2]
B = (c - A)[::-1]
XA = np.cumsum(V) - A
XB = np.cumsum(V[::-1]) - B
RSA, RSB = XA - A, XB - B

XRA, XRB = 0, 0
for i in range(n):
    if RSA[i] > 0:
        XRA = max(XRA, RSA[i] + XB[:n - 1 - i].max())
    else:
        break

for i in range(n):
    if RSB[i] > 0:
        XRB = max(XRB, RSB[i] + XA[:n - 1 - i].max())
    else:
        break

print(max(0, max(XA), max(XB), XRA, XRB))

Submission status: Runtime Error

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,C = LI()
    a = [LI() for _ in range(n)]
    u = [_[0] for _ in a]
    x = [_[1] for _ in a]
    b=c=d=e=[0] * n
    b[0] = x[0]
    c[-1] = x[-1]
    for i in range(1, n):
        b[i] = b[i-1] + x[i]
    for i in range(n-2, -1, -1):
        c[i] = c[i+1] + x[i]
    d[0] = x[0] - u[0]
    e[-1] = x[-1] - (C-u[-1])
    for i in range(1, n):
        d[i] = max(b[i]-u[i], d[i-1])
    for i in range(n-2, -1, -1):
        e[i] = max(c[i]-(C-u[i]), e[i+1])
    r = max(d[-1], e[0], 0)
    for i in range(n):
        try:
            r = max(r,b[i]-u[i]*2+e[i+1])
        try:
            r = max(r,c[i]-(C-u[i])*2+d[i-1])
            
    return r

print(main())

Submission status: Runtime Error

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

right_turn_sum = [0]
for i in range(N):
    right_turn_sum.append(sushi[i][1]+right_turn_sum[i])
for i in range(N):
    right_turn_sum[i+1] -= sushi[i][0]
right_turn_to_zero = [0]
for i in range(N):
    right_turn_to_zero.append(right_turn_sum[i+1]-sushi[i][0])
print(right_turn_sum)
print(right_turn_to_zero)

left_turn_sum = [0]
for i in range(N):
    left_turn_sum.append(sushi[-1-i][1]+left_turn_sum[i])
for i in range(N):
    left_turn_sum[i+1] -= (C - sushi[-1-i][0])
left_turn_to_zero = [0]
for i in range(N):
    left_turn_to_zero.append(left_turn_sum[i+1]-sushi[-1-i][0])

"""
print(left_turn_sum)
print(left_turn_to_zero)

ans = max(right_turn_sum)
ans = max(left_turn_sum+[ans])
print(ans)
"""
maxi = 0
for i in range(N+1):
    if maxi < right_turn_sum[i]:
        maxi = right_turn_sum[i]
    right_turn_sum[i] = max(maxi, right_turn_sum[i])

maxi = 0
for i in range(N+1):
    if maxi < right_turn_to_zero[i]:
        maxi = right_turn_to_zero[i]
    right_turn_to_zero[i] = max(maxi, right_turn_to_zero[i])

maxi = 0
for i in range(N+1):
    if maxi < left_turn_sum[i]:
        maxi = left_turn_sum[i]
    left_turn_sum[i] = max(maxi, left_turn_sum[i])

maxi = 0
for i in range(N+1):
    if maxi < left_turn_to_zero[i]:
        maxi = left_turn_to_zero[i]
    left_turn_to_zero[i] = max(maxi, left_turn_to_zero[i])
"""
print(right_turn_sum)
print(right_turn_to_zero)
print(left_turn_sum)
print(left_turn_to_zero)
"""

for i in range(N+1):
    ans = max(ans, right_turn_to_zero[i]+left_turn_sum[N-i])

for i in range(N+1):
    ans = max(ans, left_turn_to_zero[i]+right_turn_sum[N-i])
print(ans)

Submission status: Runtime Error

Solution code:
n,c = map(int,input().split())
x = [0]
v = [0]
rf = [0] * (n+2)
rg = [0] * (n+2)
lf = [0] * (n+2)
lg = [0] * (n+2)
for i in range(0,n):
    X,V = map(int,input().split())
    x.append(X)
    v.append(V)
for i in range(0,n):
    rf[i+1] = rf[i] + v[i+1]
    rg[i+1] = max(rg[i],rf[i+1] - x[i+1])
for i in range(n+1,1,-1):
    lf[i-1] = lf[i] + v[i-1]
    lg[i-1] = max(lg[i],lf[i-1] - (c-x[i-1]))

#print(lg[::-1])
#print(rg)

for i in range(1,n):
    ans = max(ans,rg[i]+lg[i+1] - x[i],rg[i]+lg[i+1] - (c - x[i+1]))
print(ans)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
#include <stack>
using namespace std;
int n;
long long int x[100003];
long long int v[100003];
long long int ls[100003];
long long int rs[100003];
long long int c;
int main()
{
    scanf("%d%lld", &n, &c);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld%lld", &x[i], &v[i]);
    }
    x[n+1] = c;
    long long int cur = 0;
    for(int i=1;i<=n;i++)
    {
        cur += v[i] - (x[i] - x[i-1]);
        ls[i] = max(ls[i-1], cur);
    }
    cur = 0;
    for(int i=n;i;i--)
    {
        cur += v[i] - (x[i+1] - x[i]);
        rs[i] = max(rs[i+1], cur);
    }
    long long int ans = max(ls[n], rs[1]);
    for(int i=1;i<=n;i++)
    {
        ans = max({ls[i] + rs[i+1] - x[i], rs[i] + ls[i-1] - (c - x[i]), ans});
    }
    printf("%lld\n", ans);
}

Submission status: Runtime Error

Solution code:

N, C = input().split(' ')
N = int(N)
C = int(C)
xs, vs = [], []
for n in range(N):
    x, v = input().split(' ')
    xs.append(int(x))
    vs.append(int(v))

dp_r = []
for i in range(N):
    dp_r.append(sum(vs[:i+1]) - xs[i])
dp_l = []
rev_vs = list(reversed(vs))
rev_xs = list(reversed(xs))
for i in range(N):
    dp_l.append(sum(rev_vs[:i+1]) - (C-rev_xs[i]))

max_right = max(dp_r)
max_left = max(dp_l)

max_bothes = []
for i in range(1, N-1):
    mr = max(dp_r[:i])
    max_bothes.append(mr - xs[dp_r.index(mr)] + max(dp_l[:N-dp_r.index(mr)-1]))


print(max([max_right, max_left, max(max_bothes)]))

Submission status: Runtime Error

Solution code:
# input
N, C = map(int, input().split(" "))
x, v = [], []
for i in range(1, N+1):
    xv = list(map(int, input().split(" ")))
    x.append(xv[0])
    v.append(xv[1])

# x_i メートル
# v_i キロカロリー
max_cal = 0
S = [[i for i in range(N)]]  # stack
place = 0  # 位置
cal = 0
S[0].append(cal)
S[0].append(place)
while len(S) > 0:
    s = S.pop()  # n = len
    # index -1 : place
    # index -2 : calorie
    if len(s) == 3:
        # len(s) = 1 になったとき
        idx = s[0]  # first
        next_place = x[idx]
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[s[0]]
        max_cal = max(max_cal, next_cal)
    else:
        #while len(s) > 1:
        # x[s[0]] は s[0] 番目の寿司の相手ある絶対位置（初期値からの距離）
        place = s[-1]
        idx = s[0]  # first
        next_place = x[idx]
        dist = abs(next_place - place)
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[idx]
        max_cal = max(max_cal, next_cal)
        S.append(s[1:-2] + [next_cal, next_place])
        place = s[-1]
        idx = s[-3]  # last
        next_place = x[idx]
        #place_step = abs(next_place - place) % C
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[idx]
        max_cal = max(max_cal, next_cal)
        S.append(s[:-3] + [next_cal, next_place])
print(max_cal)

Submission status: Runtime Error

Solution code:
# input
N, C = map(int, input().split(" "))
x, v = [], []
for i in range(1, N+1):
    xv = map(int, input().split(" "))
    x.append(xv[0])
    v.append(xv[1])# x_i メートル
# v_i キロカロリー
max_cal = 0
S = [[i for i in range(N)]]  # stack
place = 0  # 位置
cal = 0
S[0].append(cal)
S[0].append(place)
#print(S)
while len(S) > 0:
    s = S.pop()  # n = len
    # index -1 : place
    # index -2 : calorie
    print("pop", s, max_cal)
    if len(s) == 3:
        # len(s) = 1 になったとき
        #print("last-preplace", s[-1])
        idx = s[0]  # first
        next_place = x[idx]
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[s[0]]
        max_cal = max(max_cal, next_cal)
        #print("last-place", s[-1])
        #print("len(s)==1", max_cal)
    else:
        #while len(s) > 1:
        # x[s[0]] は s[0] 番目の寿司の相手ある絶対位置（初期値からの距離）
        #print("first", s)
        place = s[-1]
        idx = s[0]  # first
        next_place = x[idx]
        dist = abs(next_place - place)
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[idx]
        max_cal = max(max_cal, next_cal)
        S.append(s[1:-2] + [next_cal, next_place])
        #print(next_cal)
        #print("last", s)
        place = s[-1]
        idx = s[-3]  # last
        next_place = x[idx]
        #place_step = abs(next_place - place) % C
        place_step = min(dist, C - dist)
        next_cal = s[-2] - place_step + v[idx]
        max_cal = max(max_cal, next_cal)
        S.append(s[:-3] + [next_cal, next_place])
        #print(next_cal)
print(max_cal)

Submission status: Runtime Error

Solution code:
import numpy as np

s = input().split('\n')
n, c = map(int, s[0].split())
x_cw = np.empty(n)
v = np.empty(n)

for i in range(n):
    x_cw[i], v[i] = map(int, s[i+1].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: Runtime Error

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: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Contents   : AtCoder Regular Contest 096
Author     : Kitaura Hiromi
LastUpdate : 20180421
Since      : 20180421
"""
    
N, C = map(int, input().split())
x = []
v = []
for i in range(N):
    x_i, v_i = map(int, input().split())
    x.append(x_i)
    v.append(v_i)

ret = 0
def dfs(x, v, x_rest, v_rest, num, pos, cal):
    global ret
    if num == N:
        return cal
    else:
        for i in range(N - num):
            dist = abs(x[i] - pos)
            new_cal = max(cal, cal + v[i] - min(dist, C - dist))
            ret = max(ret, dfs(x[:i] + x[i+1:], v[:i] + v[i+1:], x_rest + [x[i]], v_rest + [v[i]], num + 1, x[i], new_cal))
    return ret

print(dfs(x, v, [], [], 0, 0, 0))

Submission status: Runtime Error

Solution code:
def new_location(old_location, new_zero, c):
    if old_location < new_zero:
        return c + (old_location - new_zero)
    else:
        return old_location - new_zero


def solve(sushi, c):
    if sushi:
        new_list = map(lambda (x,y):(new_location(x, sushi[0][0], c), y), sushi[1:])
        cw_sushi = solve(new_list, c) + sushi[0][1] - min(sushi[0][0], c - sushi[0][0])
        if len(sushi) > 1:
            new_list = map(lambda (x,y):(new_location(x, sushi[-1][0], c), y), sushi[:-1])
            ccw_sushi = solve(new_list, c) + sushi[-1][1] - min(sushi[-1][0], c - sushi[-1][0])
            return max(0, cw_sushi, ccw_sushi)

        return max(0, cw_sushi)

    return 0


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

print solve(sushi, c)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <functional>

using namespace std;
const int INT_INF = 500000000;
const long long LL_INF = (long long)pow(10, 18);
typedef long long ll;

ll N, C;
ll x[100004] = {0};
ll v[100004] = {0};
ll dp1[100004] = {0};
ll dp2[100004] = {0};
ll dp3[100004] = {0};
ll dp4[100004] = {0};

int main() {
   cin >> N >> C;
   for (int i=0; i < N; i++) {
      cin >> x[i] >> v[i];
   }
   ll v_0toN = 0;
   ll v_Nto0 = 0;
   for (int i=0; i<N; i++) {
      v_0toN += v[i];
      v_Nto0 += v[N-i-1];
      if (dp1[i] >= v_0toN - x[i]) {
	 dp1[i+1] = dp1[i];
	 dp3[i+1] = dp3[i];
      } else {
	 dp1[i+1] = v_0toN - x[i];
	 dp3[i+1] = v_0toN - 2*x[i];
      }
      int k = v_Nto0 - (C - x[N-i-1]);
      if (dp2[N-i+1] < k) {
	 dp2[N-i] = k;
	 dp4[N-i] = v_Nto0 - 2 * (C - x[N-i-1]);
      } else {
	 dp2[N-i] = dp2[N-i+1];
	 dp4[N-i] = dp4[N-i+1];
      }
      //cout << "i:" << i << " dp1: " << dp1[i] << " dp2: " << dp2[i] << endl;
     //cout << "i:" << i << " dp3: " << dp3[i] << " dp4: " << dp4[i] << endl;
   }
   ll a = 0;
   ll b = 0;
   for (int i=0; i<=N; i++) {
      //cout << "i:" << i << " dp1: " << dp1[i] << " dp2: " << dp2[i] << endl;
     // cout << "i:" << i << " dp3: " << dp3[i] << " dp4: " << dp4[i] << endl;
      a = max(dp4[i+1] + dp1[i], a);
      b = max(dp3[i] + dp2[i+1] , b);
   }
   //cout << a << " " << b << endl;
   cout << max(a, b) << endl;

}

Submission status: Runtime Error

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)

I = np.zeros((N+1, N+1))
J = np.zeros((N+1, N+1))
I[0, 0] = 0
J[0, 0] = 0
I[0, N] = v_list[N-1] - (C - x_list[N-1])
J[0, N] = v_list[N-1] - (C - x_list[N-1])

for k in range(0, N):
    if k == 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - x_list[k]
    elif k > 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - (x_list[k] - x_list[k-1])

for l in reversed(range(2, N+1)):
    if l > 0:
        I[0, l-1] = I[0, l] + v_list[l-2] -(x_list[l-1] - x_list[l-2])

for k in range(1, N+1):
    for l in range(k+1, N+1):
        if k > 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1] - x_list[k-2])
        elif k == 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1])

# J
for k in range(0, N):
    if k == 0:
        J[k+1, 0] = J[k, 0] + v_list[k] - x_list[k]
    elif k > 0:
        J[k+1, 0] = J[k, 0] + v_list[k] - (x_list[k] - x_list[k-1])

for l in reversed(range(2, N+1)):
    if l > 0:
        I
    J[0, l-1] = J[0, l] + v_list[l-2] -(x_list[l-1] - x_list[l-2])

for l in reversed(range(1, N+1)):
    for k in range(1, l):
        if l == N :
            J[k, l] = J[k, 0] + v_list[l-1] - 2 * (C - x_list[l-1])
        elif l < N:
            J[k, l] = J[k, l+1] + v_list[l-1] - 2 * (x_list[l] - x_list[l-1])
M = max(int(I.max()), int(J.max()))

print(M)

Submission status: Runtime Error

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

I = np.zeros((N+1, N+1))

I[0, 0] = 0
I[0, N] = v_list[N-1] - (C - x_list[N-1])

for k in range(0, N):
    if k == 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - x_list[k]
    elif k > 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - (x_list[k] - x_list[k-1])

for l in reversed(range(2, N+1)):
    if l > 0:
        I[0, l-1] = I[0, l] + v_list[l-2] -(x_list[l-1] - x_list[l-2])

for k in range(1, N+1):
    for l in range(k+1, N+1):
        if k > 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1] - x_list[k-2])
        elif k == 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1])

M = I.max()
print(M)

Submission status: Runtime Error

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

I = np.zeros((N+1, N+1))

I[0, 0] = 0
I[0, N] = v_list[N-1] - (C - x_list[N-1])

for k in range(0, N):
    if k == 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - x_list[k]
    elif k > 0:
        I[k+1, 0] = I[k, 0] + v_list[k] - (x_list[k] - x_list[k-1])

for l in reversed(range(2, N+1)):
    if l > 0:
        I[0, l-1] = I[0, l] + v_list[l-2] -(x_list[l-1] - x_list[l-2])

for k in range(1, N+1):
    for l in range(k+1, N+1):
        if k > 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1] - x_list[k-2])
        elif k == 1:
            I[k, l] = I[k - 1, l] + v_list[k-1] - 2 * (x_list[k-1])

M = max(I)
print(M)

Submission status: Runtime Error

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

plus_arr=[]
plus_max=0
plus_max_num=-1
plus_max_minus_distance=0
plus_max_minus_distance_num=-1
minus_arr=[]
minus_max=0
minus_max_num=N
minus_max_minus_distance=0
minus_max_minus_distance_num=N
for i,(x,v) in enumerate(nums):
    if i == 0:
        vi = v- x
        plus_arr.append(v-x)
        #plus_max=v-x
        #plus_max_num=x
        #plus_max_minus_distance=v-x
        #plus_max_minus_distance_num=x
    else:
        vi = plus_arr[i-1] + nums[i-1][0] -x + v
        plus_arr.append( vi  )
    if plus_max <= vi:
        plus_max = vi
        plus_max_num  = x
    if 2 * x < C:
        plus_max_half = plus_max
        if plus_max_minus_distance <= vi - x:
            plus_max_minus_distance = vi - x
            plus_max_minus_distance_num = x

for i,(x,v) in enumerate(nums[-1:]):
    if i == 0:
        vi = v- C + x
        minus_arr.append(v- C + x)
        #minus_max=v- C + x
        #minus_max_num=x
        #minus_max_minus_distance=v- C + x
        #minus_max_minus_distance_num=x
    else:
        vi = minus_arr[i-1] + nums[i-1][0] - C + x + v
        minus_arr.append( vi  )
    if minus_max <= vi:
        minus_max = vi
        minus_max_num  = x
    if 2 * (C - x) < C:
        minus_max_half=minus_max
        if minus_max_minus_distance <= vi -  C + x:
            minus_max_minus_distance = vi -  C + x
            minus_max_minus_distance_num = x

print(max([ plus_max,minus_max,plus_max_minus_distance + minus_max_half, plus_max_half+ minus_max_minus_distance_num]))

Submission status: Runtime Error

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,mx[n].index()):
  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: Runtime Error

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

x1=[x[i+1]-x[i] for i in range(len(x)-1)]
x2=[c-x[-1]]+x1[:0:-1]
h=[0]
for i,j in zip(x2,reversed(v)):
    h.append(h[-1]+j+-i)
t=[0]
for i,j in zip(x1,v):
    t.append(t[-1]+j-i)
hi=h.index(max(h[0:-1]))
ti=t.index(max(t[0:-1]))
tm=max(t[0:-1])
hm=max(h[0:-ti])
h2=[h[i]-c+x[-i] for i in range(1,len(h)-1)]
t2=[t[i]-x[i] for i in range(1,len(t)-1)]


#print(ti,hi)
print(max(max(t), max(h), hm+max(t2[0:-ti]),tm+max(h2[:-hi])))

Submission status: Runtime Error

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

x1=[x[i+1]-x[i] for i in range(len(x)-1)]
x2=[c-x[-1]]+x1[:0:-1]
h=[0]
for i,j in zip(x2,reversed(v)):
    h.append(h[-1]+j+-i)
t=[0]
for i,j in zip(x1,v):
    t.append(t[-1]+j-i)
hi=h.index(max(h[0:-1]))
ti=t.index(max(t[0:-1]))
tm=max(t[0:-1])
hm=max(h[0:-ti])
h2=[h[i]-c+x[-i] for i in range(1,len(h))]
t2=[t[i]-x[i] for i in range(1,len(t))]


#print(ti,hi)
print(max(max(t), max(h), hm+max(t2[0:-ti]),tm+max(h2[:-hi])))