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:
#!/usr/bin/env python3
import sys
try:
    from typing import List
except ImportError:
    pass


def solve(N: int, C: int, x: "List[int]", v: "List[int]"):
    mp1 = [0] * (N + 1)
    mp2 = [0] * (N + 1)
    cum = 0
    for i in range(N):
        cum += v[i]
        mp1[i + 1] = max(mp1[i], cum - x[i])
        mp2[i + 1] = max(mp2[i], cum - x[i] * 2)
    mn1 = [0] * (N + 1)
    mn2 = [0] * (N + 1)
    cum = 0
    for i in reversed(range(N)):
        cum += v[i]
        mn1[i] = max(mn1[i + 1], cum - (C - x[i]))
        mn2[i] = max(mn2[i + 1], cum - (C - x[i]) * 2)

    print(max(
        max(mp1[i] + mn2[i] for i in range(N + 1)),
        max(mp2[i] + mn1[i] for i in range(N + 1)),
    ))


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: Accepted

Solution code:
N, C = map(int, input().split())

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

left = [0] * N
left2 = [0] * N
right = [0] * N
right2 = [0] * N

d = 0
d2 = 0
cal = 0
for i in range(N):
    x, v = sushi[i]
    d = x
    d2 = x * 2
    cal += v
    if i == 0:
        right[i] = max(cal - d, 0)
        right2[i] = max(cal - d2, 0)
    else:
        right[i] = max(cal - d, right[i-1])
        right2[i] = max(cal - d2, right2[i-1])

d = 0
d2 = 0
cal = 0
for i in reversed(range(N)):
    x, v = sushi[i]
    d = C - x
    d2 = (C - x) * 2
    cal += v
    if i == 0:
        left[i] = max(cal - d, 0)
        left2[i] = max(cal - d2, 0)
    else:
        left[i] = max(cal - d, left[i-1])
        left2[i] = max(cal - d2, left[i-1])

ans = 0
# 左側を全部試す
for i in range(N):
    if i == 0:
        ans = max(ans, left[i])
    else:
        ans = max(ans, left[i] + right2[i-1])
# 右側を全部試す
for i in range(N):
    if i == N - 1:
        ans = max(ans, right[i])
    else:
        ans = max(ans, right[i] + left2[i+1])

print(ans)

Submission status: Accepted

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

pre_xn_sum = [ (Xn[0][1] - Xn[0][0]*2,0) ] # (s,max_idx)
post_xn_sum = []

def get_pre_xn_sum(distance=1):
    pre_xn_sum = [ (Xn[0][1] - Xn[0][0]*distance,0) ] # (s,max_idx)
    for i in range(1,N):
        cuurent_v = pre_xn_sum[i-1][0] + Xn[i][1] - ( Xn[i][0] - Xn[i-1][0] ) *distance
        previous_max_idx = pre_xn_sum[i-1][1]
        if pre_xn_sum[previous_max_idx][0] > cuurent_v:
            max_idx = previous_max_idx
        else:
            max_idx = i
        pre_xn_sum.append((cuurent_v,max_idx))
    return pre_xn_sum

def get_post_xn_sum(distance=1):
    post_xn_sum = [ (Xn[N-1][1] - (C-Xn[N-1][0])*distance,0) ] # (s,max_idx)
    for i in range(1,N):
        xn_i = N - 1 - i
        cuurent_v = post_xn_sum[i-1][0] + Xn[xn_i][1] - ( Xn[xn_i+1][0] - Xn[xn_i][0] ) *distance
        previous_max_idx = post_xn_sum[i-1][1]
        if post_xn_sum[previous_max_idx][0] > cuurent_v:
            max_idx = previous_max_idx
        else:
            max_idx = i
        post_xn_sum.append((cuurent_v,max_idx))
    return post_xn_sum

