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

Solution code:
from operator import itemgetter
import sys
input = sys.stdin.readline
N = int(input())
LR = []
for _ in range(N):
    l, r = map(int, input().split())
    LR.append([l, r+1])
ans = 0
for l, r in LR:
    ans = max(ans, r - l)

LR.sort(key=itemgetter(1))

sch = 0
rr = 0
for l, r in LR:
    if l >= rr:
        rr = r
        sch += 1
#print(sch)
if sch >= 3:
    print(ans)
elif sch == 2:
    # ここは合ってる
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
            pl = l
    assert len(LR_) >= 2
    LR = LR_
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    ans = max(ans, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        ans = max(ans, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    print(ans)
else:
    mid_l = 0
    mid_r = float("inf")
    for l, r in LR:
        mid_l = max(l, mid_l)
        mid_r = min(r, mid_r)
    for i in range(N):
        LR[i][1] -= mid_r-mid_l
    LR_ = []
    pl = 0
    for l, r in LR:
        if pl >= l:
            pass
        else:
            LR_.append([l, r])
            pl = l
    if not len(LR_) >= 2:
        print(ans + mid_r - mid_l)
        exit()
    assert mid_r - mid_l > 0
    assert LR_ == sorted(LR_)
    an = 0
    LR, LR_ = LR_, LR
    Ll, Lr = LR[0]
    Rl, Rr = LR[-1][0], LR[1][1]
    an = max(an, max(Rr-Rl, 0) + Lr-Ll)
    for i, (l, r) in enumerate(LR[1:-1], 1):
        Ll = l
        Rr = LR[i+1][1]
        an = max(an, max(Rr-Rl, 0) + max(Lr-Ll, 0))
    ans += mid_r - mid_l
    an += (mid_r - mid_l) * 2
    print(max(ans, an))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
m = map(int,read().split())
LR = list(zip(m,m))

if N==2:
    L1,R1 = LR[0]
    L2,R2 = LR[1]
    answer = (R1-L1+1) + (R2-L2+1)
    print(answer)
    exit()

# 片方に集める場合
max_width = max(R-L+1 for L,R in LR)

LR.sort()

INF=10**18
# Rが最小のもの
i = -1
opt_R = INF
for n,(L,R) in enumerate(LR):
    if opt_R>=R:
        opt_R=R
        i=n
j = -1
opt_L = -INF
for n,(L,R) in enumerate(LR):
    if opt_L<=L:
        opt_L=L
        j=n

if i==j:
    L,R = LR[i]
    answer = max_width + (R-L+1)
    print(answer)
    exit()

L1,R1 = LR[i]; L2,R2 = LR[j]

LR = [(L,R) for n,(L,R) in enumerate(LR) if n != i and n != j]

LR.sort(key = lambda x: (x[0],-x[1]))

n = len(LR)
dpl = [(-INF,INF)]*(n+1)
dpr = [(-INF,INF)]*(n+1)

for i in range(n):
    a,b = dpl[i]
    L,R = LR[i]
    dpl[i+1] = (max(a,L),min(b,R))
for i in range(n,0,-1):
    a,b = dpr[i]
    L,R = LR[i-1]
    dpr[i-1] = (max(a,L),min(b,R))

answer = 0
for (a,b),(c,d) in zip(dpl,dpr):
    l1 = max(L1,a); r1 = min(R1,b)
    l2 = max(L2,c); r2 = min(R2,d)
    x = max(0,r1-l1+1) + max(0,r2-l2+1)
    if answer < x:
        answer = x

x = max_width + max(0,min(R1,R2)-max(L1,L2)+1)
if answer < x:
    answer = x

print(answer)

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],x[1]])
ML = LR[0][0]
MR = LR[0][1]
LR.sort(key=lambda x:[x[1],-x[0]])
mR = LR[0][1]
mL = LR[0][0]

ans = max(mR-ML+1,0)
for i in range(N):
    if LR[i] not in [[ML,MR],[mL,mR]]:
        ans = max(ans,max(mR-ML+1,0)+max(LR[i][1]-LR[i][0]+1,0))

