Problem:


Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

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

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

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

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

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

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

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

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

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

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

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

Sample Input 4

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

Sample Output 4

6500000000

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



Sample input:
3 20
2 80
9 120
16 1


Sample output:
191

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, C = mapint()

Xs = []
Vs = []
for _ in range(N):
    x, v = mapint()
    Xs.append(x)
    Vs.append(v)
r_Xs = [C-x for x in Xs[::-1]]
r_Vs = Vs[::-1]

max_neg = []
tmp = 0
maxi = -10**18
for i in range(N):
    x, v = r_Xs[i], r_Vs[i]
    tmp += v
    max_neg.append(max(tmp-x, maxi))
    maxi = max(tmp-x, maxi)

max_pos = []
tmp = 0
maxi = -10**18
for i in range(N):
    x, v = Xs[i], Vs[i]
    tmp += v
    max_pos.append(max(tmp-x, maxi))
    maxi = max(tmp-x, maxi)
ans = -1
for i in range(N):
    x, v = Xs[i], Vs[i]
    if i!=N-1:
        ans = max(ans, max_pos[i], max_pos[i]-x+max_neg[N-i-2])
    else:
        ans = max(ans, max_pos[i])
for i in range(N):
    x, v = r_Xs[i], r_Vs[i]
    if i!=N-1:
        ans = max(ans, max_neg[i], max_neg[i]-x+max_pos[N-i-2])
    else:
        ans = max(ans, max_neg[i])
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class SegmentTree:
    def __init__(self, array, operator, identity_element):
        _len = len(array)
        self.__op = operator
        self.__size = 1 << (_len - 1).bit_length()
        self.__tree = [identity_element] * self.__size + \
            array + [identity_element] * (self.__size - _len)
        self.__ie = identity_element

        for i in range(self.__size - 1, 0, -1):
            self.__tree[i] = operator(
                self.__tree[i * 2], self.__tree[i * 2 + 1])

    def update(self, i, v):
        i += self.__size
        self.__tree[i] = v
        while i:
            i //= 2
            self.__tree[i] = self.__op(
                self.__tree[i * 2], self.__tree[i * 2 + 1])

    def query(self, l, r):
        """[l, r)
        """
        l += self.__size
        r += self.__size
        ret = self.__ie
        while l < r:
            if l & 1:
                ret = self.__op(ret, self.__tree[l])
                l += 1
            if r & 1:
                r -= 1
                ret = self.__op(ret, self.__tree[r])
            l //= 2
            r //= 2
        return ret

    def __getitem__(self, key):
        return self.__tree[key + self.__size]


@mt
def slv(N, C, XV):
    XV.sort()
    ans = 0
    sf = [(0, 0)]
    stf = SegmentTree([-INF]*N, max, -INF)
    c = 0
    for i, (x, v) in enumerate(XV):
        v = sf[-1][0]+v-(x-c)
        sf.append((v, x))
        stf.update(i, v)
        c = x


    str_ = SegmentTree([-INF]*N, max, -INF)
    sr = [(0, 0)]
    c = 0
    for i, (x, v) in enumerate(reversed(XV)):
        x = C - x
        v = sr[-1][0]+v-(x-c)
        sr.append((v, x))
        str_.update(i, v)
        c = x

    ans = 0
    for i in range(N+1):
        t = sf[i][0] + max(0, str_.query(0, N-i-1) - sf[i][1])
        ans = max(ans, t)
        t = sr[i][0] + max(0, stf.query(0, N-i-1) - sr[i][1])
        ans = max(ans, t)
    return ans


def main():
    N, C = read_int_n()
    XV = [read_int_n() for _ in range(N)]
    print(slv(N, C, XV))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
R = [[0, 0]]
L = [[0, 0]]
R_half = -1
for i in range(N):
    x, v = map(int, input().split())
    R.append([x, v])
    if x < C//2 + 1:
        R_half = i
for i in R[::-1]:
    L.append([C - i[0], i[1]])
L.pop(-1)
R_half += 1
L_half = N - R_half