pre_xn_sum = get_pre_xn_sum(1)
pre_xn_sum_2 = get_pre_xn_sum(2)
post_xn_sum = get_post_xn_sum(1)
post_xn_sum_2 = get_post_xn_sum(2)

ans_1 = 0
ans_2 = 0

# pre_xn_sum && post_xn_sum_2
for i in range(N+1):
    x = i -1
    y = N - 1 - i
    tmp_ans = 0
    if x >= 0:
        x_max_idx = pre_xn_sum[x][1]
        x_max = pre_xn_sum[x_max_idx][0]
        tmp_ans += max(x_max,0)
    if y >= 0:
        y_max_idx = post_xn_sum_2[y][1]
        y_max = post_xn_sum_2[y_max_idx][0]
        tmp_ans += max(y_max,0) 
    ans_1 = max(ans_1,tmp_ans)

# pre_xn_sum && post_xn_sum_2
for i in range(N+1):
    x = i -1
    y = N - 1 - i
    tmp_ans = 0
    if x >= 0:
        x_max_idx = pre_xn_sum_2[x][1]
        x_max = pre_xn_sum_2[x_max_idx][0]
        tmp_ans += max(x_max,0)
    if y >= 0:
        y_max_idx = post_xn_sum[y][1]
        y_max = post_xn_sum[y_max_idx][0]
        tmp_ans += max(y_max,0) 
    ans_1 = max(ans_1,tmp_ans)

print(max(ans_1,ans_2))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc095/tasks/arc096_b
# 写真参考


import sys
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations, accumulate
from bisect import bisect_left, bisect_right  # , insort_left, insort_right


N, C = read_ints()
X, V = read_col(N)


def solve_max_a_plas_b(A: list, B: list):
    '''max_{i<j}(a_i + b_j)をO(n)で解く'''
    assert len(A) == len(B)
    A_accum = list(accumulate(A, func=max))
    B_accum = list(accumulate(reversed(B), func=max))[::-1]
    ret = 0
    for i in range(len(A_accum) - 1):
        ret = max(A_accum[i] + B_accum[i + 1], ret)
    return ret


def ret_candi(X, V):
    V_accum = list(accumulate(V))
    V_accum_r = list(accumulate(reversed(V)))[::-1]
    A, B = [], []
    katamiti_max = 0  # 必ず折れ曲がるとも限らないので
    for i in range(N):
        katamiti_max = max(katamiti_max, V_accum[i] - X[i])
        A.append(V_accum[i] - 2 * X[i])
        B.append((V_accum_r[i]) - (C - X[i]))
    # print(A, B)
    return A, B, katamiti_max


def solve(X, V):
    A, B, katamiti_max = ret_candi(X, V)
    return max(solve_max_a_plas_b(A, B), katamiti_max)


V_r = V[::-1]
X_r = []
for x in reversed(X):
    X_r.append(C - x)
print(max(solve(X, V), solve(X_r, V_r)))

Submission status: Accepted

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

dpl=[0 for i in range(n+1)] #dpl[i]=左からi番目に行くまでのお腹の値のプラス
dpr=[0 for i in range(n+1)] #dpr[j]＝右からj番目に行くまでのお腹の値のプラス

c=0
for i in  range(n):
    c+=que[i][1]
    dpl[i+1]=c-que[i][0]

d=0
for i in range(1,n+1):
    d+=que[-i][1]
    dpr[i]=d-(C-que[-i][0])

max1=max(dpl)
max2=max(dpr)

dpb_l=[0 for i in range(n+1)]#dpb_l[i]=左からi番目に行って戻るときに達成できるお腹の値のプラス
dpb_r=[0 for i in range(n+1)]#dpb_r[i]=右からi番目に行って戻るときに達成できるお腹の値のプラス

c=0

for i in  range(n):
    c+=que[i][1]
    dpb_l[i+1]=c-2*que[i][0]

d=0
for i in range(1,n+1):
    d+=que[-i][1]

    dpb_r[i]=d-2*(C-que[-i][0])