LR.sort(key=lambda x:[x[1],x[0]])

L_ = [0]*N
for i in range(N):
    L_[i] = max(LR[i][0],L_[i-1])

for i in range(1,N):
    ans = max(ans,max(LR[i][1]-ML+1,0)+max(mR-L_[i-1]+1,0))

print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
m = map(int,read().split())
LR = list(zip(m,m))

if N==2:
    L1,R1 = LR[0]
    L2,R2 = LR[1]
    answer = (R1-L1+1) + (R2-L2+1)
    print(answer)
    exit()

# 片方に集める場合
max_width = max(R-L+1 for L,R in LR)

LR.sort()

INF=10**18
# Rが最小のもの
i = -1
opt_R = INF
for n,(L,R) in enumerate(LR):
    if opt_R>=R:
        opt_R=R
        i=n
j = -1
opt_L = -INF
for n,(L,R) in enumerate(LR):
    if opt_L<=L:
        opt_L=L
        j=n

if i==j:
    L,R = LR[i]
    answer = max_width + (R-L+1)
    print(answer)
    exit()

L1,R1 = LR[i]; L2,R2 = LR[j]

LR = [(L,R) for n,(L,R) in enumerate(LR) if n != i and n != j]

LR.sort(key = lambda x: (x[0],-x[1]))

n = len(LR)
dpl = [(-INF,INF)]*(n+1)
dpr = [(-INF,INF)]*(n+1)

for i in range(n):
    a,b = dpl[i]
    L,R = LR[i]
    dpl[i+1] = (max(a,L),min(b,R))
for i in range(n,0,-1):
    a,b = dpr[i]
    L,R = LR[i-1]
    dpr[i-1] = (max(a,L),min(b,R))

answer = 0
for (a,b),(c,d) in zip(dpl,dpr):
    l1 = max(L1,a); r1 = min(R1,b)
    l2 = max(L2,c); r2 = min(R2,d)
    x = max(0,r1-l1+1) + max(0,r2-l2+1)
    if answer < x:
        answer = x

x = max_width + max(0,min(R1,R2)-max(L1,L2)+1)
if answer < x:
    answer = x

print(answer)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    lr = [list(map(int, input().split())) for _ in [0] * n]
    lr.sort(key=lambda x: (x[0], x[1]))
    min_r = [0] * n
    min_r[0] = lr[0][1]
    min_l = [0] * n
    min_l[n-1] = lr[n-1][1]
    for i in range(1,n):
        min_r[i] = min(min_r[i - 1], lr[i][1])
    for i in range(n-2,-1,-1):
        min_l[i] = min(min_l[i + 1], lr[i][1])
    ans = max([max(min_r[i] - lr[i][0] + 1, 0) + max(min_l[i + 1] - lr[n - 1][0] + 1, 0) for i in range(n - 1)])
    l,r,w=0,10**9+1,0
    for i in range(n):
        l = max(l, lr[i][0])
        r = min(r, lr[i][1])
        w = max(w, lr[i][1] - lr[i][0]+1)
    ans = max(ans, max(r - l + 1, 0) + w)
    print(ans)
main()

Submission status: Accepted

Solution code:
import sys
n = int(input())
lm, rm = 0, 10**10
seg = []
for _ in range(n):
	l, r = map(int, input().split())
	seg.append([l, r])
	lm = max(lm, l)
	rm = min(rm, r)

seg.sort(key=lambda x: (x[0], x[1]))
mins = [seg[-1][1]]
for i in range(n-2, -1, -1):
	mins.append(min(mins[-1], seg[i][1]))
mins.reverse()

ans = 0
for i in range(n):
	l, r = seg[i]
	if rm < l and r < lm:
		print(max([x[1]-x[0]+1 for x in seg]))
		sys.exit()
	elif lm == l and rm == r:
		print(max(rm-lm+1, 0) + max([x[1]-x[0]+1 for x in seg]))
		sys.exit()
	elif i < n-1:
		ans = max(ans, max(0, rm-l+1) + max(0, mins[i+1]-lm+1))

