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:
import numpy as np

N, C = map(int, input().split())
X = [0 for _ in range(N + 1)]
V = [0 for _ in range(N + 1)]
for i in range(1, N + 1):
    X[i], V[i] = map(int, input().split())
X = np.array(X)
V = np.array(V)

X_inv = np.hstack((np.zeros(1, dtype=int), (C - X[1:])[::-1]))
V_sum = V.cumsum()
V_inv_sum = np.hstack((np.zeros(1, dtype=int), V[1:][::-1])).cumsum()

ans = 0
for i in range(N + 1):
    for j in range(N - i + 1):
        v = V_sum[i] + V_inv_sum[j]
        x1 = X[i] + 2 * X_inv[j]
        x2 = 2 * X[i] + X_inv[j]
        ans = max(ans, v - min(x1, x2))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def to_cumsum(arr):
    """
    1次元配列を累積和の1次元配列に変換する
    """
    cumsum = 0
    new = list()
    for e in arr:
        cumsum += e
        new.append(cumsum)
    return new


N, C = map(int, input().split())
X = [0 for _ in range(N + 1)]
V = [0 for _ in range(N + 1)]
for i in range(1, N + 1):
    X[i], V[i] = map(int, input().split())
X_inv = [0]
X_inv.extend(list(map(lambda x: C - x, reversed(X)))[:N])
V_sum = to_cumsum(V)
V_inv = [0]
V_inv.extend(list(reversed(V))[:N])
V_inv_sum = to_cumsum(V_inv)

ans = 0
for i in range(N + 1):
    for j in range(N - i + 1):
        v = V_sum[i] + V_inv_sum[j]
        x1 = X[i] + 2 * X_inv[j]
        x2 = 2 * X[i] + X_inv[j]
        ans = max(ans, v - min(x1, x2))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,C = [int(x) for x in input().split()]
xv =[]
append1 = xv.append
for i in range(N):
  x1,v1 = [int(x) for x in input().split()]
  append1([x1,v1,i])
  append1([x1-C,v1,i])
xv.sort()
memo = [-1]*(N+1)
ans = 0
for i in range(2*N):
  for j in range(2*N-i):
    an = 0
    memo = [-1]*(N+1)
    kyo = min(abs(xv[i][0])+abs(xv[i][0]-xv[i+j][0]),abs(xv[i+j][0])+abs(xv[i][0]-xv[i+j][0]))
    for k in range(i,i+j+1):
      if memo[xv[k][2]]==-1:
        an += xv[k][1]
        memo[xv[k][2]] = 1
    ans = max(ans,an-kyo)
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

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

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

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

    return

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

    for i in range(n):
        ans = max(ans, clock_wise[i + 1] + max(clock_wise_rev[i + 2:]) - xv[i][0])
        ans = max(ans, clock_wise_rev[i + 1] + max(clock_wise[:i + 1]) - (c - xv[i][0]))
    print(ans)
    return

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

Submission status: Time Limit Exceeded

Solution code:
n,c = map(int,input().split())
data = []
for i in range(n):
    x,v = map(int,input().split())
    data.append([x,c-x,v])
ans = 0
for turn in range(n):
    now = -data[turn][0]
    for right in range(turn+1):
        now += data[right][2]

    ans = max(ans,now)
    now -= data[turn][0]

    for left in range(n-1,turn,-1):
        now += data[left][2]
        ans = max(ans,now-data[left][1])

for turn in range(n-1,-1,-1):
    now = -data[turn][1]
    for left in range(n-1,turn-1,-1):
        now += data[left][2]

    ans = max(ans,now)
    now -= data[turn][1]

    for right in range(turn):
        now += data[right][2]
        ans = max(ans,now-data[right][0])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,c=map(int,input().split())
sushi=[list(map(int,input().split())) for i in range(n)]
def route_b(sushi,n,c):
    box_a={0:0}
    box_b={0:0}

    point,count,add=0,0,0
    for x,y in sushi:
        point=max(point,count+y-x)
        count +=y
        add +=1
        box_a[add]=point

    point,count,add=0,0,0
    for x,y in sushi[::-1]:
        point=max(point,count+y-(c-x)*2)
        count +=y
        add +=1
        box_b[add]=point

    ans=0
    for i in range(n+1):ans=max(ans,box_a[i]+max([box_b[j] for j in range(n+1-i)]))
    return ans