#dpl[i]=左からi番目のところに行くまでに達成できるお腹の値のプラスの最大値
#dpr[i]=右からi番目のところに行くまでに達成できるお腹のあたいのプラスの最大値

for i in range(1,n+1):
    dpl[i]=max(dpl[i-1],dpl[i])
for i in range(1,n+1):
    dpr[i]=max(dpr[i],dpr[i-1])

max3=0

for i in range(1,n):
    max3=max(max3,dpb_l[i]+dpr[n-i],dpb_r[i]+dpl[n-i])

print(max(max1,max2,max3))

Submission status: Accepted

Solution code:
N, C = map(int, input().split())
X_V = [list(map(int, input().split())) for i in range(N)]
max_en = 0
point = [0] * (N+1)
point_back = [0] * (N+1)
point_rev = [0] * (N+1)
point_rev_back = [0] * (N+1)
max_point = [0] * (N+1)
max_point_back = [0] * (N+1)
max_point_rev = [0] * (N+1)
max_point_rev_back = [0] * (N+1)
for i, x_v in enumerate(X_V):
    # print(X_V[N-i-1])
    if i == 0:
        point[i+1] = x_v[1] - x_v[0]
        point_back[i+1] = x_v[1] - x_v[0]*2
        point_rev[i+1] = X_V[N-i-1][1] - (C-X_V[N-i-1][0])
        point_rev_back[i+1] = X_V[N-i-1][1] - (C-X_V[N-i-1][0])*2
    else:
        point[i+1] = point[i]+x_v[1] - (x_v[0]-X_V[i - 1][0])
        point_back[i+1] = point[i+1] - x_v[0]
        point_rev[i+1] = point_rev[i]+X_V[N-i-1][1] - (X_V[N-i][0]-X_V[N-i-1][0])
        point_rev_back[i+1] = point_rev[i+1] - (C-X_V[N-i-1][0])

    max_point[i + 1] = max(max_point[i], point[i + 1])
    max_point_back[i + 1] = max(max_point_back[i], point_back[i + 1])
    max_point_rev[i + 1] = max(max_point_rev[i], point_rev[i + 1])
    max_point_rev_back[i + 1] = max(max_point_rev_back[i],
                                    point_rev_back[i + 1])

# print(point)
# print(point_back)
# print(point_rev)
# print(point_rev_back)
for i in range(N+1):
    # print(i, N-i)
    max_en = max(max_en, max_point[i], max_point_rev[N-i], max_point_back[i] + max_point_rev[N-i],
                 max_point[i] + max_point_rev_back[N-i])
    # for j in range(N+1):
    #     if i + j > N:
    #         break
    #     else:
    #         if j == 0:
    #             max_en = max(max_en, point[i])
    #             # print(i, j, point[i])
    #         elif i == 0:
    #             max_en = max(max_en, point_rev[j])
    #             # print(i, j, point_rev[j])
    #         else:
    #             max_en = max(max_en, point_back[i] + point_rev[j], point[i] + point_rev_back[j])
    #             # print(i, j, point_back[i] + point_rev_back[j])

print(max_en)

Submission status: Accepted

Solution code:
N, C = list(map(int, input().split()))

D = []

for i in range(N):
    D.append(list(map(int, input().split())))

R = [[0, 0] for i in range(N + 1)]
cnt = 0
ma = 0
rma = 0
R[0][0] = -1
for i in range(N):
    cnt += D[i][1]
    if cnt - D[i][0] > ma:
        ma = cnt - D[i][0]
    if cnt - D[i][0] * 2 > rma:
        rma = cnt - D[i][0] * 2
    R[i + 1] = [ma, rma]

cnt = 0
Ans = R[N][0]
tmp = 0
for i in range(N - 1, -1, -1):
    cnt += D[i][1]
    tmp = C - D[i][0]
    tmp2 = cnt - tmp * 2 + R[i][0]
    tmp2 = max(tmp2, cnt - tmp + R[i][1])
    if tmp2 > Ans:
        Ans = tmp2