print(max(ans, max(rm-lm+1, 0) + max([x[1]-x[0]+1 for x in seg])))

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
maxlen = int(0)
maxi = 0
N = I()
LR =[[] for _ in range(N)]
LR2 =[]
for i in range(N):
    LR[i] = LI()
    C = LR[i][1] - LR[i][0]
    if C>maxlen:
        maxlen = C
        maxi = i
for i in range(N):
    if not i==maxi:
        LR2.append(LR[i])

LR.sort()
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]
#print(rightend)
#print(leftend)

cur1 = -1; cur2 = -1
for i in range(1,N):
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]

for i in range(N-2,-1,-1):
    if live2[i+1][1]<LR[i][0]:
        leftend = LR[i][0]
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]
#print(cur1,cur2)
#print(live1)
#print(live2)
#print(leftend)
if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)


LR2.sort()
live3 = LR2[0]
for i in range(1, N - 1):
    live3 = [max(live3[0], LR2[i][0]), min(live3[1], LR2[i][1])]
ansd = live3[1] - live3[0] + 1
anslen = max(ansd, 0) + maxlen+1

ans = max(max(ansC),anslen)
####################################################


#####################################################
LR.sort(key=lambda x:x[1])
rightend = LR[0][1]
leftend  = LR[N-1][0]

live1 = [[] for _ in range(N)]
live2 = [[] for _ in range(N)]
live1[0] = LR[0]
live2[N-1] = LR[N-1]
#print(rightend)
#print(leftend)

cur1 = -1; cur2 = -1
for i in range(1,N):
    if live1[i-1][1]>LR[i][1]:
        rightend = LR[i][1]
    if rightend<LR[i][0]:
        cur1 = i-1
        break
    live1[i] = [max(live1[i-1][0],LR[i][0]),min(live1[i-1][1],LR[i][1])]

for i in range(N-2,-1,-1):
    if live2[i+1][1]<LR[i][0]:
        leftend = LR[i][0]
    if leftend>LR[i][1]:
        cur2 = i+1
        break
    live2[i] = [max(live2[i+1][0],LR[i][0]),min(live2[i+1][1],LR[i][1])]
#print(cur1,cur2)
#print(live1)
#print(live2)
#print(leftend)
if cur1==-1:
    cur1=N-2
if cur2==-1:
    cur2=1
ansC = [0]*N
for i in range(cur2,cur1+2):
    ansC[i] = (live1[i-1][1]-live1[i-1][0]+1) + (live2[i][1]-live2[i][0]+1)

LR2.sort(key=lambda x:x[1])
live3 = LR2[0]
for i in range(1, N - 1):
    live3 = [max(live3[0], LR2[i][0]), min(live3[1], LR2[i][1])]
ansd = live3[1] - live3[0] + 1
anslen = max(ansd, 0) + maxlen+1

ans = max(max(ansC),anslen)


print(ans)
#print(ansC)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
LR = [tuple(map(int,input().split())) for i in range(N)]

ltor = {}
rtol = {}
l_dup = set()
r_dup = set()
ans = 0
for i,(l,r) in enumerate(LR):
    ans = max(ans, r-l+1)
    if l in ltor:
        ltor[l] = min(r, ltor[l])
        l_dup.add(l)
    else:
        ltor[l] = r
    if r in rtol:
        rtol[r] = max(l, rtol[r])
        r_dup.add(r)
    else:
        rtol[r] = l
ls = list(ltor.keys())
ls.sort()
rs = list(rtol.keys())
rs.sort(reverse=True)

if ls[-1] <= rs[-1]:
    for l,r in LR:
        maxl = ls[-1] if l!=ls[-1] or l in l_dup else ls[-2]
        minr = rs[-1] if r!=rs[-1] or r in r_dup else rs[-2]
        ans = max(ans, r-l+1 + minr-maxl+1)