def route_a(sushi,n,c):
    box_a = {0: 0}
    box_b = {0: 0}

    point, count, add = 0, 0, 0
    for x, y in sushi:
        point = max(point, count + y - x*2)
        count += y
        add += 1
        box_a[add] = point

    point, count, add = 0, 0, 0
    for x, y in sushi[::-1]:
        point = max(point, count + y - (c-x) )
        count += y
        add += 1
        box_b[add] = point

    ans = 0
    for i in range(n + 1): ans = max(ans, box_b[i] + max([box_a[j] for j in range(n + 1 - i)]))
    return ans

print(max(route_a(sushi,n,c),route_b(sushi,n,c)))

Submission status: Time Limit Exceeded

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

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

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

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

print(m)

Submission status: Time Limit Exceeded

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

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

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

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

print(m)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from itertools import accumulate
INF = float("inf")


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):

    # 時計回り
    m = -INF
    for i in range(N):
        cost = []
        benefit = []
        # i番目でターン
        for j in range(i+1):
            if j == 0:
                cost.append(x[j])
                benefit.append(v[j])
            else:
                cost.append(cost[-1]+x[j]-x[j-1])
                benefit.append(benefit[-1]+v[j])
        turn = x[j]
        for j in range(N-1, i, -1):
            if j == N-1:
                cost.append(cost[-1]+(C-x[j])+turn)
                benefit.append(benefit[-1]+v[j])
            else:
                cost.append(cost[-1]+(C-x[j])-(C-x[j+1]))
                benefit.append(benefit[-1]+v[j])
        callory = [b-c for c, b in zip(cost, benefit)]
        # print(callory, cost, benefit)
        m = max(m, max(callory))

    # 半時計回りな
    x = list(reversed([C-v for v in x]))
    v = list(reversed(v))
    for i in range(N):
        cost = []
        benefit = []
        # i番目でターン
        for j in range(i+1):
            if j == 0:
                cost.append(x[j])
                benefit.append(v[j])
            else:
                cost.append(cost[-1]+x[j]-x[j-1])
                benefit.append(benefit[-1]+v[j])
        turn = x[j]
        for j in range(N-1, i, -1):
            if j == N-1:
                cost.append(cost[-1]+(C-x[j])+turn)
                benefit.append(benefit[-1]+v[j])
            else:
                cost.append(cost[-1]+(C-x[j])-(C-x[j+1]))
                benefit.append(benefit[-1]+v[j])
        callory = [b-c for c, b in zip(cost, benefit)]
        # print(callory, cost, benefit)
        m = max(m, max(callory))

    print(max(0, m))
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    x = [int()] * (N)  # type: "List[int]"
    v = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        x[i] = int(next(tokens))
        v[i] = int(next(tokens))
    solve(N, C, x, v)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from itertools import accumulate
INF = float("inf")


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):

    # 時計回り
    m = -INF
    for i in range(N):
        cost = []
        benefit = []
        # i番目でターン
        for j in range(i+1):
            if j == 0:
                cost.append(x[j])
                benefit.append(v[j])
            else:
                cost.append(cost[-1]+x[j]-x[j-1])
                benefit.append(benefit[-1]+v[j])
        turn = x[j]
        for j in range(N-1, i, -1):
            if j == N-1:
                cost.append(cost[-1]+(C-x[j])+turn)
                benefit.append(benefit[-1]+v[j])
            else:
                cost.append(cost[-1]+(C-x[j])-(C-x[j+1]))
                benefit.append(benefit[-1]+v[j])
        callory = [b-c for c, b in zip(cost, benefit)]
        # print(callory, cost, benefit)
        m = max(m, max(callory))

    x = list(reversed([C-v for v in x]))
    v = list(reversed(v))
    for i in range(N):
        cost = []
        benefit = []
        # i番目でターン
        for j in range(i+1):
            if j == 0:
                cost.append(x[j])
                benefit.append(v[j])
            else:
                cost.append(cost[-1]+x[j]-x[j-1])
                benefit.append(benefit[-1]+v[j])
        turn = x[j]
        for j in range(N-1, i, -1):
            if j == N-1:
                cost.append(cost[-1]+(C-x[j])+turn)
                benefit.append(benefit[-1]+v[j])
            else:
                cost.append(cost[-1]+(C-x[j])-(C-x[j+1]))
                benefit.append(benefit[-1]+v[j])
        callory = [b-c for c, b in zip(cost, benefit)]
        # print(callory, cost, benefit)
        m = max(m, max(callory))

    print(max(0, m))
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    x = [int()] * (N)  # type: "List[int]"
    v = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        x[i] = int(next(tokens))
        v[i] = int(next(tokens))
    solve(N, C, x, v)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

    return max_v


