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: Wrong Answer

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
    
    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))
    an += (mid_r - mid_l) * 2
    print(an)

Submission status: Wrong Answer

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()
    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))
    an += (mid_r - mid_l) * 2
    print(an)

Submission status: Wrong Answer

Solution code:
N=int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
max_L=0
min_R=10**9
for i in LR:
  max_L=max(max_L,i[0])
  min_R=min(min_R,i[1])

l=[]
r=[]
LR.sort()
for i in LR:
  l.append(min_R-i[0])
  r.append(i[1]-max_L)
  
ans=0
for i in range(N-1):
  ans = max(ans,l[i]+min(r[i+1:]))
  
print(ans+2)

Submission status: Wrong Answer

Solution code:
class SegmentTree(object):
    def __init__(self, n, func, init_val):#要素数、関数、単位元
        self.N0 = 2**((n-1).bit_length())
        self.func = func
        self.val = init_val
        self.data = [self.val]*(2*self.N0)
    def update(self, k, x):#k番目の値をxに変更する　O(logn)
        k += self.N0-1
        self.data[k] = x
        while k >= 0:
            k = (k - 1) // 2
            self.data[k] = self.func(self.data[2*k+1], self.data[2*k+2])
    def query(self, l, r):# 区間[l, r)の最小値を求める
        L = l + self.N0; R = r + self.N0
        s = self.val
        while L < R:
            if R & 1:
                R -= 1
                s = self.func(s, self.data[R-1])
 
            if L & 1:
                s = self.func(s, self.data[L-1])
                L += 1
            L >>= 1; R >>= 1
        return s
N = int(input())
S1 = SegmentTree(N, max, 0)
S2 = SegmentTree(N, min, float('inf'))
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)
tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp
R = lr[-1][1]
tmp = [lr[-1]]
for l, r in lr[-2::-1]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]
for i in range(len(lr)):
    l, r = lr[i]
    S1.update(i, l)
    S2.update(i, r)
for i in range(len(lr)-1):
    l = S1.query(0, i+1)
    r = S2.query(i+1, N)
    ans = max(ans, r-l+1)


print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [[]]*N
max_n = 0
min_n = 10**9
for i in range(N):
    LR[i] = list(map(int, input().split()))
    min_n = min(min_n, LR[i][0])
    max_n = max(max_n, LR[i][1])

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


set2 = [LR[0][0], LR[0][1]]
set1 = [LR[1][0], LR[1][1]]

LR = sorted(LR[2:], key=lambda x: x[1]-max_n)

for i in range(N-2):
    if max((min(set1[1], LR[i][1]) - max(set1[0], LR[i][0]))+1, 0)+(set2[1]-set2[0]+1) >= max((min(set2[1], LR[i][1]) - max(set2[0], LR[i][0])+1), 0) + (set1[1]-set1[0]+1):
        set1 = [max(set1[0], LR[i][0]), min(set1[1], LR[i][1])]
    else:
        set2 = [max(set2[0], LR[i][0]), min(set2[1], LR[i][1])]

ans1 = max(set1[1] - set1[0]+1, 0) + max(set2[1]-set2[0]+1, 0)

print(ans1)

Submission status: Wrong Answer

Solution code:
class SegmentTree(object):
    def __init__(self, n, func, init_val):#要素数、関数、単位元
        self.N0 = 2**((n-1).bit_length())
        self.func = func
        self.val = init_val
        self.data = [self.val]*(2*self.N0)
    def update(self, k, x):#k番目の値をxに変更する　O(logn)
        k += self.N0-1
        self.data[k] = x
        while k >= 0:
            k = (k - 1) // 2
            self.data[k] = self.func(self.data[2*k+1], self.data[2*k+2])
    def query(self, l, r):# 区間[l, r)の最小値を求める
        L = l + self.N0; R = r + self.N0
        s = self.val
        while L < R:
            if R & 1:
                R -= 1
                s = self.func(s, self.data[R-1])
 
            if L & 1:
                s = self.func(s, self.data[L-1])
                L += 1
            L >>= 1; R >>= 1
        return s
N = int(input())
S1 = SegmentTree(N, max, 0)
S2 = SegmentTree(N, min, float('inf'))
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)
tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp
R = lr[-1][1]
tmp = [lr[-1]]
for l, r in lr[-2::-1]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]
for i in range(len(lr)):
    l, r = lr[i]
    S1.update(i, l)
    S2.update(i, r)
for i in range(len(lr)):
    l = S1.query(0, i)
    r = S2.query(i, N)
    ans = max(ans, r-l+1)


print(ans)