R_sum = [0]
L_sum = [0]
R_sum2 = [0]
L_sum2 = [0]
total_1 = 0
total_2 = 0
total_3 = 0
total_4 = 0
for i in range(1, N + 1):
    total_1 += R[i][1] - (R[i][0] - R[i-1][0])
    total_2 += L[i][1] - (L[i][0] - L[i-1][0])
    total_3 += R[i][1] - 2*(R[i][0] - R[i-1][0])
    total_4 += L[i][1] - 2*(L[i][0] - L[i-1][0])
    R_sum.append(total_1)
    L_sum.append(total_2)
    R_sum2.append(total_3)
    L_sum2.append(total_4)
result_1 = max(R_sum)
result_2 = max(L_sum)
result_3 = max(R_sum[:R_half+1]) + max(L_sum2[:L_half+1])
result_4 = max(L_sum[:L_half+1]) + max(R_sum2[:R_half+1])
print(max([result_1, result_2, result_3, result_4]))

Submission status: Wrong Answer

Solution code:
N, C = map(int, input().split())
R = [[0, 0]]
L = [[0, 0]]
R_half = -1
for i in range(N):
    x, v = map(int, input().split())
    R.append([x, v])
    if x <= C/2:
        R_half = i
for i in R[::-1]:
    L.append([C - i[0], i[1]])
L.pop(-1)
R_half += 1
L_half = N - R_half

R_sum = [0]
L_sum = [0]
R_sum2 = [0]
L_sum2 = [0]
total_1 = 0
total_2 = 0
total_3 = 0
total_4 = 0
for i in range(1, N + 1):
    total_1 += R[i][1] - (R[i][0] - R[i-1][0])
    total_2 += L[i][1] - (L[i][0] - L[i-1][0])
    total_3 += R[i][1] - 2*(R[i][0] - R[i-1][0])
    total_4 += L[i][1] - 2*(L[i][0] - L[i-1][0])
    R_sum.append(total_1)
    L_sum.append(total_2)
    R_sum2.append(total_3)
    L_sum2.append(total_4)
result_1 = max(R_sum)
result_2 = max(L_sum)
result_3 = max(R_sum[:R_half+1]) + max(L_sum2[:L_half+1])
result_4 = max(L_sum[:L_half+1]) + max(R_sum2[:R_half+1])
print(max([result_1, result_2, result_3, result_4]))

Submission status: Wrong Answer

Solution code:
def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()

    n, c = map(int, input().split())
    # v: cumulative sum
    x, v = [0] * (n+2), [0] * (n+2)
    for i in range(n):
        j, k = map(int, input().split())
        x[i+1] = j
        v[i+1] = v[i] + k
    x[n+1] = c
    v[n+1] = v[n]
    
    max_nut_clockwise = [0] * (n+1)
    for i in range(1, n+1):
        max_nut_clockwise[i] = max(max_nut_clockwise[i-1], v[i] - x[i])
    max_nut_counterclockwise = [0] * (n+1)
    for i in range(n-1, -1, -1):
        max_nut_counterclockwise[i] = max(max_nut_counterclockwise[i+1], v[-1] - v[i] - c + x[i+1])

    ans = 0
    # rotate clockwise, then rotate counterclockwise
    for i in range(n):
        if ans < v[i] - 2*x[i] + max_nut_counterclockwise[i]:
            ans = v[i] - 2*x[i] + max_nut_counterclockwise[i]
    # rotate counterclockwise, then rotate clockwise
    for i in range(2, n+2):
        if ans < v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]:
            ans = v[-1] - v[i-1] - 2 * (c - x[i]) + max_nut_clockwise[i-1]
    
    print(ans)

    print(x)
    print(v)
    print(max_nut_clockwise)
    print(max_nut_counterclockwise)

main()

Submission status: Wrong Answer

Solution code:
n,C = map(int,input().split())
distance_ls = [0] * n
value_ls = [0] * n
for i in range(n):
    x,v = map(int,input().split())
    distance_ls[i] = x
    value_ls[i] = v

