Problem:


Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931



Sample input:
4
4 7
1 4
5 8
2 5


Sample output:
6

Submission status: Time Limit Exceeded

Solution code:
import itertools
import math
import os
import sys
from collections import defaultdict
from operator import itemgetter

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class SparseTable:
    """
    構築 O(NlogN)、クエリ O(1)
    """

    def __init__(self, values, fn):
        """
        :param list values:
        :param callable fn: 結合則を満たす冪等な関数。min、max など。add はだめ
        """
        self._values = values
        self._fn = fn

        # SparseTable を構築
        # self._table[i][p]: [i, i+2^p) に fn を適用した結果の値のインデックス
        self._table = self._build(values, fn)

        # self._msb[i]: 最上位ビット; どの p を見るべきか
        self._msb = [0] * (len(values) + 1)
        for i in range(2, len(values) + 1):
            self._msb[i] = self._msb[i >> 1] + 1

    @staticmethod
    def _build(values, fn):
        # AtCoder の PyPy 2.4.0 では math.log2 が使えない
        size = int(math.log(len(values), 2)) + 1

        st = [[0] * size for _ in range(len(values))]
        for i in range(len(values)):
            st[i][0] = i
        for p in range(1, size):
            for i in range(len(values)):
                q = min(i + (1 << (p - 1)), len(values) - 1)
                l = st[i][p - 1]
                r = st[q][p - 1]
                if values[l] == fn(values[l], values[r]):
                    st[i][p] = l
                else:
                    st[i][p] = r
        return st

    def get(self, a, b):
        """
        半開区間 [a, b) に fn を適用した結果
        :param int a:
        :param int b:
        """
        if b <= a:
            return None
        p = self._msb[b - a]
        return self._fn(
            self._values[self._table[a][p]],
            self._values[self._table[b - (1 << p)][p]]
        )


N = int(sys.stdin.readline())
LR = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]


def calc_score(lr):
    ma = IINF
    mi = 0
    for l, r in lr:
        ma = min(ma, r)
        mi = max(mi, l)
    return max(0, ma - mi + 1)


def test(N, LR):
    import numpy as np
    LR = np.array(LR, dtype=int)
    ret = 0
    counts = defaultdict(int)
    for choice in itertools.product([True, False], repeat=N):
        if sum(choice) in [N, 0]:
            continue
        choice = np.array(choice)
        score = calc_score(LR[choice]) + calc_score(LR[~choice])
        if score >= ret:
            counts[score] = max(counts[score], sum(choice))
        ret = max(score, ret)
        # print(score, choice)
    # print(ret, counts[ret])
    return ret


def solve():
    L, R = zip(*LR)
    L = np.array(L, dtype=int)
    R = np.array(R, dtype=int)
    if N == 2:
        ans = (R - L + 1).sum()
        print(ans)
        exit()

    # minR と minL のやつを同じグループにするとき、一番幅が広いのを他のグループにするのが最適。
    diff = R - L
    order = diff.argsort()
    L = L[order]
    R = R[order]
    diff = diff[order]
    li = L.argmax()
    ri = R.argmin()

    g1i = N - 1
    while g1i in [li, ri]:
        g1i -= 1
    g1 = diff[g1i] + 1
    g2 = max(0, R[ri] - L[li] + 1)
    ans1 = g1 + g2

    # minR と minL のやつを違うグループにするとき、どこで区切るかを全探索。
    LR.sort()
    L, R = zip(*LR)
    rsp = SparseTable(R, min)
    ans2 = 0
    for sep in range(1, N):
        max_l = L[sep - 1]
        min_r = rsp.get(0, sep)
        s1 = max(0, min_r - max_l + 1)
        max_l = L[-1]
        min_r = rsp.get(sep, N)
        s2 = max(0, min_r - max_l + 1)
        score = s1 + s2
        ans2 = max(score, ans2)

    LR.sort(key=itemgetter(1))
    L, R = zip(*LR)
    lsp = SparseTable(L, max)
    for sep in range(1, N):
        max_l = lsp.get(0, sep)
        min_r = R[0]
        s1 = max(0, min_r - max_l + 1)
        max_l = lsp.get(sep, N)
        min_r = R[sep]
        s2 = max(0, min_r - max_l + 1)
        score = s1 + s2
        ans2 = max(score, ans2)

    return max(ans1, ans2)