n, c = map(int, input().split())
sushis = []
for _ in range(n):
    sushis.append([int(x) for x in input().split()])
print(solve(c, sushis))

Submission status: Time Limit Exceeded

Solution code:
###############################################################################

from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)


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


def main():
    n, c = intin()
    xvlist = [(0, 0)]
    xvlist.extend(intinl(n))

    ans = -float('inf')

    for i in range(n + 1):
        for j in range(i + 1):
            k = (n - i + 1) + j
            x1, _ = xvlist[j] if j > 0 else (0, 0)
            x2, _ = xvlist[k] if j < i else (c, 0)
            x2 = c - x2
            distance = min(x1, x2) * 2 + max(x1, x2)
            food = sum([v for x, v in xvlist[:(j+1)]]) + \
                   sum([v for x, v in xvlist[k:]])
            ans = max(ans, food - distance)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):

    ans = -INF
    hantokeix = [C-el for el in x][::-1]
    hantokeiv = v[::-1]
    for i in range(N):
        # 反時計にi個とってから時計回り
        tot = [0]
        j = 0
        curr = 0
        for j in range(i):
            tot.append(tot[-1] + hantokeiv[j]-(hantokeix[j]-curr))
            curr = hantokeix[j]
        # ターン
        curr = -curr
        for j in range(N-i):
            tot.append(tot[-1]+v[j]-(x[j]-curr))
            curr = x[j]
        sairyo = max(tot)
        ans = max(ans, sairyo)

    for i in range(N):
        # 時計周りにi個とってから反時計回り
        tot = [0]
        j = 0
        curr = 0
        for j in range(i):
            tot.append(tot[-1] + v[j]-(x[j]-curr))
            curr = x[j]
        # ターン
        curr = -curr
        for j in range(N-i):
            tot.append(tot[-1]+hantokeiv[j]-(hantokeix[j]-curr))
            curr = hantokeix[j]
        sairyo = max(tot)
        ans = max(ans, sairyo)

    print(ans)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    x = [int()] * (N)  # type: "List[int]"
    v = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        x[i] = int(next(tokens))
        v[i] = int(next(tokens))
    solve(N, C, x, v)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

ans = 0
Sv = [xv[0][1]]
for x,v in xv[1:-1]:
    Sv.append(Sv[-1]+v)
for i in range(N+1):
    for j in range(N+1-i):
        ans = max(ans,Sv[i]+(Sv[N]-Sv[N-j])-xv[i][0]-(C-xv[N+1-j][0]) - min(xv[i][0],(C-xv[N+1-j][0])))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import bisect

n, c = [int(item) for item in input().split()]

xs, vs, xrs = [], [], []
for i in range(n):
  x, v = [int(item) for item in input().split()]
  xs.append(x)
  xrs.append(c-x)
  vs.append(v)
xrs = xrs[::-1]

lft_v = list(accumulate(vs))
rgt_v = list(accumulate(vs[::-1]))

ans = 0
# No return
for i in range(n):
  ans = max(ans, lft_v[i]-xs[i], rgt_v[i]-xrs[i])
  
# Includes return
for i in range(n-1):
  for j in range(n-1-i):
    ans = max(ans, lft_v[i] - xs[i]*2 + rgt_v[j] - xrs[j])
    ans = max(ans, rgt_v[j] - xrs[j]*2 + lft_v[i] - xs[i])
    
print(ans)

Submission status: Time Limit Exceeded

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

re_lst = []
for i in reversed(range(n)):
    re_lst.append([abs(c-lst[i][0]), lst[i][1]])

r_accum = []
s = 0
for i in range(n):
    s += lst[i][1]
    r_accum.append(s)

l_accum = []
s = 0
for i in range(n):
    s += re_lst[i][1]
    l_accum.append(s)

r_max = 0
for i in range(n):
    r_max = max(r_max, r_accum[i] - lst[i][0])
    
l_max = 0
for i in range(n):
    l_max = max(l_max, l_accum[i] - re_lst[i][0])