# right_best[i] = 右のi番目の寿司まで存在する時、0始点での最適な[cost,value]
right_best = [[0,0] for _ in range(n)]
total_value = 0
best = [0,0]
for i in range(n):
    total_value += value_ls[i]
    cost = distance_ls[i]
    if best[1] - best[0] <= total_value - cost:
        best = [cost,total_value]
    right_best[i] = best

# 初期値：反時計回りには動かない時の、最高の利益
ans = right_best[-1][1] - right_best[-1][0]
total_value = 0
for i in range(-1,-n,-1):
    # インデックスiの寿司まで反時計回りで行って、食べる
    cost = C-distance_ls[i]
    total_value += value_ls[i]
    profit = total_value - cost
    ans = max(ans,profit)
    # 右の最適なところまで行く
    profit = profit - cost + right_best[i-1][1] - right_best[i-1][0]
    ans = max(ans,profit)

    # 先にright_best[i-1]をとる
    profit = right_best[i-1][1] - right_best[i-1][0]
    ans = max(ans,profit)
    # # インデックスiの寿司まで反時計回りで行って、食べる
    profit = profit - right_best[i-1][0] + total_value - cost
    ans = max(profit,ans)
# ずっと反時計の時
cost = C - distance_ls[0]
value = total_value + value_ls[0]
ans = max(ans,value-cost)
print(ans)

Submission status: Wrong Answer

Solution code:
n,C = map(int,input().split())
distance_ls = [0] * n
value_ls = [0] * n
for i in range(n):
    x,v = map(int,input().split())
    distance_ls[i] = x
    value_ls[i] = v

# right_best[i] = 右のi番目の寿司まで存在する時、0始点での最適な[cost,value]
right_best = [[0,0] for _ in range(n)]
total_value = 0
best = [0,0]
for i in range(n):
    total_value += value_ls[i]
    cost = distance_ls[i]
    if best[1] - best[0] <= total_value - cost:
        best = [cost,total_value]
    right_best[i] = best

# 初期値：反時計回りには動かない時の、最高の利益
ans = right_best[-1][1] - right_best[-1][0]
total_value = 0
for i in range(-1,-n,-1):
    # インデックスiの寿司まで反時計回りで行って、食べる
    cost = C-distance_ls[i]
    total_value += value_ls[i]
    profit = total_value - cost
    ans = max(ans,profit)
    # 右の最適なところまで行く
    profit = profit - cost + right_best[i-1][1] - right_best[i-1][0]
    ans = max(ans,profit)

    # 先にright_best[i]をとる
    profit = right_best[i-1][1] - right_best[i-1][0]
    ans = max(ans,profit)
    # # インデックスiの寿司まで反時計回りで行って、食べる
    profit = profit - right_best[i-1][0] + total_value - cost
    ans = max(profit,ans)
# ずっと反時計の時
cost = C - distance_ls[0]
value = value_ls[0]
ans = max(ans,value-cost)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


class HeapSet:
    def __init__(self):
        self.minQue = []
        self.maxQue = []
        self.counter = defaultdict(lambda: 0)

    def insert(self, x):
        heappush(self.minQue, x)
        heappush(self.maxQue, -x)
        self.counter[x] += 1

    def delete(self, x):
        self.counter[x] = max(0, self.counter[x] - 1)

    def get_max(self):
        while self.maxQue and self.counter[-self.maxQue[0]] == 0:
            heappop(self.maxQue)
        return -self.maxQue[0] if self.maxQue else None

    def get_min(self):
        while self.minQue and self.counter[self.minQue[0]] == 0:
            heappop(self.minQue)
        return self.minQue[0] if self.minQue else None

    def __str__(self):

        min = []
        sl = sorted(list(set(self.minQue)))
        for i in range(len(sl)):
            if self.counter[sl[i]]:
                min += [sl[i]] * self.counter[sl[i]]

        return min.__str__()