print(solve())
# assert test(N, LR) == solve()

Submission status: Time Limit Exceeded

Solution code:
def calc(left_a, right_a, left_b, right_b, T):
    for left_t, right_t in T:
        los_a = max(0, left_t - left_a) + max(0, right_a - right_t)
        los_b = max(0, left_t - left_b) + max(0, right_b - right_t)

        if los_a <= los_b:
            left_a = max(left_a, left_t)
            right_a = min(right_a, right_t)
        else:
            left_b = max(left_b, left_t)
            right_b = min(right_b, right_t)

        if left_a == right_a:
            return max(0, right_b - left_b + 1)

        if left_b == right_b:
            return max(0, right_a - left_a + 1)

    return max(0, right_a - left_a + 1) + max(0, right_b - left_b + 1)


def f():
    N = int(input())
    W = list(set([tuple(map(int, input().split())) for _ in range(N)]))

    res = 0
    left_a = 0
    right_a = 10 ** 9
    for k, w in enumerate(W):
        left_b, right_b = w
        if left_a == right_a:
            res = max(res, right_b - left_b + 1)
            continue

        if k:
            res = max(res, calc(left_a, right_a, left_b, right_b, W[k + 1:]))

        left_a = max(left_b, left_a)
        right_a = min(right_b, right_a)
        if left_a > right_a:
            left_a = right_a

    print(res)


if __name__ == '__main__':
    f()

Submission status: Time Limit Exceeded

Solution code:
def calc(left_a, right_a, left_b, right_b, T):
    for left_t, right_t in T:
        los_a = max(0, left_t - left_a) + max(0, right_a - right_t)
        los_b = max(0, left_t - left_b) + max(0, right_b - right_t)

        if los_a <= los_b:
            left_a = max(left_a, left_t)
            right_a = min(right_a, right_t)
        else:
            left_b = max(left_b, left_t)
            right_b = min(right_b, right_t)

    return max(0, right_a - left_a + 1) + max(0, right_b - left_b + 1)


def f():
    N = int(input())
    W = sorted([list(map(int, input().split())) for _ in range(N)])
    res = 0
    left_a = -1
    right_a = 10 ** 9 + 1
    for k in range(1, N):
        left_b, right_b = W[k]
        if left_a == right_a:
            res = max(res, right_b - left_b + 1)
            continue

        left_a = max(W[k - 1][0], left_a)
        right_a = min(W[k - 1][1], right_a)
        if left_a > right_a:
            left_a = right_a

        res = max(res, calc(left_a, right_a, left_b, right_b, W[k + 1:]))
    print(res)


if __name__ == '__main__':
    f()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
Q=[]
Q1=[]
Q2=[]
for i in range(N):
  Q.append(list(map(int,input().split())))
Q.sort()
for i in Q:
  Q1.append(i[0])
  Q2.append(i[1])
ans=0
for i in range(N-1):
  Q11=Q1[0:i+1]
  Q12=Q1[i+1:]
  Q21=Q2[0:i+1]
  Q22=Q2[i+1:]
  tmp=max(0,min(Q21)-max(Q11)+1) + max(0,min(Q22)-max(Q12)+1)
  #print(ans)
  if ans<tmp:
    ans=tmp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
lr = [list(map(int, input().split())) for i in range(n)]


g = 0
lr.sort()

for st in range(1,n) :
    al = 0
    ar = 10000000000
    bl = 0
    br = 10000000000
    for i in range(st) :
        if(al < lr[i][0]) :
            al = lr[i][0]
        if(ar > lr[i][1]) :
            ar = lr[i][1]
    for j in range(st,n) :
        if(bl < lr[j][0]) :
            bl = lr[j][0]
        if(br > lr[j][1]) :
            br = lr[j][1]

    if(g < ar-al+br-bl+2) :
        g = ar-al+br-bl+2