rd_max = 0
for i in range(n):
    for j in range(n-i-1):
        pt = r_accum[i] - 2*lst[i][0]
        pt += l_accum[j] - re_lst[j][0]
        if pt > rd_max:
            rd_max = pt
            

ld_max = 0
for i in range(n):
    for j in range(n-i-1):
        pt = l_accum[i] - 2*re_lst[i][0]
        pt += r_accum[j] - lst[j][0]
        if pt > ld_max:
            ld_max = pt

print(max(r_max, l_max, rd_max, ld_max))

Submission status: Time Limit Exceeded

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

# 真上に0があると考える。下から⇢にいくか←にいくかで区別

#右方向に進んだときの累積Caloryと累積max
R_cal = [0 for i in range(N)]
R_max = [0 for i in range(N)]
for i in range(N):
    if i == 0:
        R_cal[i] = Xi[i][1] - Xi[i][0]
        R_max[i] = max(R_cal[i], 0)
    else:
        d = Xi[i][0] - Xi[i - 1][0]
        R_cal[i] = R_cal[i - 1] + Xi[i][1] - d
        R_max[i] = max(R_cal[i], R_max[i - 1])

#右方向に進んだときの累積max
L_cal = [0 for i in range(N)]
L_max = [0 for i in range(N)]
for i in range(N - 1, -1, -1):
    if i == N - 1:
        L_cal[i] = Xi[i][1] - (C - Xi[i][0])
        L_max[i] = max(L_cal[i], 0)
    else:
        d = Xi[i + 1][0] - Xi[i][0]
        L_cal[i] = L_cal[i + 1] + Xi[i][1] - d
        L_max[i] = max(L_cal[i], L_max[i + 1])

#右方向にとにかくすすむ
max_value = 0
for i in range(N):
    cal = R_cal[i]
    l_cal = 0
    if i < N - 1:
        l_cal = max(L_max[i + 1:]) - Xi[i][0]
    if l_cal > 0:
        cal += l_cal
    max_value = max(cal, max_value)
#左にとにかくすすむ
for i in range(N - 1, -1, -1):
    cal = L_cal[i]
    r_cal = 0
    if i > 0:
        r_cal = max(R_max[:i]) - (C - Xi[i][0])
    if r_cal > 0:
        cal += r_cal
    max_value = max(cal, max_value)
print(max_value)

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import accumulate

def main():
  input = sys.stdin.readline
  N, C = map(int, input().split())
  X = []
  V = []
  for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
  Vr = V[::-1]
  Xr = X[::-1]

  F = list(accumulate(V))
  for i in range(N):
    F[i] = F[i] - X[i]

  R = list(accumulate(Vr))
  for i in range(N):
    R[i] = R[i] - (C - Xr[i])

  val = 0
  for i in range(N-1):
    v1 = F[i] + max(R[:-(i+1)]) - X[i]
    v2 = R[i] + max(F[:-(i+1)]) - (C - Xr[i])
    val = max(val, v1, v2)
  
  ans = max(0, val, max(F), max(R))
  print(ans)


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import accumulate

def main():
  input = sys.stdin.readline
  N, C = map(int, input().split())
  X = []
  V = []
  for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
  Vr = V[::-1]
  Xr = X[::-1]
  
  
  R = list(accumulate(V))
  for i in range(N):
    R[i] = R[i] - X[i]

  L = list(accumulate(Vr))
  for i in range(N):
    L[i] = L[i] - (C - Xr[i])

  Rmax = max(R)
  Lmax = max(L)
  
  RLmax = 0
  for i in range(N-1):
    cur = R[i] + max(L[:-(i+1)]) - X[i]
    RLmax = max(RLmax, cur)
    if R[i] == Rmax:
      break
  
  LRmax = 0
  for i in range(N-1):
    cur = L[i] + max(R[:-(i+1)]) - (C - Xr[i])
    LRmax = max(LRmax, cur)
    if L[i] == Lmax:
      break
  
  ans = max(0, Rmax, Lmax, RLmax, LRmax)
  print(ans)


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import accumulate