ll_ans = [0]
minr = 10**9+10
for l in ls:
    r = ltor[l]
    minr = min(r, minr)
    ll_ans.append(max(0, minr - l + 1))

lr_ans = [0]
maxl = 0
minr = 10**9+10
for l in reversed(ls):
    r = ltor[l]
    minr = min(r, minr)
    maxl = max(l, maxl)
    lr_ans.append(max(0, minr - maxl + 1))
lr_ans.reverse()

rr_ans = [0]
maxl = -10
for r in rs:
    l = rtol[r]
    maxl = max(l, maxl)
    rr_ans.append(max(0, r - maxl + 1))

rl_ans = [0]
minr = 10**9
maxl = -10
for r in reversed(rs):
    l = rtol[r]
    maxl = max(l, maxl)
    minr = min(r, minr)
    rl_ans.append(max(0, minr - maxl + 1))
rl_ans.reverse()

for l,r in list(zip(ll_ans, lr_ans))[1:-1]:
    ans = max(ans, l+r)
for l,r in list(zip(rl_ans, rr_ans))[1:-1]:
    ans = max(ans, l+r)

print(ans)

Submission status: Accepted

Solution code:
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class SegmentTree():
    '''
    非再帰
    segment tree
    '''

    def __init__(self, n, func, init=float('inf')):
        '''
        n->配列の長さ
        func:func(a,b)->val,　func=minだとRMQになる
        木の高さhとすると,
        n:h-1までのノード数。h段目のノードにアクセスするために使う。
        data:ノード。
        parent:k->child k*2+1とk*2+2
        '''
        self.n = 2**(n-1).bit_length()
        self.init = init
        self.data = [init]*(2*self.n)
        self.func = func

    def set(self, k, v):
        '''
        あたいの初期化
        '''
        self.data[k+self.n-1] = v

    def build(self):
        '''
        setの後に一斉更新
        '''
        for k in reversed(range(self.n-1)):
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def update(self, k, a):
        '''
        list[k]=aに更新する。
        更新ぶんをrootまで更新
        '''
        k += self.n-1
        self.data[k] = a

        while k > 0:
            k = (k-1)//2
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def query(self, l, r):
        '''
        [l,r)のfuncを求める
        '''
        L = l+self.n
        R = r+self.n
        ret = self.init
        while L < R:
            if R & 1:
                R -= 1
                ret = self.func(ret, self.data[R-1])
            if L & 1:
                ret = self.func(ret, self.data[L-1])
                L += 1
            L >>= 1
            R >>= 1
        return ret


N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]
L = sorted(L, key=lambda x: x[0])

Seg_L = SegmentTree(N, lambda a, b: max(a, b), init=0)
Seg_R = SegmentTree(N, lambda a, b: min(a, b), init=float('inf'))

for i, q in enumerate(L):
    l, r = q[0], q[1]
    Seg_L.set(i, l)
    Seg_R.set(i, r)
Seg_L.build()
Seg_R.build()
cand = []
for pivot in range(1, N):
    low_1, high_1 = Seg_L.query(0, pivot), Seg_R.query(0, pivot)
    low_2, high_2 = Seg_L.query(pivot, N), Seg_R.query(pivot, N)
    p1 = max(high_1-low_1+1, 0)
    p2 = max(high_2-low_2+1, 0)
    ans = p1+p2
    cand.append(ans)
ans1 = max(cand)

cand2 = []
for rem in range(N):
    rem_low = Seg_L.query(rem, rem+1)
    rem_high = Seg_R.query(rem, rem+1)
    use_low = max(Seg_L.query(0, rem), Seg_L.query(rem+1, N))
    use_high = min(Seg_R.query(0, rem), Seg_R.query(rem+1, N))
    p1 = max(rem_high-rem_low+1, 0)
    p2 = max(use_high-use_low+1, 0)
    ans = p1+p2
    cand2.append(ans)
ans2 = max(cand2)
print(max(ans1, ans2))

Submission status: Accepted

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