print(g)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
lr=[[int(i) for i in input().split()] for j in range(n)]
lr=sorted(lr)
li_test=[]

for x,y in lr:
    li_test.append(y)

li=[li_test[0]]
for i in range(1,n):
    a=min(li_test[:i+1])
    li.append(a)

li_test=li_test[::-1]
li2=[li_test[0]]
for i in range(1,n):
    a=min(li_test[:i+1])
    li2.append(a)
li2=li2[::-1]
    
ans=0
maxi=lr[-1][0]
for i in range(n-1):
    one = max(0,li[i]-lr[i][0]+1)
    two = max(0,li2[i+1]-maxi+1)
    ans=max(ans,one+two)
print(ans)

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


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


def read_float():
    return float(input())


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


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


def read_str_n():
    return list(map(str, input().split()))


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


def mt(f):
    import time

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

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

    return wrap


@mt
def slv(N, LR):
    LR.sort(key=lambda x: x[1], reverse=True)
    LR.sort(key=lambda x: x[0])

    @lru_cache(maxsize=None)
    def f(li, ri):
        l = 0
        r = INF
        for i in range(li, ri+1):
            l_, r_ = LR[i]
            l = max(l, l_)
            r = min(r, r_)
        return max(0, r-l+1)

    ans = 0
    for i in range(N-1):
        ans = max(ans, f(0, i) + f(i+1, N-1))
    return ans


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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N = I()
    LR=LLIN_(N)
    L_sort = sorted(LR)
    R_sort = sorted(LR,key=lambda x: x[1])
    
    # print(L_sort)
    # print(R_sort)
    
    def get_fun(A):
        left = -1
        right = 10**9+7
        for l,r in A:
            left = max(l,left)
            right = min(r,right)
        return max(0,right-left+1)
    
    ans = 0
    for i in range(1,N):
        # print(L_sort[:i],L_sort[i:])
        ans = max(ans,get_fun(L_sort[:i]) + get_fun(L_sort[i:]) )
        ans = max(ans,get_fun(R_sort[:i]) + get_fun(R_sort[i:]) )
    print(ans)





if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
lr=[[0]*2 for _ in range(n)]
for i in range(n):
    lr[i] = list( map(int,input().split()) )
sortedlr = sorted(lr,key=lambda x:x[0])
ans=0
for i in range(1,n):
    left  = sortedlr[:i]
    right = sortedlr[i:]
    cand =min(left[i][1] for i in range(len(left)) ) - max(left[i][0] for i in range(len(left)) ) +1
    cand+=min(right[i][1] for i in range(len(right)) ) - max(right[i][0] for i in range(len(right)) ) +1
    if ans<cand:
        ans=cand
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = 0
r = float("INF")
w = 0
LR = sorted([list(map(int,input().split())) for i in range(n)])
rm = [float("INF")]*(n+1)
for i in range(n):
    rm[-2-i] = min(rm[-1-i],LR[-1-i][1])
for i in range(n):
    x,y = LR[-1-i]
    l = max(l,x)
    r = min(r,y)
    w = max(w,y-x+1)
    rm[-2-i] = min(rm[-1-i],y)
ans = max(r-l+1,0)+w
for k in range(n-1):
    i,j = LR[k]
    a = max(r-i+1,0)
    b = max(rm[k+1]+1-l,0)
    ans = max(ans,a+b)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = 0
r = float("INF")
LR = [list(map(int,input().split())) for i in range(n)]
w = 0
for i,j in LR:
    l = max(l,i)
    r = min(r,j)
    w = max(w,j-i+1)
ans = max(r-l+1,0)+w
LR.sort()
rm = [float("INF")]*(n+1)
for i in range(n):
    rm[-2-i] = min(rm[-1-i],LR[-1-i][1])