Submission status: Wrong Answer

Solution code:
class SegmentTree(object):
    def __init__(self, n, func, init_val):#要素数、関数、単位元
        self.N0 = 2**((n-1).bit_length())
        self.func = func
        self.val = init_val
        self.data = [self.val]*(2*self.N0)
    def update(self, k, x):#k番目の値をxに変更する　O(logn)
        k += self.N0-1
        self.data[k] = x
        while k >= 0:
            k = (k - 1) // 2
            self.data[k] = self.func(self.data[2*k+1], self.data[2*k+2])
    def query(self, l, r):# 区間[l, r)の最小値を求める
        L = l + self.N0; R = r + self.N0
        s = self.val
        while L < R:
            if R & 1:
                R -= 1
                s = self.func(s, self.data[R-1])
 
            if L & 1:
                s = self.func(s, self.data[L-1])
                L += 1
            L >>= 1; R >>= 1
        return s
N = int(input())
S1 = SegmentTree(N, max, 0)
S2 = SegmentTree(N, min, float('inf'))
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)
for i in range(N):
    l, r = lr[i]
    S1.update(i, l)
    S2.update(i, r)
for i in range(N):
    l = S1.query(0, i)
    r = S2.query(i, N)
    ans = max(ans, r-l+1)


print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort(reverse = True)
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)

R = lr[0][1]
tmp = [lr[0]]
for l, r in lr[1:]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)

tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp[::-1]
R = lr[0][1]
tmp = [lr[0]]
for l, r in lr[1:]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort()
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)

tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp[::-1]
R = lr[0][1]
tmp = [lr[0]]
for l, r in lr[1:]:
    if R<=r:
        print(l, r)
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

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

if answer < max_width:
    answer = max_width

print(answer)

Submission status: Wrong Answer

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

n = int(input())
A = [list(map(int,input().split())) for i in range(n)]

mR = float("inf")
ML = -float("inf")
indmR = 0
indML = 0
lenmR = 0
lenML = 0
for i in range(n):
    if mR > A[i][1] or (mR == A[i][1] and lenmR >= A[i][1]-A[i][0]+1):
        lenmR = A[i][1]-A[i][0]+1
        indmR = i
        mR = A[i][1]
    if ML < A[i][0] or (ML == A[i][0] and lenML > A[i][1]-A[i][0]+1):
        lenML = A[i][1]-A[i][0]+1
        indML = i
        ML = A[i][0]

ans = 0
lenmax2 = 0
for i in range(n):
    if i != indML and i != indmR:
        lenmax2 = max(lenmax2, A[i][1]-A[i][0]+1)

ans = max(0, mR-ML+1) + lenmax2
# print("ans",ans)

if indML != indmR:
    
    aa =[[ML, A[indML][1]], [A[indmR][0], mR]]
    aa_h = [[j for j in i] for i in aa]

    if indmR > indML:
        A.pop(indmR)
        A.pop(indML)
    else:
        A.pop(indML)
        A.pop(indmR)
    # print(A)
    # print(aa)
    
    A.sort()
    k = float("inf")
    D = {}
    for i in range(len(A)):
        if A[i][0] > aa[1][0]:
            ind = min(aa[1][1]+1, A[i][0]) - aa[1][0]
            try:
                D[ind] = min(D[ind], min(aa[0][1],A[i][1]))
            except:
                D[ind] = min(aa[0][1],A[i][1])
    # print(D)
    D[0] = 0
    DD = []
    for i in D.keys():
        DD.append([i, D[i]])
    DD.sort()
    for i in range(len(DD)-1, 0, -1):
        DD[i-1][1] = min(DD[i-1][1], DD[i][1])
    for i in range(len(DD)-1, 0, -1):
        # print(i,k, DD[i-1][0]+aa[0][1]-DD[i][1],DD[i-1][0],aa[0][1],DD[i][1])
        k = min(k, DD[i-1][0]+aa[0][1]-DD[i][1])
    # print(DD[-1][0])
    k = min(k, DD[-1][0])


    ans = max(ans, aa[1][1]-aa[1][0]+aa[0][1]-aa[0][0]+2-k)
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys
from operator import itemgetter, add

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 **18
MOD = 10 ** 9 + 7

def compress(A):
    """ 座標圧縮 """

    zipped, unzipped = {}, {}
    for i, a in enumerate(sorted(set(A))):
        zipped[a] = i
        unzipped[i] = a
    return zipped, unzipped