class Segtree():
    def __init__(self, N):
        # N:  処理する区間の長さ
        self.N0 = 2**(N-1).bit_length()
        self.INF = 2**31-1
        self.seg_min = [self.INF]*(2*self.N0)

    def update(self, index, value):
        index += self.N0 - 1
        self.seg_min[index] = value
        while index > 0:
            index = (index - 1) // 2
            self.seg_min[index] = min(self.seg_min[index * 2 + 1], self.seg_min[index * 2 + 2])

    def query(self, first, last):
        first += self.N0 - 1
        last += self.N0 - 1
        ret = self.INF
        while first <= last:
            if not first & 1:
                ret = min(ret, self.seg_min[first])
            if last & 1:
                ret = min(ret, self.seg_min[last])
            first = first // 2
            last = last // 2 - 1
        return ret


N = int(input())
prob = []
max_len = 0
max_len_pair = []
for _ in range(N):
    L, R = map(int, input().split())
    if max_len < R - L + 1:
        max_len = R - L + 1
        max_len_pair = [(L, R)]
    elif max_len == R - L + 1:
        max_len_pair.append((L, R))
    prob.append((L, R))
prob.sort(key=lambda x: x[1])
prob.sort(key=lambda x: x[0])

segtree_L = Segtree(N)
segtree_R = Segtree(N)
for i in range(N):
    segtree_L.update(i, -prob[i][0])
    segtree_R.update(i, prob[i][1])

ans_best = 0
for i in range(N-1):
    ans1 = max(segtree_R.query(0, i) + segtree_L.query(0, i) + 1, 0)
    ans2 = max(segtree_R.query(i+1, N-1) + segtree_L.query(i+1, N-1) + 1, 0)
    ans_best = max(ans_best, ans1+ans2)

max_len_pair.sort(key=lambda x: x[0])
ans_another1 = max_len
ans_another2 = max_len
flg = 0
for i in range(N):
    if prob[i] == max_len_pair[0]:
        idx = i
        flg += 1
    if prob[i] == max_len_pair[-1]:
        idx2 = i
        flg += 1
    if flg == 2:
        break

Lmax1 = 0
Rmin1 = 10**9+1
Lmax2 = 0
Rmin2 = 10**9+1
for i in range(N):
    if i != idx:
        Lmax1 = max(Lmax1, prob[i][0])
        Rmin1 = min(Rmin1, prob[i][1])
    if i != idx2:
        Lmax2 = max(Lmax2, prob[i][0])
        Rmin2 = min(Rmin2, prob[i][1])
ans_another1 += max(0, Rmin1 - Lmax1 + 1)
ans_another2 += max(0, Rmin2 - Lmax2 + 1)

print(max(ans_best, ans_another1, ans_another2))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
P = 10**9
N = int(input())
LR = [ inpl() for _ in range(N) ]
LR.sort()

K = 0
mlist = []
for i in range(N):
    l, r = LR[i]
    k = r -l + 1
    if k == K:
        mlist.append(i)
    elif k > K:
        mlist = [i]
        K = k
U = []
r = P
for i in range(N):
    l = LR[i][0]
    r = min(r, LR[i][1])
    U.append((l,r))
D = [None]*N
l = LR[-1][0]
for i in range(N):
    r = min(r, LR[N-1-i][1])
    D[N-1-i] = (l,r)

ans = K
for m in mlist:
    if m == 0:
        score = K + max(0, D[1][1]-D[1][0]+1)
    elif m == N-1:
        score = K + max(0, U[-2][1]-U[-2][0]+1)
    else:
        score = K + max(0, min(U[m-1][1],D[m+1][1]) - D[m+1][0] + 1)
    if score > ans:
        ans = score

LR2 = []
for i in range(N):
    while LR2 and LR2[-1][1] >= LR[i][1]:
        LR2.pop()
    LR2.append(LR[i])
M = len(LR2)
if M < 2:
    print(ans)
    exit()

R1 = LR2[0][1]
L2 = LR2[-1][0]
for i in range(M-1):
    L1 = LR2[i][0]
    R2 = LR2[i+1][1]
    score = max(0, R1-L1+1) + max(0, R2-L2+1)
    if score > ans:
        ans = score