for k in range(n-1):
    i,j = LR[k]
    a = max(r-i+1,0)
    b = max(rm[k+1]+1-l,0)
    ans = max(ans,a+b)
print(ans)

Submission status: Accepted

Solution code:
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
task.sort()
score = [0] * (n - 1)
l1, r1 = task[0][0], task[0][1]
l2, r2 = task[n - 1][0], task[n - 1][1]
i, j = 0, n - 1
for _ in range(n - 1):
    l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
    l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
    j -= 1
    score[i] += max(0, r1 - l1 + 1)
    score[j] += max(0, r2 - l2 + 1)
    i += 1
ans = max(ans, max(score))
print(ans)

Submission status: Accepted

Solution code:
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
for k in range(1):
    task.sort(key = lambda x : x[k])
    score = [0] * (n - 1)
    l1, r1 = task[0][0], task[0][1]
    l2, r2 = task[n - 1][0], task[n - 1][1]
    i, j = 0, n - 1
    for _ in range(n - 1):
        l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
        l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
        j -= 1
        score[i] += max(0, r1 - l1 + 1)
        score[j] += max(0, r2 - l2 + 1)
        i += 1
ans = max(ans, max(score))
print(ans)

Submission status: Accepted

Solution code:
import heapq

n = int(input())
ll, rr = [], []
task = []
ans = 0
for _ in range(n):
    l, r = map(int, input().split())
    heapq.heappush(ll, -l)
    heapq.heappush(rr, r)
    task.append([l, r])
maxl1, minr1 = -heapq.heappop(ll), heapq.heappop(rr)
maxl2, minr2 = -heapq.heappop(ll), heapq.heappop(rr)
for i in range(n):
    ma = maxl1 if not task[i][0] == maxl1 else maxl2
    mi = minr1 if not task[i][1] == minr1 else minr2
    ans = max(ans, task[i][1] - task[i][0] + max(0, mi - ma + 1) + 1)
for k in range(2):
    task.sort(key = lambda x : x[k])
    score = [0] * (n - 1)
    l1, r1 = task[0][0], task[0][1]
    l2, r2 = task[n - 1][0], task[n - 1][1]
    i, j = 0, n - 1
    for _ in range(n - 1):
        l1, r1 = max(l1, task[i][0]), min(r1, task[i][1])
        l2, r2 = max(l2, task[j][0]), min(r2, task[j][1])
        j -= 1
        score[i] += max(0, r1 - l1 + 1)
        score[j] += max(0, r2 - l2 + 1)
        i += 1
ans = max(ans, max(score))
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=[]
dd=0
LL,RR=[],[]

for i in range(N):
  L,R=map(int, input().split())
  LL.append(L)
  RR.append(R)
  A.append((L,-R))
LL=sorted(LL)
RR=sorted(RR)
A=sorted(A)
dl,dr=0,10**9+1
el,er=0,10**9+1
D=[0 for i in range(N-1)]
E=[0 for i in range(N-1)]

for i in range(N-1):
  dl=max(dl,A[i][0])
  dr=min(dr,-A[i][1])
  D[i]=dr-dl+1
  el=max(el,A[-1-i][0])
  er=min(er,-A[-1-i][1])
  E[-i-1]=er-el+1
ans=dd
for i in range(len(D)):
  d=max(0,D[i])+max(0,E[i])
  ans=max(d,ans)
for L,R in A:
  l=LL[-1]
  r=RR[0]
  if l==L:
    l=LL[-2]
  if r==-R:
    r=RR[1]
  d=(-R-L+1)+max(0,r-l+1)
  ans=max(ans,d)
print(ans)

Submission status: Accepted

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 10**18