class SegTree:
    """
    セグメント木
    1.update:  i番目の値をxに更新する
    2.query: 区間[l, r)の値を得る
    """

    def __init__(self, n, func, intv, A=[]):
        """
        :param n: 要素数(0-indexed)
        :param func: 値の操作に使う関数(min, max, add, gcdなど)
        :param intv: 要素の初期値(単位元)
        :param A: 初期化に使うリスト(オプション)
        """
        self.n = n
        self.func = func
        self.intv = intv
        # nより大きい2の冪数
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.intv] * (n2 << 1)
        # 初期化の値が決まっている場合
        if A:
            # 1段目(最下段)の初期化
            for i in range(n):
                self.tree[n2+i] = A[i]
            # 2段目以降の初期化
            for i in range(n2-1, -1, -1):
                self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1])

    def update(self, i, x):
        """
        i番目の値をxに更新
        :param i: index(0-indexed)
        :param x: update value
        """
        i += self.n2
        self.tree[i] = x
        while i > 1:
            self.tree[i >> 1] = x = self.func(x, self.tree[i ^ 1])
            i >>= 1
 
    def query(self, a, b):
        """
        [a, b)の値を得る
        :param a: index(0-indexed)
        :param b: index(0-indexed)
        """
        l = a + self.n2
        r = b + self.n2
        s = self.intv
        while l < r:
            if r & 1:
                r -= 1
                s = self.func(s, self.tree[r])
            if l & 1:
                s = self.func(s, self.tree[l])
                l += 1
            l >>= 1
            r >>= 1
        return s

    def get(self, i):
        """ 一点取得 """
        return self.tree[i+self.n2]

def bisearch_max(mn, mx, func):
    """ 条件を満たす最大値を見つける二分探索 """

    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            # 上を探しに行く
            ok = mid
        else:
            # 下を探しに行く
            ng = mid
    return ok

def bisearch_min(mn, mx, func):
    """ 条件を満たす最小値を見つける二分探索 """

    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            # 下を探しに行く
            ok = mid
        else:
            # 上を探しに行く
            ng = mid
    return ok

N = INT()
LR = []
A = set()
for i in range(N):
    l, r = MAP()
    LR.append((l, r))
    A.add(l)
    A.add(r)

zipped, unzipped = compress(A)

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

l1 = LR[0][0]
r1 = LR[0][1]

l2 = 0
r2 = INF
st1 = SegTree(len(zipped), add, 0)
st2 = SegTree(len(zipped), add, 0)
for i in range(1, N):
    l, r = LR[i]
    l2 = max(l2, l)
    r2 = min(r2, r)
    st1.update(zipped[l], st1.get(zipped[l])+1)
    st2.update(zipped[r], st2.get(zipped[r])+1)

def check1(m):
    return st1.query(m, len(zipped)) == 0

def check2(m):
    return st2.query(0, m+1) == 0

ans = (r1-l1+1) + (r2-l2+1)
for i in range(1, N-1):
    l, r = LR[i]
    l1 = max(l1, l)
    r1 = min(r1, r)
    st1.update(zipped[l], st1.get(zipped[l])-1)
    st2.update(zipped[r], st2.get(zipped[r])-1)
    if st1.get(zipped[l]) == 0:
        idx = bisearch_min(-1, len(zipped), check1) - 1
        l2 = unzipped[idx]
    if st2.get(zipped[r]) == 0:
        idx = bisearch_max(0, len(zipped)+1, check2) + 1
        r2 = unzipped[idx]
    ans = max(ans, (r1-l1+1) + (r2-l2+1))
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort(reverse = True)
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)

tmp = [lr[0]]
for i in range(1, N):
    if lr[i][0] == lr[i-1][0]:
        continue
    else:
        tmp.append(lr[i])
lr = tmp[::-1]
R = lr[0][1]
tmp = [lr[0]]
for l, r in lr[1:]:
    if R<=r:
        continue
    tmp.append([l, r])
    R = r
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
max_l = 0
max_len = 0
min_r = 1001001001
min_len = 0
l_i = 0
r_i = 0
p = []
longest = 0
for i in range(n):
  l, r = map(int, input().split())
  p.append([l, r])
  if l - r + 1 > longest:
    longest = l - r + 1 
  if l > max_l:
    max_l = l
    l_i = i
  elif l == max_l:
    if r - l > max_len:
      l_i = i
      max_len = r - l
  if r < min_r:
    min_r = r
    r_i = i
  elif r == min_r:
    if r - l > min_len:
      r_i = i
      min_len = r - l