def main():

    N, C = in_nn()
    xv = []

    for i in range(N):
        x, v = in_nn()
        xv.append((x, v))

    if N == 1:
        ans = 0
        x, v = xv[0]
        ans = max(ans, v - min(x, C - x))
        print(ans)
        exit()

    xv.sort()

    tsum = [0] * (N + 1)
    for i in range(N):
        tsum[i + 1] = tsum[i] + xv[i][1]

    for i in range(N):
        tsum[i + 1] -= xv[i][0]

    rev_tsum = [0] * (N + 1)
    for i in range(N):
        rev_tsum[i + 1] = rev_tsum[i] + xv[N - 1 - i][1]

    for i in range(N):
        rev_tsum[i + 1] -= C - xv[N - 1 - i][0]

    heap = HeapSet()

    for i in range(N + 1):
        heap.insert(tsum[i])

    # print(tsum)
    # print(rev_tsum)
    # print(dmin)

    ans = heap.get_max()
    for i in range(1, N + 1):
        heap.delete(tsum[N + 1 - i])
        v1 = heap.get_max()
        v2 = rev_tsum[i]
        c2 = C - xv[N - i][0]
        value = v1 + v2 - c2
        ans = max(ans, value)

    heap2 = HeapSet()
    for i in range(N + 1):
        heap2.insert(rev_tsum[i])

    for i in range(1, N + 1):
        heap2.delete(rev_tsum[N + 1 - i])
        v1 = heap2.get_max()
        v2 = tsum[i]
        c2 = xv[i - 1][0]
        value = v1 + v2 - c2
        ans = max(ans, value)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


class HeapSet:
    def __init__(self):
        self.minQue = []
        self.maxQue = []
        self.counter = defaultdict(lambda: 0)

    def insert(self, x):
        heappush(self.minQue, x)
        heappush(self.maxQue, -x)
        self.counter[x] += 1

    def delete(self, x):
        self.counter[x] = max(0, self.counter[x] - 1)

    def get_max(self):
        while self.maxQue and self.counter[-self.maxQue[0]] == 0:
            heappop(self.maxQue)
        return -self.maxQue[0] if self.maxQue else None

    def get_min(self):
        while self.minQue and self.counter[self.minQue[0]] == 0:
            heappop(self.minQue)
        return self.minQue[0] if self.minQue else None

    def __str__(self):

        min = []
        sl = sorted(list(set(self.minQue)))
        for i in range(len(sl)):
            if self.counter[sl[i]]:
                min += [sl[i]] * self.counter[sl[i]]

        return min.__str__()


def main():

    N, C = in_nn()
    xv = []

    for i in range(N):
        x, v = in_nn()
        xv.append((x, v))

    if N == 1:
        ans = 0
        x, v = xv[0]
        ans = max(ans, v - min(x, C - x))
        print(ans)
        exit()

    xv.sort()

    tsum = [0] * (N + 1)
    for i in range(N):
        tsum[i + 1] = tsum[i] + xv[i][1]

    for i in range(N):
        tsum[i + 1] -= xv[i][0]

    dmin = defaultdict(lambda: INF)
    dmin[0] = 0
    for i in range(1, N + 1):
        dmin[tsum[i]] = min(dmin[tsum[i]], xv[i - 1][0])

    rev_tsum = [0] * (N + 1)
    for i in range(N):
        rev_tsum[i + 1] = rev_tsum[i] + xv[N - 1 - i][1]

    for i in range(N):
        rev_tsum[i + 1] -= C - xv[N - 1 - i][0]

    heap = HeapSet()

    for i in range(N + 1):
        heap.insert(tsum[i])

    # print(tsum)
    # print(rev_tsum)
    # print(dmin)

    ans = heap.get_max()
    for i in range(1, N + 1):
        heap.delete(tsum[N + 1 - i])
        v1 = heap.get_max()
        v2 = rev_tsum[i]
        c1 = dmin[v1]
        c2 = C - xv[N - i][0]
        value = v1 + v2 - min(c1, c2)
        ans = max(ans, value)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