def main():
    n = int(ipt())
    base = 10**9
    qs = []
    # Lの最大、Rの最小を求めると同時に、それらが同じセットに入るときのansの最大値を求める
    lma = 0
    li = -1
    ll = 0
    rmi = INF
    ri = INF
    lr = 0
    mal = 0
    for i in range(n):
        l,r = map(int,ipt().split())
        qs.append((l,r))
        d = r-l+1
        f = True
        if l > lma:
            if ll > mal:
                mal = ll
            lma = l
            li = i
            ll = d
            f = False
        elif l == lma and ll > d:
            li = i
            mal = max(mal,ll)
            ll = d
            f = False
        if r < rmi:
            if lr > mal:
                mal = lr
            rmi = r
            ri = i
            lr = d
            f = False
        elif r == rmi and lr > d:
            ri = i
            mal = max(mal,lr)
            lr = d
            f = False
        if f and mal < d:
            mal = d
    ans = mal+max(0,rmi-lma+1)

    # Lの最大値とRの最大値が別のセットに入る場合
    q = []
    for la,ra in qs:
        v = (base-1-max(0,ra-lma+1))*base+max(0,rmi-la+1)
        q.append(v)
    q.sort()
    dp0 = [INF,0]
    dp1 = [0,INF]
    f = False
    for i in q:
        l = base-1-i//base
        r = i%base
        if f:
            dp1[1] = min(dp1[1],r)
            if dp0[0]+r > sum(dp1):
                dp1[0] = dp0[0]
                dp1[1] = r
        f = True
        dp0[0] = min(dp0[0],l)

    # 上二つのうち最大を取る
    print(max(ans,sum(dp1)))
    
    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 10**18

def main():
    n = int(ipt())
    base = 10**9
    qs = []
    lma = 0
    li = -1
    ll = 0
    rmi = INF
    ri = INF
    lr = 0
    mal = 0
    for i in range(n):
        l,r = map(int,ipt().split())
        qs.append((l,r))
        d = r-l+1
        f = True
        if l > lma:
            if ll > mal:
                mal = ll
            lma = l
            li = i
            ll = d
            f = False
        elif l == lma and ll > d:
            li = i
            mal = max(mal,ll)
            ll = d
            f = False
        if r < rmi:
            if lr > mal:
                mal = lr
            rmi = r
            ri = i
            lr = d
            f = False
        elif r == rmi and lr > d:
            ri = i
            mal = max(mal,lr)
            lr = d
            f = False
        if f and mal < d:
            mal = d

    ans = mal+max(0,rmi-lma+1)
#    print(ans)

    q = []
    for la,ra in qs:
        v = (base-1-max(0,ra-lma+1))*base+max(0,rmi-la+1)
        q.append(v)

    q.sort()
    dp0 = [INF,0]
    dp1 = [0,INF]
    f = False
    for i in q:
        l = base-1-i//base
        r = i%base
        if f:
            dp1[1] = min(dp1[1],r)
            if dp0[0]+r > sum(dp1):
                dp1[0] = dp0[0]
                dp1[1] = r
        f = True
        dp0[0] = min(dp0[0],l)
#        print(dp0,dp1)

    print(max(ans,sum(dp1)))






    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
lr=[list(map(int,input().split())) for _ in range(n)]
lr.sort(key=lambda x:x[0])
# 右端がもっとも左にある問題
r0=0
tmpr=float('inf')
# 左端がもっとも右にある問題
l0=0
tmpl=0
for i,x in enumerate(lr):
  l,r=x
  if tmpl<l:
    l0=i
    tmpl=l
  if tmpr>r:
    r0=i
    tmpr=r
if l0==r0:
  ans=lr[r0][1]-lr[l0][0]+1
  tmp=0
  for i in range(n):
    if i==l0:continue
    l,r=lr[i]
    tmp=max(tmp,r-l+1)
  ans+=tmp
  print(ans)
  exit()
ans0=max(0,lr[r0][1]-lr[l0][0]+1)
tmp=0
for i in range(n):
  if i==l0 or i==r0:continue
  l,r=lr[i]
  tmp=max(tmp,r-l+1)
ans0+=tmp