print(Ans)

Submission status: Accepted

Solution code:
n, c = map(int, input().split())

x_list = []
v_list = []
one_list = []
round_list = []
r_one_list = []
r_round_list = []

total = 0

for i in range(n):
    x, v = map(int, input().split())
    x_list.append(x)
    v_list.append(v)
    total = total + v
    one_list.append(total - x)
    round_list.append(total - (2 * x))

prev = 0

for i in range(n):
    if prev > one_list[i]:
        one_list[i] = prev
    else:
        prev = one_list[i]

prev = 0

for i in range(n):
    if prev > round_list[i]:
        round_list[i] = prev
    else:
        prev = round_list[i]


total = 0
for i in range(1, n+1):
    total = total + v_list[-i]
    r_one_list.append(total - (c - x_list[-i]))
    r_round_list.append(total - 2 * (c - x_list[-i]))

prev = 0
for i in range(n):
    if prev > r_one_list[i]:
        r_one_list[i] = prev
    else:
        prev = r_one_list[i]

prev = 0
for i in range(n):
    if prev > r_round_list[i]:
        r_round_list[i] = prev
    else:
        prev = r_round_list[i]

ret = 0

for i in range(n-1):
    tmp = max(one_list[i] + r_round_list[-i-2],
              round_list[i] + r_one_list[-i-2])
    if tmp > ret:
        ret = tmp

ret = max(one_list[-1], r_one_list[-1], ret)

print(ret)

Submission status: Accepted

Solution code:
def main():
    N, C = map(int, input().split())
    XV = [tuple(map(int, input().split())) for _ in range(N)]
    return max(solve(N, C, XV), solve(N, C, [(C - x, v) for x, v in reversed(XV)]))

def solve(N, C, XV):
    lv = [0] * N
    rv = [0] * N
    x0, c, m = 0, 0, 0
    for i, (x, v) in enumerate(XV):
        c += v - (x - x0)
        m = max(m, c)
        lv[i] = m
        x0 = x
    rv = [0] * N
    x0, c, m = C, 0, 0
    for i, (x, v) in enumerate(reversed(XV)):
        c += v - 2 * (x0 - x)
        m = max(m, c)
        rv[i] = m
        x0 = x
    for i in range(N - 1):
        lv[i] += rv[N - i - 2]
    return max(lv)

print(main())

Submission status: Accepted

Solution code:
#AC dattakedo segtree iranaikara keshita
def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    rm = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
        rm.append(max(rm[-1], r[-1]))
    l = [S[-1][1] + S[-1][0] - C]
    lm = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
        lm.append(max(lm[-1], l[-1]))
    l.reverse()
    lm.reverse()
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + lm[i+1] if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rm[i-1] if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

Submission status: Accepted

Solution code:
#AC dattakedo segtree iranaikara keshita
def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    rm = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
        rm.append(max(rm[-1], r[-1]))
    l = [S[-1][1] + S[-1][0] - C]
    lm = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
        lm.append(max(lm[-1], l[-1]))
    l.reverse()
    lm.reverse()
    def func(x,y):
        return max(x, y)
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + lm[i+1] if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rm[i-1] if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

Submission status: Accepted

Solution code:
class SegTree:
    def __init__(self, a, func):
        self.n = 2**(len(a) - 1).bit_length()
        self.f = func
        self.d = [0] * (2 * self.n - 1)
        self.d[self.n - 1:self.n - 1 + len(a)] = a
        for i in reversed(range(self.n - 1)):
            self.d[i] = self.f(self.d[2 * i + 1], self.d[2 * i + 2])

    def update(self, i, v):
        i += self.n - 1
        self.d[i] = v
        while i:
            i = (i - 1) // 2
            self.d[i] = self.f(self.d[2 * i + 1], self.d[2 * i + 2])

    def query(self, l, r):
        assert l <= r
        l += self.n
        r += self.n
        s = self.d[l - 1]
        while l < r:
            if l & 1:
                s = self.f(s, self.d[l - 1])
                l += 1
            if r & 1:
                r -= 1
                s = self.f(s, self.d[r - 1])
            l //= 2
            r //= 2
        return s