g1 = []
g2 = []
g1.append(p[l_i])
g2.append(p[r_i])
g1_r = p[l_i][1]
g1_l = p[l_i][0]
g2_r = p[r_i][1]
g2_l = p[r_i][0]
#最小rと最大rを別々のグループに入れる
for i in range(n):
  if i == l_i or i == r_i:
    continue
  else:
    if min(p[i][1] - g1_r, 0) < min(g2_l - p[i][0], 0):
      g2.append(p[i])
      g2_l = max(g2_l, p[i][0])
    else:
      g1.append(p[i])
      g1_r = min(g1_r, p[i][1])
ans = max(g1_r - g1_l + 1, 0) + max(g2_r -g2_l + 1, 0)
#ans2 = max(g2_r - g1_l + 1, 0) + longest

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort(reverse = True)
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)

tmp = [lr[0]]
R = lr[0][1]
for i in range(1, N):
    if lr[i][1]<R:
        tmp.append(lr[i])
        R = lr[i][1]
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
max_l = 0
max_len = 0
min_r = 1001001001
min_len = 0
l_i = 0
r_i = 0
p = []
longest = 0
for i in range(n):
  l, r = map(int, input().split())
  p.append([l, r])
  if l - r + 1 > longest:
    longest = l - r + 1 
  if l > max_l:
    max_l = l
    l_i = i
  elif l == max_l:
    if r - l > max_len:
      l_i = i
      max_len = r - l
  if r < min_r:
    min_r = r
    r_i = i
  elif r == min_r:
    if r - l > min_len:
      r_i = i
      min_len = r - l
g1 = []
g2 = []
g1.append(p[l_i])
g2.append(p[r_i])
g1_r = p[l_i][1]
g1_l = p[l_i][0]
g2_r = p[r_i][1]
g2_l = p[r_i][0]
#最小rと最大rを別々のグループに入れる
for i in range(n):
  if i == l_i or i == r_i:
    continue
  else:
    if min(p[i][1] - g1_r, 0) < min(g2_l - p[i][0], 0):
      g2.append(p[i])
      g2_l = max(g2_l, p[i][0])
    else:
      g1.append(p[i])
      g1_r = min(g1_r, p[i][1])
ans = max(g1_r - g1_l + 1, 0) + max(g2_r -g2_l + 1, 0)
ans2 = max(g2_r - g1_l + 1, 0) + longest

print(max(ans, ans2))

Submission status: Wrong Answer

Solution code:
N = int(input())
lr = []
L, R = [], []
for _ in range(N):
    l, r = map(int, input().split())
    lr.append((l, r))
    L.append(l)
    R.append(r)
lr.sort(reverse = True)
L.sort()
R.sort()
ans = 0
for l, r in lr:  
    m = L[-1]
    if L[-1] == l:
        m = L[-2]
    M = R[0]
    if R[0] == r:
        M = R[1]
    ans = max(ans, M-m+1+r-l+1)
tmp = [lr[0]]
R = lr[0][1]
for i in range(1, N):
    if lr[i][1]<R:
        tmp.append(lr[i])
lr = tmp[::-1]

ans1 = [0]
ans2 = [0]
R = lr[0][1]
for l, r in lr:
    if l>R:
        ans1.append(0)
    else:
        ans1.append(R-l+1)
L = lr[-1][0]
for l, r in lr[::-1]:
    if L>r:
        ans2.append(0)
    else:
        ans2.append(r-L+1)