class HeapSet:
    def __init__(self):
        self.minQue = []
        self.maxQue = []
        self.counter = defaultdict(lambda: 0)

    def insert(self, x):
        heappush(self.minQue, x)
        heappush(self.maxQue, -x)
        self.counter[x] += 1

    def delete(self, x):
        self.counter[x] = max(0, self.counter[x] - 1)

    def get_max(self):
        while self.maxQue and self.counter[-self.maxQue[0]] == 0:
            heappop(self.maxQue)
        return -self.maxQue[0] if self.maxQue else None

    def get_min(self):
        while self.minQue and self.counter[self.minQue[0]] == 0:
            heappop(self.minQue)
        return self.minQue[0] if self.minQue else None

    def __str__(self):

        min = []
        sl = sorted(list(set(self.minQue)))
        for i in range(len(sl)):
            if self.counter[sl[i]]:
                min += [sl[i]] * self.counter[sl[i]]

        return min.__str__()


def main():

    N, C = in_nn()
    xv = []

    for i in range(N):
        x, v = in_nn()
        xv.append((x, v))

    if N == 1:
        ans = 0
        x, v = xv[0]
        ans = max(ans, v - min(x, C - x))
        print(ans)
        exit()

    xv.sort()

    tsum = [0] * (N + 1)
    for i in range(N):
        tsum[i + 1] = tsum[i] + xv[i][1]

    for i in range(N):
        tsum[i + 1] -= xv[i][0]

    dmin = defaultdict(lambda: INF)
    dmin[0] = 0
    for i in range(1, N + 1):
        dmin[tsum[i]] = min(dmin[tsum[i]], xv[i - 1][0])

    rev_tsum = [0] * (N + 1)
    for i in range(N):
        rev_tsum[i + 1] = rev_tsum[i] + xv[N - 1 - i][1]

    for i in range(N):
        rev_tsum[i + 1] -= C - xv[N - 1 - i][0]

    heap = HeapSet()

    for i in range(N + 1):
        heap.insert(tsum[i])

    # print(tsum)
    # print(rev_tsum)
    # print(dmin)

    ans = 0
    for i in range(N + 1):
        v1 = heap.get_max()
        v2 = rev_tsum[i]
        c1 = dmin[v1]
        if 0 <= N - i < N:
            c2 = C - xv[N - i][0]
        else:
            c2 = 0
        value = v1 + v2 - min(c1, c2)
        ans = max(ans, value)
        heap.delete(tsum[N - i])

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N, C = in_nn()
    xv = []

    for i in range(N):
        x, v = in_nn()
        xv.append((x, v))

    if N == 1:
        ans = 0
        x, v = xv[0]
        ans = max(ans, v - min(x, C - x))
        print(ans)
        exit()

    xv.sort()

    tsum = [0] * (N + 1)
    for i in range(N):
        tsum[i + 1] = tsum[i] + xv[i][1]

    ans = 0
    for i in range(N):
        d = xv[i][0]
        v = tsum[i + 1]
        ans = max(ans, v - d)

    for i in range(N - 1, -1, -1):
        d = C - xv[i][0]
        v = tsum[N] - tsum[i]
        ans = max(ans, v - d)

    for i in range(N):
        for j in range(N - 1, i + 1, -1):
            d1 = xv[i][0]
            d2 = C - xv[j][0]
            d = d1 + d2 + min(d1, d2)
            v = tsum[i + 1] + tsum[N] - tsum[j]
            ans = max(ans, v - d)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


n, c = list(map(int, input().split()))
xv = [[0, 0]]+[list(map(int, input().split())) for i in range(n)] + [[c, 0]]
xv_rev = reversed(xv)

# print(xv)
ans = 0

cal = 0
for i in range(1, len(xv)):
    cal += xv[i][1]
    cal -= (xv[i][0]-xv[i-1][0])
    ans = max(cal, ans)

cal = 0
for i in range(1, len(xv)):
    cal += xv[-1-i][1]
    cal -= (xv[-i][0]-xv[-1-i][0])
    ans = max(cal, ans)


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



n, c = LI()
clock_pos = []
value = []
for pos, v in LIR(n):
    clock_pos += [pos]
    value += [v]

r1 = 0
r2 = 0
A1 = [0]
A2 = [0]
for i in range(n):
    r1 += value[i]
    r2 += value[-i - 1]
    A1 += [max(A1[i], r1 - clock_pos[i])]
    A2 += [max(A2[i], r2 - (c - clock_pos[-i-1]))]