def main():
  input = sys.stdin.readline
  N, C = map(int, input().split())
  X = []
  V = []
  for _ in range(N):
    x, v = map(int, input().split())
    X.append(x)
    V.append(v)
  Vr = V[::-1]
  Xr = X[::-1]
  
  
  R = list(accumulate(V))
  for i in range(N):
    R[i] = R[i] - X[i]

  L = list(accumulate(Vr))
  for i in range(N):
    L[i] = L[i] - (C - Xr[i])

  Rmax = max(R)
  Lmax = max(L)
  
  RLmax = 0
  for i in range(N-1):
    cur = R[i] + max(L[:-(i+1)]) - X[i]
    RLmax = max(RLmax, cur)
  
  LRmax = 0
  for i in range(N-1):
    cur = L[i] + max(R[:-(i+1)]) - (C - Xr[i])
    LRmax = max(LRmax, cur)
  
  ans = max(0, Rmax, Lmax, RLmax, LRmax)
  print(ans)


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
n, c = map(int, input().split())
sushi = [tuple(map(int, input().split())) for _ in range(n)]
def sumv(s):
    ret = 0
    for _, v in s:
        ret += v
    return ret
# counter clock wize till i
ccw = []
for i in range(n):
    score = sumv(sushi[:i+1]) - sushi[i][0]
    maxscore = score
    for j in range(1, n-i):
        score += sushi[n-j][1]
        maxscore = max(maxscore, score - (c - sushi[n-j][0]) - sushi[i][0])
    ccw.append(maxscore)
# clock wize till i
cw = []
for i in range(n):
    score = sumv(sushi[n-i-1:]) - (c - sushi[n-i-1][0])
    maxscore = score
    for j in range(n-i-1):
        score += sushi[j][1]
        maxscore = max(maxscore, score - sushi[j][0] - (c - sushi[n-i-1][0]))
    cw.append(maxscore)
print(max(max(ccw), max(cw), 0))

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

def main():
    n,c = map(int,input().split())
    x1,v1 = [0],[0]
    x2,v2 = [],[]
    for _ in range(n):
        a,b = map(int, input().split())
        x1.append(a)
        x2 = [c-a] + x2
        v1.append(b)
        v2 = [b] + v2
    x2 = [0] + x2
    v2 = [0] + v2

    v1, v2 = list(accumulate(v1)), list(accumulate(v2))

    f = [v2[i] - x2[i] for i in range(n+1)]
    f2 = [v2[i] - 2*x2[i] for i in range(n+1)]
    g1 = list(accumulate(f, max))
    g2 = list(accumulate(f2, max))
    val = max(v1[n]-x1[n] + g2[0], v1[n]-2*x1[n] + g1[0])
    for i in range(1,n+1):
        val = max(val, v1[n-i]-x1[n-i] + g2[i], v1[n-i]-2*x1[n-i] + g1[i])

    print(val)

if __name__=='__main__': main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

n,c = map(int,input().split())
x1,v1 = [0],[0]
x2,v2 = [],[]
for _ in range(n):
  a,b = map(int, input().split())
  x1.append(a)
  x2 = [c-a] + x2
  v1.append(b)
  v2 = [b] + v2
x2 = [0] + x2
v2 = [0] + v2

v1, v2 = list(accumulate(v1)), list(accumulate(v2))

f1 = [v1[i] - x1[i] for i in range(n+1)]
f2 = [v2[i] - x2[i] for i in range(n+1)]
g1,x1_ = f1[0],x1[0]
g2,x2_ = f2[0],x2[0]
val = max(v1[n]-x1[n] + g2 - min(x1[n],x2_), v2[n]-x2[n] + g1 - min(x2[n],x1_))
for i in range(1,n+1):
  if g1<f1[i]:
	  g1,x1_ = f1[i], x1[i]
  if g2<f2[i]:
	  g2,x2_ = f2[i], x2[i]
  val = max(val, v1[n-i]-x1[n-i] + g2 - min(x1[n-i],x2_), v2[n-i]-x2[n-i] + g1 - min(x2[n-i],x1_))

print(val)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

n,c = map(int,input().split())
x1,v1 = [0],[0]
x2,v2 = [],[]
for _ in range(n):
  a,b = map(int, input().split())
  x1.append(a)
  x2 = [c-a] + x2
  v1.append(b)
  v2 = [b] + v2
x2 = [0] + x2
v2 = [0] + v2

v1, v2 = list(accumulate(v1)), list(accumulate(v2))
res = 0
for i in range(n+1):
  for j in range(n+1-i):
    cost = v1[i] + v2[j] - x1[i] - x2[j] - min(x1[i],x2[j])
    if cost > res:
      res = cost
print(res)