print(ans)

Submission status: Accepted

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

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 argsort(li, key=None, reverse=False):
    return [i for _, i in sorted([(a, i) for i, a in enumerate(li)], key=(lambda t: key(t[0])) if key else None, reverse=reverse)]


def solve():
    L, R = zip(*LR)
    L = list(L)
    R = list(R)
    if N == 2:
        ans = R[0] - L[0] + 1 + R[1] - L[1] + 1
        # ans = (R - L + 1).sum()
        print(ans)
        exit()

    # minR と minL のやつを同じグループにするとき、一番幅が広いのを他のグループにするのが最適。
    diff = [r - l for r, l in zip(R, L)]
    order = argsort(diff)
    L = [L[o] for o in order]
    R = [R[o] for o in order]
    diff.sort()
    li = L.index(max(L))
    ri = R.index(min(R))

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

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
# input = sys.stdin.readline

n = int(input())
lr = []
for i in range(n):
    l, r = [int(item) for item in input().split()]
    lr.append((l, r))
lr.sort()
al = lr[0][0]; ar = lr[0][1]; anum = ar - al + 1
bl = lr[1][0]; br = lr[1][1]; bnum = br - bl + 1
# for line in lr:
#     print(line)

for i in range(2, n):
    nl = lr[i][0]; nr = lr[i][1]
    # add new to a
    adda_l = max(al, nl)
    adda_r = min(ar, nr)
    adda_num = max(adda_r - adda_l + 1, 0)
    adda_ret = adda_num + bnum
    # add new to b
    addb_l = max(bl, nl)
    addb_r = min(br, nr)
    addb_num = max(addb_r - addb_l + 1, 0)
    addb_ret = addb_num + anum
    # create new
    create_l = max(al, bl)
    create_r = min(ar, br)
    create_num = max(create_r - create_l + 1, 0)
    cnum = nr - nl + 1
    create_ret = create_num + cnum

    if adda_ret >= addb_ret and adda_ret >= create_ret:
        al = adda_l
        ar = adda_r
        anum = adda_num
    elif addb_ret >= adda_ret and addb_ret >= create_ret:
        bl = addb_l
        br = addb_r
        bnum = addb_num
    else:
        al = create_l
        ar = create_r
        anum = create_num
        bl = nl
        br = nr
        bnum = cnum

print(anum + bnum)

Submission status: Accepted

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

N=int(input())
LR=[tuple(map(int,input().split())) for i in range(N)]

LR.sort()

# Segment tree(1-indexed,再帰を使わないもの,最小値を求める)

seg_el=1<<(N.bit_length())# Segment treeの台の要素数
SEG=[1<<30]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化

for i in range(N):# Aを対応する箇所へupdate. Aは0-indexedなことに注意. 
    SEG[i+seg_el]=LR[i][1]

for i in range(seg_el-1,0,-1):# 親の部分もupdate
    SEG[i]=min(SEG[i*2],SEG[i*2+1])

def update(n,x,seg_el):# A[n]をxへ更新（反映）
    i=n+seg_el
    SEG[i]=x
    i>>=1# 子ノードへ
    
    while i!=0:
        SEG[i]=min(SEG[i*2],SEG[i*2+1])
        i>>=1
        
def getvalues(l,r):# 区間[l,r)に関するminを調べる
    L=l+seg_el
    R=r+seg_el
    ANS=1<<30

    while L<R:
        if L & 1:
            ANS=min(ANS , SEG[L])
            L+=1

        if R & 1:
            R-=1
            ANS=min(ANS , SEG[R])
        L>>=1
        R>>=1

    return ANS

SEG2=[-1]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化

for i in range(N):# Aを対応する箇所へupdate. Aは0-indexedなことに注意. 
    SEG2[i+seg_el]=LR[i][0]

for i in range(seg_el-1,0,-1):# 親の部分もupdate
    SEG2[i]=max(SEG2[i*2],SEG2[i*2+1])