def main():
    N, C = map(int, input().split())
    S = []
    for i in range(N):
        x, v = map(int, input().split())
        S.append((x,v))
    r = [S[0][1] - S[0][0]]
    for i, v in enumerate(S[1:], start=1):
        r.append(r[-1] + v[1] - (v[0] - S[i-1][0]))
    l = [S[-1][1] + S[-1][0] - C]
    for i, v in enumerate(reversed(S[:-1]), start=1):
        l.append(l[-1] + v[1] - (S[N-i][0] - v[0]))
    l.reverse()
    def func(x,y):
        return max(x, y)
    rs = SegTree(r, func)
    ls = SegTree(l, func)
    m = 0
    for i in range(N):
        rr = r[i] - S[i][0] + ls.query(i+1, N) if i < N-1 else 0
        ll = l[i] + S[i][0] - C + rs.query(0, i) if i > 0 else 0
        m = max(m, r[i], rr, ll, l[i])
    return m
print(main())

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n, c = [int(x) for x in input().split()]
xv = [[0, 0]]
for _ in range(n):
    xv.append([int(x) for x in input().split()])
xv.sort()

from copy import deepcopy

xv_2 = [[0, 0]] + deepcopy(xv)[::-1]
for i in range(1, n + 1):
    xv_2[i][0] = c - xv_2[i][0]

xv_cumsum = [0]
xv_2_cumsum = [0]

for i in range(1, n + 1):
    xv_cumsum.append(xv_cumsum[-1] + xv[i][1])
    xv_2_cumsum.append(xv_2_cumsum[-1] + xv_2[i][1])

clock = [0]
anti_clock = [0]

for i in range(1, n + 1):
    clock.append(clock[-1] + xv[i][1] - (xv[i][0] - xv[i - 1][0]))

for i in range(1, n + 1):
    anti_clock.append(anti_clock[-1] + xv_2[i][1] - (xv_2[i][0] - xv_2[i - 1][0]))

for i in range(1, n + 1):
    clock[i] = max(clock[i], clock[i - 1])
    anti_clock[i] = max(anti_clock[i], anti_clock[i - 1])

ans = 0

for i in range(n):
    ans = max(ans, xv_2_cumsum[i] - 2*xv_2[i][0] + clock[n - i], xv_cumsum[i] -2*xv[i][0] + anti_clock[n - i])

print(ans)

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [None]*n
    for i in range(n):
        xv[i] = list(map(int, input().split()))
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v = v + vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v = v + vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv, 1):
        v = v + vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[n-i] = left_max
        _2oas[i] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1], 1):
        v = v + vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[n-i] = right_max
        _2obs[i] = v - 2*(c - xi)
    for oa, _2ob, ob, _2oa in zip(gl, _2obs[:n], gr, _2oas[:n]):
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        ans = max(ans, _2oas[i-1]+gr[-i], _2obs[i-1]+gl[-i])
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        oa = gl[-i]
        _2ob = _2obs[i-1]
        ob = gr[-i]
        _2oa = _2oas[i-1]
        ans = max(ans, _2oa+ob, _2ob+oa)
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, c = map(int, input().split())
    xv = [list(map(int, input().split())) for _ in range(n)]
    v, left_max, right_max = 0, 0, 0
    gl = [None]*n
    gr = [None]*n
    _2oas = [None]*(n+1)
    _2obs = [None]*(n+1)
    _2oas[0], _2obs[0] = 0, 0
    ans = 0
    for i, (xi, vi) in enumerate(xv):
        v += vi
        left = v - xi
        if left_max < left:
            left_max = left
        gl[i] = left_max
        _2oas[i+1] = v - 2*xi
    v = 0
    for i, (xi, vi) in enumerate(xv[::-1]):
        v += vi
        right = v - c + xi
        if right_max < right:
            right_max = right
        gr[i] = right_max
        _2obs[i+1] = v - 2*(c - xi)
    for i in range(1, n+1):
        oa = gl[-i]
        _2ob = _2obs[i-1]
        ob = gr[-i]
        _2oa = _2oas[i-1]
        if ans < _2oa+ob:
            ans = _2oa+ob
        if ans < _2ob+oa:
            ans = _2ob+oa
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

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