import heapq
class pqheap:
  def __init__(self,key=None):
    self.p = list()
    self.q = list()
  def insert(self,x):
    heapq.heappush(self.p, x)
    return
  def erase(self,x):
    heapq.heappush(self.q, x)
    return
  def minimum(self):
    while self.q and self.p[0] == self.q[0]:
      heapq.heappop(self.p)
      heapq.heappop(self.q)
    return self.p[0] if len(self.p)>0 else None
pq=pqheap()

[pq.insert(x[1]) for i,x in enumerate(lr) if i!=l0 and i!=r0]
l1,r1=lr[r0]
l2,r2=lr[l0]
if pq.minimum():r2=min(r2,pq.minimum())
ans1=max(r1-l1+1,0)
ans1+=max(r2-l2+1,0)
for i,[l,r] in enumerate(lr):
  if i==l0 or i==r0:continue
  tmp=0
  l1=max(l1,l)
  pq.erase(r)
  tmp=max(r1-l1+1,0)
  if pq.minimum():
    r2=min(lr[l0][1],pq.minimum())
  else:
    l2,r2=lr[l0]
  tmp+=max(r2-l2+1,0)
  ans1=max(ans1,tmp)
print(max(ans1,ans0))

Submission status: Accepted

Solution code:
from operator import itemgetter

class SegTree:  # 0-index !!!
    """
    fx: モノイドXでの二項演算
    ex: モノイドXでの単位元
    init(seq, fx, ex): 配列seqで初期化 O(N)
    update(i, x): i番目の値をxに更新 O(logN)
    query(l, r): 区間[l,r)をfxしたものを返す O(logN)
    get(i): i番目の値を返す
    show(): 配列を返す
    """

    def __init__(self, seq, fx, ex):
        self.n = len(seq)
        self.fx = fx
        self.ex = ex
        self.size = 1<<(self.n - 1).bit_length()
        self.tree = [ex] * (self.size * 2)
        # build
        for i, x in enumerate(seq, start=self.size):
            self.tree[i] = x
        for i in reversed(range(1, self.size)):
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, i, x):  # O(log(n))
        i += self.size
        self.tree[i] = x
        while i:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, i, x):
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.fx(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, l, r):  # l = r の場合はたぶんバグるので注意
        tmp_l = self.ex
        tmp_r = self.ex
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                tmp_l = self.fx(tmp_l, self.tree[l])
                l += 1
            if r & 1:
                tmp_r = self.fx(self.tree[r - 1], tmp_r)  # 交換法則を仮定しない(順序大事に)
            l >>= 1
            r >>= 1
        return self.fx(tmp_l, tmp_r)

    def get(self, i):
        return self.tree[self.size + i]

    def show(self):
        return self.tree[self.size: self.size + self.n]

# ---------------------- #

n = int(input())
LR = [tuple(int(x) for x in input().split()) for _ in range(n)]
LR.sort(key=itemgetter(0))
L = []
R = []
for l, r in LR:
    L.append(l)
    R.append(r)
seg = SegTree(R, fx=min, ex=10**18)
ans = 0
for i in range(1, n):
    contest1 = seg.query(0, i) - L[i - 1] + 1
    contest2 = seg.query(i, n) - L[n - 1] + 1
    ans = max(ans, contest1 + contest2)