ans = 0
for j in range(n-1):
    ans = max(ans, A1[j+1] + A2[n - j - 1] - clock_pos[j], A2[j+1] + A1[n - j - 1] - (c - clock_pos[-j-1]))

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

N, C = map(int, sys.stdin.readline().split())

sushi_set = []
for i in range(N):
    x, v = map(int, sys.stdin.readline().split())
    sushi_set.append((x, v))
sushi_set.sort()

ans = -1

# right
# 方向転換は一回まででと考えて良いのではないか？
right = [0 for _ in range(N)]
max_n = -float("inf")
energy = 0
right_back = [0 for _ in range(N)]
for i, (x, v) in enumerate(sushi_set):
    energy += v
    if energy - x > max_n:
        max_n = energy - x
    right[i] = max_n
    right_back[i] = energy - 2 * x

# left
left = [0 for _ in range(N)]
max_n = -float("inf")
energy = 0
left_back = [0 for _ in range(N)]
for i, (x, v) in enumerate(sushi_set[::-1]):
    energy += v
    if energy - (C - x) > max_n:
        max_n = energy - (C - x)
    left[i] = max_n
    left_back[i] = energy - 2 * (C - x)

# print("right", right)
# print("right_back", right_back)
# print("left", left)
# print("left_back", left_back)

ans = max(max(right), max(left))
# print(ans)
# right -> left
for i in range(N-1):
    ans = max(ans, right_back[i] + left[N-2-i])
# left -> right
for i in range(1, N-1):
    ans = max(ans, left_back[i] + right[N-2-i])

print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
import numpy as np
import itertools
N, C, *XV = [int(_) for _ in open(0).read().split()]
XV = [0, 0] + XV
XV = np.array(XV).reshape((N+1, 2))
YV = np.zeros((N+1, 2), dtype=np.int64)
YV[1:] = XV[:0:-1]
YV[1:, 0] *= -1
YV[1:, 0] += C

cumxvv = np.cumsum(XV[:, 1])
cumxvv -= XV[:, 0]
cumyvv = np.cumsum(YV[:, 1])
cumyvv -= YV[:, 0]
ans=-float('inf')
for i, j in itertools.product(range(N), repeat=2):
    if i + j > N:
        continue
    ans = max(ans, cumxvv[i] + cumyvv[j] - min(XV[i,0], YV[j,0]))
print(ans)

Submission status: Wrong Answer

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


g = [0] * (N+1)
for i in range(N-1, -1, -1):
  g[i] = g[i+1] + V[i]
  
f1 = [0] * (N+1)
f2 = [0] * (N+1)
h1 = [0] * (N+1)
h2 = [0] * (N+1)
f1[0] = V[0] - X[0]
f2[0] = V[0] - 2*X[0]
h1[0] = f1[0]
h2[0] = f2[0]
for i in range(1, N):
  f1[i] = f1[i-1] + V[i] + X[i-1] - X[i]
  h1[i] = max(h1[i-1], f1[i])
for i in range(1, N):
  f2[i] = f2[i-1] + V[i] + 2*X[i-1] - 2*X[i]
  h2[i] = max(h2[i-1], f2[i])
  
max1 = 0
max2 = 0
#反時計周り→時計周りにおける最大値max1を考える
for k in range(N, -1, -1):
  max1 = max(max1, h1[(k-1)%(N+1)]+g[k]-2*(C-X[k]))
#時計周り→反時計周りにおける最大値max2を考える
for k in range(N, -1, -1):
  max2 = max(max2, h2[(k-1)%(N+1)]+g[k]-(C-X[k]))
print(max(max1, max2))

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

n, c = (int(x) for x in input().split())
X = []
V = []
D = []
prev_x = 0
for _ in range(n):
    x, v = (int(x) for x in input().split())
    X.append(x)
    D.append(x - prev_x)
    V.append(v)
    prev_x = x
D.append(c - X[-1])
rev_D = list(reversed(D))
rev_V = list(reversed(V))

ans = 0
# 時計回り
A = [0] * n
for i in range(n):
    A[i] = V[i] - D[i]
acc_A = list(accumulate(A))
ans = max(ans, max(acc_A))