for a, b in zip(ans1, ans2[::-1]):
    ans = max(ans, a+b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
max_l = 0
max_len = 0
min_r = 1001001001
min_len = 0
l_i = 0
r_i = 0
p = []
longest = 0
for i in range(n):
  l, r = map(int, input().split())
  p.append([l, r])
  if l - r + 1 > longest:
    longest = l - r + 1 
  if l > max_l:
    max_l = l
    l_i = i
  elif l == max_l:
    if r - l > max_len:
      l_i = i
      max_len = r - l
  if r < min_r:
    min_r = r
    r_i = i
  elif r == min_r:
    if r - l > min_len:
      r_i = i
      min_len = r - l
g1 = []
g2 = []
g1.append(p[l_i])
g2.append(p[r_i])
g1_r = p[l_i][1]
g1_l = p[l_i][0]
g2_r = p[r_i][1]
g2_l = p[r_i][0]
#最小rと最大rを別々のグループに入れる
for i in range(n):
  if i == l_i or i == r_i:
    continue
  else:
    if min(p[i][1] - g1_r, 0) < min(g2_l - p[i][0], 0):
      g2.append(p[i])
      g2_l = max(g2_l, p[i][0])
    else:
      g1.append(p[i])
      g1_r = min(g1_r, p[i][1])
ans = g1_r - g1_l + g2_r -g2_l + 2
ans2 = g2_r - g1_l + 1 + longest

print(max(ans, ans2))

Submission status: Wrong Answer

Solution code:
N = int(input())
X = list(list(map(int,input().split()))for i in range(N))
X.sort()
LL, LR = X[0]
RL, RR = X[-1]
L = [LR-LL+1]
R = [RR-RL+1]
for i in range(1,N-1):
    LL = X[i][0]
    LR = min(LR,X[i][1])
    RR = min(X[-i-1][1],RR)
    L.append(LR-LL+1)
    R.append(max(RR-RL+1,0))
ans = 0
for i in range(N-1):
    ans = max(ans,L[i]+R[-1-i])
print(ans)

Submission status: Wrong Answer

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,0,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: Wrong Answer

Solution code:
def pleasure(a,b):
    if a[1]<b[0] or b[1]<a[0]:
        return [0,-1]
    if a[0]<=b[0]<=a[1]<=b[1]:
        return [b[0],a[1]]
    if a[0]<=b[0]<=b[1]<=a[1]:
        return [b[0],b[1]]
    if b[0]<=a[0]<=b[1]<=a[1]:
        return [a[0],b[1]]
    if b[0]<=a[0]<=a[1]<=b[1]:
        return [a[0],a[1]]

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

first_contest = List[0]

# 問題1に対して最も楽しめない問題をsecond_contestに回す
worst_problem = 0
worst_pleasure_value = 1000000000
for i in range(N):
    now_pleasure = pleasure(List[0],List[i])
    now_pleasure_value = now_pleasure[1]-now_pleasure[0]+1
    if worst_pleasure_value > now_pleasure_value:
        worst_pleasure_value = now_pleasure_value
        worst_problem = i
second_contest = List[worst_problem]

# 順にどちらのコンテストに入れるかを考えていく
for i in range(N):
    pf = pleasure(first_contest,List[i])
    ps = pleasure(second_contest,List[i])
    if (pf[1]-pf[0]+1) - (first_contest[1]-first_contest[0]+1) > (ps[1]-ps[0]+1) - (second_contest[1]-second_contest[0]+1):
        first_contest = pf
    else:
        second_contest = ps
        
print(first_contest[1]-first_contest[0]+1+second_contest[1]-second_contest[0]+1)

Submission status: Wrong Answer

Solution code:
n = int(input())
max_l = 0
max_len = 0
min_r = 1001001001
min_len = 0
l_i = 0
r_i = 0
p = []
for i in range(n):
  l, r = map(int, input().split())
  p.append([l, r])
  if l > max_l:
    max_l = l
    l_i = i
  elif l == max_l:
    if r - l > max_len:
      l_i = i
      max_len = r - l
  if r < min_r:
    min_r = r
    r_i = i
  elif r == min_r:
    if r - l > min_len:
      r_i = i
      min_len = r - l
g1 = []
g2 = []
g1.append(p[l_i])
g2.append(p[r_i])
g1_r = p[l_i][1]
g1_l = p[l_i][0]
g2_r = p[r_i][1]
g2_l = p[r_i][0]
for i in range(n):
  if i == l_i or i == r_i:
    continue
  else:
    if min(p[i][1] - g1_r, 0) < min(g2_l - p[i][0], 0):
      g2.append(p[i])
      g2_l = max(g2_l, p[i][0])
    else:
      g1.append(p[i])
      g1_r = min(g1_r, p[i][1])
ans = g1_r - g1_l + g2_r -g2_l + 2
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
LR = [list(map(int, input().split())) for _ in range(N)]
Lmax = max([l for l, r in LR])
Rmin = min([r for l, r in LR])

sLR = sorted(LR, key=lambda x:(max(x[1] - Lmax, 0), - max(Rmin - x[0], 0)))  
L = [0] * N

l,r = sLR[0][0], sLR[0][1]
L[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  L[itr + 1] = max(r - l + 1, 0)
  
sLR = sLR[::-1]
R = [0] * N

l,r = sLR[0][0], sLR[0][1]
R[0] = r - l + 1
for itr, val in enumerate(sLR[1:]):
  l = max(l, val[0])
  r = min(r, val[1])
  R[itr + 1] = max(r - l + 1, 0)

ans = 0  
for l, r in zip(L[:-1], R[::-1][1:]):
  ans = max(ans, l + r) 

print(ans)

Submission status: Wrong Answer

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(0)
		sys.exit()
	elif lm == l and rm == r:
		print(rm-lm+1 + 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, rm-lm+1 + max([x[1]-x[0]+1 for x in seg])))