def update2(n,x,seg_el):# A[n]をxへ更新（反映）
    i=n+seg_el
    SEG2[i]=x
    i>>=1# 子ノードへ
    
    while i!=0:
        SEG2[i]=max(SEG2[i*2],SEG2[i*2+1])
        i>>=1
        
def getvalues2(l,r):# 区間[l,r)に関するmaxを調べる
    L=l+seg_el
    R=r+seg_el
    ANS=-1

    while L<R:
        if L & 1:
            ANS=max(ANS , SEG2[L])
            L+=1

        if R & 1:
            R-=1
            ANS=max(ANS , SEG2[R])
        L>>=1
        R>>=1

    return ANS

ANS=0

for i in range(N):
    ANS=max(ANS,LR[i][1]-LR[i][0]+1+max(0,min(getvalues(0,i),getvalues(i+1,N))-max(getvalues2(0,i),getvalues2(i+1,N))+1))

    #print(LR[i][1]-LR[i][0]+1+max(0,min(getvalues(0,i),getvalues(i+1,N))-max(getvalues2(0,i),getvalues2(i+1,N))+1))

LR2=[LR[0]]

for i in range(N):
    if LR[i][0]==LR2[-1][0]:
        continue
    while len(LR2)>0 and LR2[-1][0]<=LR[i][0] and LR2[-1][1]>=LR[i][1]:
        LR2.pop()

    LR2.append(LR[i])

LN=len(LR2)

SEG=[1<<30]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化

for i in range(LN):# Aを対応する箇所へupdate. Aは0-indexedなことに注意. 
    SEG[i+seg_el]=LR2[i][1]

for i in range(seg_el-1,0,-1):# 親の部分もupdate
    SEG[i]=min(SEG[i*2],SEG[i*2+1])

def update(n,x,seg_el):# A[n]をxへ更新（反映）
    i=n+seg_el
    SEG[i]=x
    i>>=1# 子ノードへ
    
    while i!=0:
        SEG[i]=min(SEG[i*2],SEG[i*2+1])
        i>>=1
        
def getvalues(l,r):# 区間[l,r)に関するminを調べる
    L=l+seg_el
    R=r+seg_el
    ANS=1<<30

    while L<R:
        if L & 1:
            ANS=min(ANS , SEG[L])
            L+=1

        if R & 1:
            R-=1
            ANS=min(ANS , SEG[R])
        L>>=1
        R>>=1

    return ANS

SEG2=[-1]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化

for i in range(LN):# Aを対応する箇所へupdate. Aは0-indexedなことに注意. 
    SEG2[i+seg_el]=LR2[i][0]

for i in range(seg_el-1,0,-1):# 親の部分もupdate
    SEG2[i]=max(SEG2[i*2],SEG2[i*2+1])

def update2(n,x,seg_el):# A[n]をxへ更新（反映）
    i=n+seg_el
    SEG2[i]=x
    i>>=1# 子ノードへ
    
    while i!=0:
        SEG2[i]=max(SEG2[i*2],SEG2[i*2+1])
        i>>=1
        
def getvalues2(l,r):# 区間[l,r)に関するmaxを調べる
    L=l+seg_el
    R=r+seg_el
    ANS=-1

    while L<R:
        if L & 1:
            ANS=max(ANS , SEG2[L])
            L+=1

        if R & 1:
            R-=1
            ANS=max(ANS , SEG2[R])
        L>>=1
        R>>=1

    return ANS


for i in range(1,LN):
    ANS=max(ANS,max(0,getvalues(0,i)-getvalues2(0,i)+1)+max(0,getvalues(i,LN)-getvalues2(i,LN)+1))

    #print(max(0,getvalues(0,i)-getvalues2(0,i)+1))
    #print(max(0,getvalues(i,LN)-getvalues2(i,LN)+1))

print(ANS)

Submission status: Accepted

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]]
a=li_test[0]
for i in range(1,n):
    a=min(li_test[i],a)
    li.append(a)