# 反時計回り
B = [0] * n
for i in range(n):
    B[i] = rev_V[i] - rev_D[i]
acc_B = list(accumulate(B))
ans = max(ans, max(acc_B))

max_acc_A = [acc_A[0]]
max_acc_B = [acc_B[0]]
for i in range(1, n):
    max_acc_A.append(max(max_acc_A[-1], acc_A[i]))
    max_acc_B.append(max(max_acc_B[-1], acc_B[i]))

# 時計回りからの反時計回り i個まで食べて向きを変える
tmp = 0
for i in range(n - 1):
    tmp_cal = acc_A[i] - X[i]  # 食べて原点まで戻った時点のカロリー
    tmp = max(tmp, tmp_cal + max_acc_B[n - i - 1])
ans = max(ans, tmp)

# 反時計回りからの時計回り
tmp = 0
for i in range(n - 1):
    tmp_cal = acc_B[i] - (c - X[-i - 1])  # 食べて原点まで戻った時点のカロリー
    tmp = max(tmp, tmp_cal + max_acc_A[n - i - 1])
ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
import copy
N,C = map(int, input().split())

X = []

for i in range(N):
  x,c = map(int, input().split())
  X.append((x,c))
  
PS = [[0,0,0,0]]
QS = [[0,0,0,0]]

# PS[i] = x,c0,c1,c2
# x:右回りの距離
# c0:累積カロリー
# c1:右回りで得られるコスト（行きのxのロス組み込み
# c2:右回り＋Oに帰るまでで得られるコスト

for i in range(N):
  xx,c0,c1,c2 = PS[i]
  x,c = X[i]
  PS.append([x, c0+c, c0+c-x, c0+c-2*x])

for i in range(N):
  xx,c0,c1,c2 = QS[i]
  x,c = X[N-i-1]
  x = C-x
  QS.append([x, c0+c, c0+c-x, c0+c-2*x])

PS = np.array(PS)  
QS = np.array(QS)

#print(PS)
#print(QS)

ans = 0
# OP, PO, OQの流れ
# OQの選ぶべき値は探索する必要がない？
QIDX = [0] * N
histmax, histi = 0,0
for q in range(1,N):
  if histmax < QS[q][2]:
    histmax, histi = QS[q][2], q
  QIDX[q] = histi
  
PIDX = [0] * N
histmax, histi = 0,0
for p in range(1,N):
  if histmax < PS[p][2]:
    histmax, histi = PS[p][2], p
  PIDX[p] = histi

for p in range(N):
  wk = PS[p][3] + QS[QIDX[N-p-1]][2]
  ans = max(ans, wk)

for q in range(N):
  wk = QS[q][3] + PS[PIDX[N-q-1]][2]
  ans = max(ans, wk)

print(ans)

Submission status: Wrong Answer

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

cumR=[0]*(N+1)
cummaxR=[0]*(N+1)
for i in range(N):
    cumR[i+1]=cumR[i]+li[i][1]-li[i][0]
    cummaxR[i+1]=cummaxR[i]+li[i][1]-li[i][0]*2
    if i>0:
        cumR[i+1]+=li[i-1][0]
        cummaxR[i+1]+=li[i-1][0]*2
for i in range(1,N):
    cummaxR[i]=max(cummaxR[i],cummaxR[i-1])
cumL=[0]*(N+1)
cummaxL=[0]*(N+1)
for i in reversed(range(N)):
    cumL[i]=cumL[i+1]+li[i][1]-(C-li[i][0])
    cummaxL[i]=cummaxL[i+1]+li[i][1]-(C-li[i][0])*2
    if i<N-1:
        cumL[i]+=(C-li[i+1][0])
        cummaxL[i]+=(C-li[i+1][0])*2
for i in reversed(range(N)):
    cummaxL[i]=max(cummaxL[i],cummaxL[i+1])
ans=0
for i in range(N):
    res=cumR[i]+cummaxL[i+1]
    ans=max(ans,res)
    if i>0:
        res2=cumL[i]+cummaxR[i-1]
        ans=max(ans,res2)
    else:
        ans=max(ans,cummaxR[N-1])
        
print(ans)