fr1, fr2 = [0 for _ in range(n+1)], [0 for _ in range(n+1)]
fl1, fl2 = [0 for _ in range(n+2)], [0 for _ in range(n+2)]

tmp1, tmp2 = 0, 0
for i in range(0, n):
    tmp1 += v[i+1] - (x[i+1] - x[i])
    tmp2 += v[i+1] - 2 * (x[i+1] - x[i])
    fr1[i+1] = max(tmp1, fr1[i])
    fr2[i+1] = max(tmp2, fr2[i])
    
tmp1, tmp2 = 0, 0
for i in range(n, 0, -1):
    tmp1 += v[i] - abs(x[i+1] - x[i])
    tmp2 += v[i] - 2 * abs(x[i+1] - x[i])
    fl1[i] = max(tmp1, fl1[i+1])
    fl2[i] = max(tmp2, fl2[i+1])

ans = 0
for i in range(n+1):
    ans = max(ans, fr1[i] + fl2[i+1], fr2[i] + fl1[i+1])
print(ans)

Submission status: Accepted

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

A1 = [0, 0]
X1 = [0]
A2 = [0, 0]
X2 = [0]
for x, v in xv:
  A1[-1] += v - x
  A1.append(A1[-1] + x)
  X1.append(x)
A1.pop()

xv = xv[::-1]
for x, v in xv:
  A2[-1] += v - (C-x)
  A2.append(A2[-1] + (C-x))
  X2.append(C-x)
A2.pop()

max_1 = []
max_2 = []
now = -1
for i, a in enumerate(A1):
  if a > now:
    max_1.append(i)
    now = a
  else:
    max_1.append(max_1[-1])

now = -1
for i, a in enumerate(A2):
  if a > now:
    max_2.append(i)
    now = a
  else:
    max_2.append(max_2[-1])

ans = 0
for i, a in enumerate(A1):
  idx = max_2[-i-1]
  calory = max(a, a + A2[idx] - X1[i])
  ans = max(ans, calory)

for i, a in enumerate(A2):
  idx = max_1[-i-1]
  calory = max(a, a + A1[idx] - X2[i])
  ans = max(ans, calory)

print(ans)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,c = na()
migi = []
sushi_m = []

for i in range(n):
  x,v = na()
  migi.append(x)
  sushi_m.append(v)

sushi_h = list(reversed(sushi_m))
hidari = [c-i for i in reversed(migi)]

m = 0
mm = 0
h = 0
hh = 0
mmigi = []
hhidari = []

for i in range(n):
  m += sushi_m[i]
  h += sushi_h[i]
  mm = max(mm,m-migi[i])
  mmigi.append(mm)
  hh = max(hh,h-hidari[i])
  hhidari.append(hh)

ans = 0
for i in range(n):#migi
  if n-i-2 >= 0 and hhidari[n-i-2]-migi[i] > 0:
    ans = max(ans, mmigi[i]+hhidari[n-i-2]-migi[i])
  else:
    ans = max(ans, mmigi[i])
    
for i in range(n):#hidari
  if n-i-2 >= 0 and mmigi[n-i-2]-hidari[i] > 0:
    ans = max(ans, hhidari[i]+mmigi[n-i-2]-hidari[i])
  else:
    ans = max(ans, hhidari[i])

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate

import sys

input=sys.stdin.readline

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

acu=list(accumulate(V))
if N>=2:
    data=[0 for i in range(0,N)]
    data[N-1]=acu[N-2]-2*X[N-1]
    for i in range(1,N):
        data[N-1-i]=min(data[N-i],acu[N-2-i]-2*X[N-1-i])

    data2=[0 for i in range(0,N)]
    data2[N-1]=acu[N-2]-X[N-1]
    for i in range(1,N):
        data2[N-1-i]=min(data2[N-i],acu[N-2-i]-X[N-1-i])
    ans=[0 for i in range(0,N-1)]
    for i in range(0,N-1):
        ans[i]=min(data[i+1]-acu[i]+X[i]+2*C,data2[i+1]-acu[i]+2*X[i]+C)
    test1=max(acu[i]-X[i] for i in range(0,N))
    k=sum(V)
    test2=max(k-acu[i]-(C-X[i+1]) for i in range(0,N-1))
    test2=max(test2,k-(C-X[0]))
    test3=k-min(ans)
    print(max(0,test1,test2,test3))
else:
    print(max(0,V[0]-min(C-X[0],X[0])))

Submission status: Accepted

Solution code:
import sys


class SegmentTree():
    """
    update, get を提供するSegmentTree

    Attributes
    ----------
    __n : int
        葉の数。2 ^ i - 1
    __dot :
        Segment function
    __e: int
        単位元
    __node: list
        Segment Tree
    """
    def __init__(self, A, dot, e):
        """
        Parameters
        ----------
        A : list
            対象の配列
        dot :
            Segment function
        e : int
            単位元
        """
        n = 2 ** (len(A) - 1).bit_length()
        self.__n = n
        self.__dot = dot
        self.__e = e
        self.__node = [e] * (2 * n)
        for i in range(len(A)):
            self.__node[i + n] = A[i]
        for i in range(n - 1, 0, -1):
            self.__node[i] = self.__dot(self.__node[2 * i], self.__node[2 * i + 1])
    
    def update(self, i, c):
        i += self.__n
        node = self.__node
        node[i] = c
        while i > 1:
            i //= 2
            node[i] = self.__dot(node[2 * i], node[2 * i + 1])

    def get(self, l, r):
        vl, vr = self.__e, self.__e
        l += self.__n
        r += self.__n
        while (l < r):
            if l & 1:
                vl = self.__dot(vl, self.__node[l])
                l += 1
            l //= 2
            if r & 1:
                r -= 1
                vr = self.__dot(vr, self.__node[r])
            r //= 2
        return self.__dot(vl, vr)


N, C = map(int, input().split())
S = [tuple(map(int, s.split())) for s in sys.stdin.readlines()]

R = [0] * (N + 1)
pos = 0
for i, (x, v) in enumerate(S):
    R[i + 1] = R[i] + v - (x - pos)
    pos = x
L = [0] * (N + 1)
pos = 0
for i, (x, v) in enumerate(reversed(S)):
    x = C - x
    L[i + 1] = L[i] + v - (x - pos)
    pos = x

RST = SegmentTree(R, max, 0)
LST = SegmentTree(L, max, 0)
ans1 = RST.get(0, N + 1)
ans2 = LST.get(0, N + 1)

score = 0
pos = 0
ans3 = 0
for i in range(N):
    x, v = S[i]
    score += v - (x - pos) * 2
    ans3 = max(ans3, score + LST.get(0, N - i))
    pos = x

score = 0
pos = 0
ans4 = 0
for i in range(N):
    x, v = S[N - 1 - i]
    x = C - x
    score += v - (x - pos) * 2
    ans4 = max(ans4, score + RST.get(0, N - i))
    pos = x


print(max([ans1, ans2, ans3, ans4]))