li_test=li_test[::-1]
li2=[li_test[0]]
a=li_test[0]
for i in range(1,n):
    a=min(li_test[i],a)
    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)
    tokubetu=lr[i][1]-lr[i][0]+1
    tokubetu2=max(0,li2[0]-maxi+1)
    check=max(one+two,tokubetu+tokubetu2)
    ans=max(ans,check)
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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

n = int(input())
lr = [[int(i) for i in readline().split()] for _ in range(n)]

from operator import itemgetter
lr.sort(key=itemgetter(1),reverse=True)

a,b = lr.pop()
lr.sort(reverse=True) #L大きい順

if n == 2:
    c,d=lr[0]
    print(d-c+1+b-a+1)
    exit()

#ひとつだけ[a,b]と逆
#print(a,b,lr)
res = 0
for l,r in lr[1:]:
    res = max(res,r-l+1)
#print(res,b,lr[0][0])
ans = res + max(0,b-max(a,lr[0][0])+1)

# [l,r] より右はぜったい逆
c,d = lr[0]
for l,r in lr[1:]:
    res = max(d-c+1,0) + max(b-l+1,0)
    ans = max(ans,res)
    c = max(c,l)
    d = min(d,r)


#[a,b]以外あっち
c = 0
d = 10**9
for l,r in lr:
    c = max(c,l)
    d = min(d,r)
ans = max(ans,max(d-c+1,0)+b-a+1)


print(ans)

Submission status: Accepted

Solution code:
n=int(input())
it=[]
for _ in range(n):
    it.append(list(map(int,input().split())))
it.sort()
ac=[i+[j] for j,i in enumerate(it[:])]
ac.sort(key=lambda x:x[1])
bc=[i+[j] for j,i in enumerate(it[:])]
bc.sort(key=lambda x:x[0],reverse=True)

maa=0
mi=bc[0][0]
ma=ac[0][1]
a=0
b=0
for i in range(n):
    if i==ac[0][2]:
        ma=ac[1][1]
        a=1
    if i==bc[0][2]:
        mi=bc[1][0]
        b=1
   # print(ma-mi+1)
    maa=max(max(ma-mi+1,0)+it[i][1]-it[i][0]+1,maa)
    if a:
        ma=ac[0][1]
        a=0
    if b:
        mi=bc[0][0]
        b=0

aa=[0]*n
bb=[0]*n
aa[0]=it[0][1]-it[0][0]+1
mi=it[0][0]
ma=it[0][1]
for i in range(1,n-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    aa[i]=so

bb[-1]=it[-1][1]-it[-1][0]+1
mi=it[-1][0]
ma=it[-1][1]

for i in range(n-2,0,-1):
    mi=max(mi,it[i][0])
    ma=min(ma,it[i][1])
    so=ma-mi+1
    if so<0:
        so=0
    bb[i]=so
ma=aa[0]+bb[1]
for i in range(1,n-1):
    ma=max(ma,aa[i]+bb[i+1])
print(max(ma,maa))

Submission status: Accepted

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

problem.sort()

min_r_up = [0] * n
r = problem[0][1]
for i in range(n):
    r = min(r, problem[i][1])
    min_r_up[i] = r

min_r_down = [0] * n
r = problem[-1][1]
for i in reversed(range(n)):
    r = min(r, problem[i][1])
    min_r_down[i] = r


ans = 0

for i in range(n-1):
    num = 0
    l1 = problem[i][0]
    l2 = problem[-1][0]

    # 1
    r1 = problem[i][1]
    if i >= 1:
        if min_r_up[i-1] < r1:
            r2 = min(min_r_up[i-1], min_r_down[i+1])
        else:
            r2 = min_r_down[i+1]
    else:
        r2 = min_r_down[i+1]

    num += max(0, r1-l1+1)
    num += max(0, r2-l2+1)

    ans = max(ans, num)

    # 2
    r1 = min_r_up[i]
    r2 = min_r_down[i+1]

    num = 0
    num += max(0, r1-l1+1)
    num += max(0, r2-l2+1)
    ans = max(ans, num)


print(ans)