LR.sort(key=lambda item: item[1] - item[0], reverse=True)
lmax = max(l for l, _ in LR[1:])
rmin = min(r for _, r in LR[1:])
ans = max(ans, LR[0][1] - LR[0][0] + 1 + max(rmin - lmax + 1, 0))
print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from operator import itemgetter

    N = int(readline())
    mat = []

    l_max = 0
    r0 = 0
    l_idx = -1
    r_min = INF
    l1 = 0
    r_idx = -1

    for i in range(N):
        l, r = map(int, readline().split())
        r += 1
        mat.append([l, r])
        if l > l_max:
            l_max = l
            r0 = r
            l_idx = i
        if r < r_min:
            l1 = l
            r_min = r
            r_idx = i

    if N == 2:
        ans = 0
        for l, r in mat:
            ans += r - l
    elif l_idx == r_idx:
        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)
    else:
        mat2 = []
        for i in range(N):
            l, r = mat[i]
            mat2.append([max(r - l_max, 0), max(r_min - l, 0)])

        mat2.sort(key=itemgetter(1), reverse=True)
        mat2.sort(key=itemgetter(0))

        l_acc = []

        ans = 0
        h = max(0, r_min - l_max)
        for i in range(N):
            l, r = mat[i]
            ans = max(ans, h + r - l)

        a, b = mat2[0][0], r_min - l1
        ans = max(ans, a + b)

        for i in range(N - 1):
            a = max(a, mat2[i + 1][0])
            b = min(b, mat2[i][1])
            ans = max(ans, a + b)

        a, b = r0 - l_max, mat2[N - 1][1]
        ans = max(ans, a + b)

        ans = max(ans, (r0 - l_max))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

N = int(input())
LR = [tuple(map(int, input().split())) for _ in range(N)]
p = max(Li for Li, _ in LR)
q = min(Ri for _, Ri in LR)
ab = []

for L, R in LR:
    a = max(0, R-p+1)
    b = max(0, q-L+1)
    ab.append((a, b))

ab.sort(key=lambda t: (t[0], -t[1]))
b_min = 10**18
ans = max(0, q-p+1)+max(R-L+1 for L, R in LR)

for i in range(1, N):
    a_min = ab[i][0]
    b_min = min(b_min, ab[i-1][1])
    ans = max(ans, a_min+b_min)

print(ans)

Submission status: Accepted

Solution code:
N, *LR = [int(_) for _ in open(0).read().split()]
LR = sorted(set([(l, r + 1) for l, r in zip(LR[::2], LR[1::2])]))


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


minr = min(r for l, r in LR)
lminr = max(l for l, r in LR if r == minr)
maxl = max(l for l, r in LR)
rmaxl = min(r for l, r in LR if l == maxl)
LR2 = [lr for lr in LR if lr not in [(minr, lminr), (maxl, rmaxl)]]
LR = [(minr, lminr)] + LR2 + [(maxl, rmaxl)]
M = len(LR)
if M == 1:
    ans = 2 * (LR[0][1] - LR[0][0])
elif M == 2:
    ans = sum(r - l for l, r in LR)
else:
    #(lminr,minr)と(maxl,rmaxl)が同一または同じ回
    ans = max(0, minr - maxl) + max(r - l for l, r in LR2)
    #(lminr,minr)と(maxl,rmaxl)が違う回 [0,i)と[i,M)に分けて施行すればよい(i∈[1,M))
    st = SegmentTree([r for l, r in LR], min, 10**10)
    for i in range(1, M):
        v1 = max(0, minr - max(lminr, LR[i - 1][0]))
        v2 = max(0, st.query(i, M) - maxl)
        ans = max(ans, v1 + v2)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
LRs = [tuple(map(int, input().split())) for _ in range(N)]


# [L1, R1]は最小のRを、[L2, R2]は最大のLを含む。L1を減らす形で走査。
R1 = min(map(lambda t: t[1], LRs))
L2 = max(map(lambda t: t[0], LRs))
LRs.sort(key=lambda t: (-t[0], t[1])) # Lについて降順、L同じならRについて昇順

ans = 0
R2 = 1001001001
for i in range(1, N):
    R2 = min(R2, LRs[i-1][1])
    L1 = LRs[i][0]  # LRsはLについて降順ソート済みより
    ans = max(ans, max(0, R2 - L2 + 1) + max(0, R1 - L1 + 1))


# 加えて、コンテスト1つだけ行うときを場合分け
LRs.sort(key = lambda t: t[0] - t[1])
one_problem_contest = LRs[0][1] - LRs[0][0] + 1
L_max = max(map(lambda t: t[0], LRs[1:]))
R_min = min(map(lambda t: t[1], LRs[1:]))
ans = max(ans, one_problem_contest + max(R_min - L_max + 1, 0))

print(ans)