Problem:


Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000



Sample input:
4 2
1 3
2 4


Sample output:
2

Submission status: Accepted

Solution code:
n, m = list(map(int, input().split()))
lmax = 0
rmin = n
for i in range(m):
  l, r = list(map(int, input().split()))
  lmax = max(lmax, l)
  rmin = min(rmin, r)

if rmin<lmax:
  ans = 0
else:
  ans = rmin-lmax + 1
print(ans)

Submission status: Accepted

Solution code:
def main():
    N, M = map(int, input().split())
    LR = [
        list(map(int, input().split()))
        for _ in range(M)
    ]

    ans = f(N, M, LR)
    ans1 = cumsum(N, M, LR)
    assert ans == ans1
    # ans = WA(N, M, LR)
    # ans = TLE(N, M, LR)
    print(ans)


def cumsum(N, M, LR):
    a = [0] * (N + 1)
    for L, R in LR:
        a[L-1] += 1
        a[R] -= 1

    from itertools import accumulate
    a = accumulate(a)
    ans = sum(x == M for x in a)
    return ans


def WA(N, M, LR):
    import numpy as np
    a = np.zeros(N, dtype=int)
    for L, R in LR:
        a[L-1:R] += 1
    ans = (a == M).sum()
    return ans


def f(N, M, LR):
    l_max = max(L for L, _ in LR)
    r_min = min(R for _, R in LR)

    ans = r_min - l_max + 1
    ans = max(ans, 0)
    return ans


def TLE(N, M, LR):
    ans = 0
    for i in range(1, N+1):
        g = 0
        for L, R in LR:
            if L <= i <= R:
                g += 1
        if g == M:
            ans += 1

    return ans


if __name__ == '__main__':
    main()

Submission status: Accepted

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

left_max = -1
right_min = n+1

for i in range(m):
    s,t = map(int,input().split())
    left_max = max(left_max,s)
    right_min = min(right_min, t)
    
print(max(0, right_min - left_max +1))

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
G=[0]*(N+2)
for i in range(M):
    L,R=map(int,input().split())
    G[L]+=1
    G[R+1]-=1
GG=[0]*(N+2)
tmp=0
for i in range(N+2):
    tmp+=G[i]
    GG[i]=tmp
ans=GG.count(M)
print(ans)

Submission status: Accepted

Solution code:
n,m = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(m)]
L = max([i[0] for i in LR])
R = min([i[1] for i in LR])
print(max(R-L+1,0))

Submission status: Accepted

Solution code:
n, m=map(int, input().split())
grid = []
for i in range(m):
    array = list(map(int, input().strip().split()))
    grid.append(array)


maxa,mina=grid[0]
for i in range(1,m):
    if maxa<grid[i][0]:
        maxa=grid[i][0]
    if mina>grid[i][1]:
        mina=grid[i][1]

v=mina-maxa+1
if v>0:
    print(v)
else:
    print(0)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
l,r=0,n
for i in range(m):
    a,b=map(int,input().split())
    l=max(l,a)
    r=min(r,b)
print(max(r-l+1,0))

Submission status: Accepted

Solution code:
N, M = list(map(int, input().split()))
G_min, G_max = map(list, zip(*[list(map(int, input().split())) for i in range(M)]))
G_min.append(1)
G_max.append(N)
G_min = max(G_min)
G_max = min(G_max)

if G_max >= G_min:
  print(G_max-G_min+1)
else:
  print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
LR = [list(map(int, input().split()))[:2] for m in range(M)]

# 最初の 2つの値を初期の下限、上限を定めた範囲とする
minV, maxV = LR[0]

# 次の行以降について、下限と上限の範囲が狭まるならば更新していく
for m in range(1, M):
    if minV < LR[m][0]:
        minV = LR[m][0]
    if LR[m][1] < maxV:
        maxV = LR[m][1]

# 上限と下限の間に存在する整数値
w = maxV - minV + 1
if (w > 0):
    print(w)
else:
    print(0)

Submission status: Accepted

Solution code:
# 解説を見ての解答
from sys import stdin

n, m = map(int, stdin.readline().rstrip().split())
lr = [list(map(int, stdin.readline().rstrip().split())) for i in range(m)]

l, r = lr[0][0], lr[0][1]
for i in range(m):
    l = max(l, lr[i][0])
    r = min(r, lr[i][1])

print(max(0,r-l+1))

Submission status: Accepted

Solution code:
# ABC127C - Prison
# l-max < i < r-min -> max(0, r - l + 1)
import sys
input = sys.stdin.readline

n, m = list(map(int, input().rstrip().split()))
lst = [list(map(int, input().rstrip().split())) for _ in range(m)]
l, r = lst[0][0], lst[0][1]
for i in lst[1:]:
    l = max(l, i[0])
    r = min(r, i[1])
print(max(0, r - l + 1))

Submission status: Accepted

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

left, right = 0, int(1e6)
for i in range(M):
    L, R = map(int, input().split())
    left = max(L, left)
    right = min(R, right)

print(int(max(right - left + 1, 0)))

Submission status: Accepted

Solution code:
# ABC127C - Prison
# l-max < i < r-min -> count i
n, m = list(map(int, input().rstrip().split()))
lst = [list(map(int, input().rstrip().split())) for _ in range(m)]
l, r = lst[0][0], lst[0][1]
for i in lst[1:]:
    l = max(l, i[0])
    r = min(r, i[1])
print(max(0, r - l + 1))

Submission status: Accepted

Solution code:
# ABC127C - Prison
n, m = list(map(int, input().rstrip().split()))
lst = [list(map(int, input().rstrip().split())) for _ in range(m)]
ans = 0
l, r = lst[0][0], lst[0][1]
for i in lst[1:]:
    l = max(l, i[0])
    r = min(r, i[1])
for i in range(1, n + 1):
    if l <= i <= r:
        ans += 1
print(ans)

Submission status: Accepted

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

l, r = map(int, input().split())

for i in range(M-1):
    l2, r2 = map(int, input().split())
    if l2 > l:
        l = l2
    if r > r2:
        r = r2
if r - l + 1 > 0:
    print(r - l + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
from itertools import accumulate

n, m = map(int, input().split())
cards = [0] * (n+2)
for i in range(m):
  s, e = map(int, input().split())
  cards[s] += 1
  cards[e+1] -= 1
valids = list(accumulate(cards))
print(valids.count(m))

Submission status: Accepted

Solution code:
def update(pos, val):
  while(pos <= N):
    fen[pos] = fen[pos] + val
    pos = pos + (pos & -pos)

def query(pos):
  cont = 0
  while(pos > 0):
    cont = cont + fen[pos]
    pos = pos - (pos & - pos)
  return cont

N, M = map(int,input().split())
fen = [0] * (N + 2)
for i in range (M):
  A, B = map(int,input().split())
  update(A,1)
  update(B + 1,-1)
  #for j in range(1,N + 1):
    #print("ci sono x tessere per il punto " + str(j) + " " + str(query(i)))
  #print("---------")
#print()

ans = 0
for i in range(1,N + 1):
  if query(i) == M:
    ans = ans + 1
print(ans)

Submission status: Accepted

Solution code:
def c_prison(N, M, Gate_info):
    left_max = 1
    right_min = N
    for l, r in Gate_info:
        left_max = max(left_max, l)
        right_min = min(right_min, r)
    return right_min - left_max + 1 if left_max <= right_min else 0

N, M = [int(i) for i in input().split()]
Gate_info = [[int(i) for i in input().split()] for j in range(M)]
print(c_prison(N, M, Gate_info))

Submission status: Accepted

Solution code:
from itertools import product
import bisect
import sys


def input():
    return sys.stdin.readline()[:-1]


n, m = map(int, input().split())
n_min = 1
n_max = 10000000
for i in range(m):
    l, r = map(int, input().split())
    n_min = max(n_min, l)
    n_max = min(n_max, r)
ans = n_max-n_min+1
if ans < 0:
    ans = 0
print(ans)

Submission status: Accepted

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

l=1
r=N

for i in range(M):
  L,R = map(int,input().split())
  l = max(l,L)
  r = min(r,R)
print(max(r-l+1,0))

Submission status: Accepted

Solution code:
def c_prison(N, M, Gate_info):
    can_pass_through = [0] * (N + 2)  # [i]: i番目のIDカードで通過できるゲートの数
    for l, r in Gate_info:
        can_pass_through[l] += 1
        can_pass_through[r + 1] -= 1
    for i in range(1, N + 1):
        can_pass_through[i + 1] += can_pass_through[i]
    return sum([1 for p in can_pass_through if p == M])

N, M = [int(i) for i in input().split()]
Gate_info = [[int(i) for i in input().split()] for j in range(M)]
print(c_prison(N, M, Gate_info))

Submission status: Accepted

Solution code:
N, M = map(int,input().split())
LR = [list(map(int,input().split())) for _ in range(M)]

Lma = 0
Rmi = N + 1
for L, R in LR:
  Lma = max(L, Lma)
  Rmi = min(R, Rmi)

print(max(0, Rmi - Lma + 1))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
 
l_list = []
r_list = []
for i in range(M):
  l, r = map(int, input().split())
  l_list.append(l)
  r_list.append(r)
  
l = max(l_list)
r = min(r_list)
 
if r < l:
  print(0)
else:
  print(r-l+1)

Submission status: Accepted

Solution code:
def abc127c():
    N, M = (int(s) for s in input().split(" "))
    max = 0
    min = N + 1
    for i in range(0, M):
        L, R = (int(s) for s in input().split(" "))
        if L > max:
            max = L
        if R < min:
            min = R
    a = min - max + 1
    answer = a if a >= 0 else 0
    print(answer)
abc127c()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
c = [0 for _ in range(n+1)]
for _ in range(m):
    l, r = map(int, input().split())
    c[l-1] += 1
    c[r] -= 1
cur = ans = 0
for i in range(n):
    cur += c[i]
    c[i] = cur
    if c[i] == m:
        ans += 1
print(ans)

Submission status: Accepted

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

p=[]
q=[]

for i in range(m):
    l,r=map(int,input().split())
    p.append(l)
    q.append(r)

p1=max(p)
q1=min(q)

if q1>=p1:
    print(q1-p1+1)
else:
    print(0)

Submission status: Accepted

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

Ls = []
Rs = []
for i in range(0, M):
    l, r = input().split()
    Ls.append(int(l))
    Rs.append(int(r))

maxL = max(Ls)
minR = min(Rs)
result = max(0, minR-maxL+1)

print(result)

Submission status: Accepted

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

L_list = []
R_list = []
for i in range(M):
  L, R = map(int, input().split())
  L_list.append(L)
  R_list.append(R)

L = max(L_list)
R = min(R_list)

if R < L:
  print(0)
else:
  print(R - L + 1)

Submission status: Accepted

Solution code:
import sys
import numpy as np
N,M= (int(i) for i in input().split(" "))  

LR= np.array([[int(i) for i in input().split()] for i in range(M)]) 

L=np.max(LR[:,0])
R=np.min(LR[:,1])


el=np.sum(np.logical_and(LR>L,R>LR))

if L>R:
    print(0)
else:
    
    print(int((R-L)+1))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
Lmax = 0
Rmin = N
for i in range(M):
  L, R = map(int, input().split())
  Lmax = max(Lmax, L)
  Rmin = min(Rmin, R)
print(max(0, Rmin-Lmax+1))

Submission status: Accepted

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers):
    return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers):
    return reduce(LCM, numbers)
def LCM(m, n):
    return (m * n // fractions.gcd(m, n))
def unite(x, y):
    # それぞれのノードの根を求める
    x = root(x)
    y = root(y)
    if x == y:
        return
    # node[x]の根をyに変更する
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  # xが根の場合
        return x
    else:
        node[x] = root(node[x])  # 経路圧縮
        return node[x]
def dfs(v):
    # ノードに訪れた
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  # そもそもvとv2が辺でつながっていない
            continue
        if visited[v2] == True:  # もう見た
            continue
        dfs(v2)


n, m = MI()
lr = [LI() for _ in range(m)]
max_l = lr[0][0]
min_r = lr[0][1]
for l, r in lr:
    max_l = max(max_l, l)
    min_r = min(min_r, r)

print(min_r - max_l + 1 if max_l <= min_r else 0)

Submission status: Accepted

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

p = []
q = []

for i in range(m):
    l, r = map(int,input().split())
    p.append(l)
    q.append(r)

p1 = max(p)
q1 = min(q)


if q1 >= p1:
    print(q1 - p1 + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
ml=0
mr=100000
for i in range(m):
  l,r=map(int,input().split())
  ml=max(ml,l)
  mr=min(mr,r)
  if ml>mr:
    break
if ml<=mr:
  print(mr-ml+1)
else:
  print(0)

Submission status: Accepted

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


def solve(N: int, M: int, L: "List[int]", R: "List[int]"):
    lower = 0
    upper = 10000000000
    for i in range(M):
        lower = max(lower, L[i])
        upper = min(upper, R[i])
    if upper < lower:
        print(0)
    else:
        print(upper - lower + 1)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    L = [int()] * (M)  # type: "List[int]" 
    R = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        L[i] = int(next(tokens))
        R[i] = int(next(tokens))
    solve(N, M, L, R)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, m = map(lambda x: int(x), input().split(' '))
l = []
r = []
for i in range(m):
    l_tmp, r_tmp = map(lambda x: int(x), input().split(' '))
    l.append(l_tmp)
    r.append(r_tmp)

l_max = max(l)
r_min = min(r)

result = 0
if l_max <= r_min:
    result = r_min - l_max + 1
print(result)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
L1, R1 = map(int, input().split())
flag = 0
def find_key(L1,R1,L2,R2):
    if R1 < L2 or R2 < L1:
        return(False)
    else:
        a = [R1,L1,R2,L2]
        a.sort()
        return(a[1],a[2])

for i in range(M - 1):
    L,R = map(int, input().split())
    if find_key(L1,R1,L,R) != False:
        L1,R1 = find_key(L1,R1,L,R)
    else:
        flag = 1
        print(0)
        break
if flag == 0:
    print(R1-L1+1)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
ml=0
mr=100000
for i in range(m):
	l,r=map(int,input().split())
	ml=max(ml,l)
	mr=min(mr,r)
if ml<=mr:
	print(mr-ml+1)
else:
	print(0)

Submission status: Accepted

Solution code:
import numpy as np
N,M = map(int,input().split())
LR = [list(map(int,input().split())) for _ in range(M)]

# 軸ごとの計算をするためにnumpy配列に変換する
LRn = np.array(LR)


print(max(0, LRn.min(axis=0)[1] - LRn.max(axis=0)[0] + 1))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
l = [] 
r = []
count = 0

N, M = map(int, input().split())
l = [0] * M
r = [0] * M
for i in range(0,M):
    l[i], r[i] = map(int, input().split())

#idカードの生成
    
ml = max(l)
mr = min(r)

for i in range(1,N+1):
    if  ml <= i and i <= mr:
        count += 1

print(count)

Submission status: Accepted

Solution code:
*t,=map(int,open(0).read().split());print(max(0,min(t[3::2])-max(t[2::2])+1))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
conunt = 0
maxL = 0
minR = 0
maxL, minR = map(int, input().split())
for _ in range(M-1):
    a, b = map(int, input().split())
    if maxL <= a:
      maxL = a
    if minR >= b:
      minR = b
if maxL <= minR:
  print(minR - maxL +1)
else:
  print('0')

Submission status: Accepted

Solution code:
N,M = map(int, input().split())
gate_l = [[int(x) for x in input().split()] for _ in range(M)]

min_card = max(l[0] for l in gate_l)
max_card = min(l[1] for l in gate_l)

if max_card >= min_card:
    print(max_card - min_card +1)
    
else:
    print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
A = []
B = []
for _ in range(M):
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)
ans = min(B) - max(A) + 1

if ans < 1:
    print(0)
else:
    print(ans)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
L,R=1,n
for i in range(m):
	l,r=map(int,input().split())
	L=max(L,l)
	R=min(R,r)
print(max(R-L+1,0))

Submission status: Accepted

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

max_L = 0
min_R = 10**6
for i in range(M):
    l, r = map(int, input().split())
    if l > max_L:
        max_L = l
    if r < min_R:
        min_R = r
    
print(max(min_R - max_L + 1, 0))

Submission status: Accepted

Solution code:
from itertools import accumulate
from sys import exit, stdin
N, M = [int(_) for _ in stdin.readline().rstrip().split()]
imos = [0]*(N+1)
count = 0
for i in range(M):
    l, r = [int(_) for _ in stdin.readline().rstrip().split()]
    imos[l-1]+=1
    imos[r]-=1
imos = list(accumulate(imos))
for i in range(N+1):
    if imos[i] == M:
        count += 1
print(count)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
L,R=1,n
for i in range(m):
	l,r=map(int,input().split())
	L=max(L,l)
	R=min(R,r)
print(len([int(i) for i in range(L,R+1)]))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n,m = LI()
    t = [0 for i in range(n+1)]
    for i in range(m):
        l,r = LI()
        t[l-1] += 1
        t[r] -= 1
    for i in range(n):
        t[i+1] += t[i]
        if t[i] == m:
            t[i] = 1
        else:
            t[i] = 0
    print(sum(t[:n]))
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    q = I()
    m = 0
    l = [-float("inf"),float("inf")]
    x = 0
    num = 0
    for _ in range(q):
        Q = LI()
        if len(Q) == 1:
            print(x,m)
        else:
            z,a,b = Q
            m += b
            if num == 0:
                num += 1
                l = [a,float("inf")]
                x = a
            elif num == 1:
                if a != l[0]:
                    num += 1
                    l = [min(a,l[0]),max(a,l[0])]
                    x = l[0]
                    m += l[1]-l[0]
            else:
                num += 1
                if num % 2:
                    if l[0] <= a < l[1]:
                        m += min(a-l[0],l[1]-a)
                        x = a
                    elif a < l[0]:
                        m += l[0]-a
                        x = l[0]
                        l = [a,l[1]]
                    else:
                        m += a-l[1]
                        x = l[1]
                        l = [l[0],a]
                else:
                    if l[0] <= a < l[1]:
                        if a < x:
                            m += x-a
                            l = [a,x]
                            x = a
                        else:
                            m += a-x
                            l = [x,a]
                    elif a < l[0]:
                        m += x-a
                        x = l[0]
                        l = [l[0],x]
                    else:
                        m += a-x
                        l = [x,l[1]]
    return

#G
def G():
    return

#H
def H():
    return

#I
def I_():
    return

#J
def J():
    return

#Solve
if __name__ == "__main__":
    C()

Submission status: Accepted

Solution code:
import sys

N, M = map(lambda x: int(x), sys.stdin.readline().split(" "))

_min, _max = 1, 100000
for _ in range(0, M):
    L, R = map(lambda x: int(x), sys.stdin.readline().split(" "))
    _min = max(_min, L)
    _max = min(_max, R)
if _min > _max:
    print(0)
else:
    print(_max - _min + 1)

Submission status: Accepted

Solution code:
import numpy as np
from sys import stdin

def main():
    nm = [int(x) for x in stdin.readline().rstrip().split()]
    gate = np.zeros([nm[1], 2], dtype=int)
    
    for i in range(nm[1]):
        g = [int(x) for x in stdin.readline().rstrip().split()]
        gate[i] = g
    
    l_max = np.max(gate[:, 0])
    r_min = np.min(gate[:, 1])
    c = 0
    if l_max <= r_min:
        c = r_min-l_max+1
    print(c)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""



N, M = list(map(int, input().split()))
L=[0]*M
R=[0]*M


A = set(range(1, N+1))


for i in range(M):
    L[i], R[i] = list(map(int, input().split()))


def main():
    res = min(R)-max(L)+1
    if res > 0:
        print(res)
    else:
        print(0)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
maxL = 1
minR = N
for _ in range(M):
    l, r = map(int, input().split())
    maxL = max(maxL, l)
    minR = min(minR, r)
print(max(minR - maxL + 1, 0))
# 交差しない場合を考慮する

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
lr_list = [list(map(int, input().split())) for _ in range(m)]
max_l = 1
min_r = n
for lr in lr_list:
    max_l = max(max_l, lr[0])
    min_r = min(min_r, lr[1])
print(max(0, min_r - max_l + 1))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
lLst = [0] * M
rLst = [0] * M
for i in range(M):
    lLst[i], rLst[i] = map(int, input().split())

lLst.sort(reverse=True)
rLst.sort()
if lLst[0] > rLst[0]:
    ans = 0
else:
    ans = rLst[0] - lLst[0] + 1

print(ans)

Submission status: Accepted

Solution code:
N, M = map(int,input().split())
L = [0] * M
R = [0] * M
for i in range(M):
    L[i], R[i] = map(int, input().split())

if min(R) >= max(L):
    print(min(R) - max(L) + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
import sys

n, m = map(int, input().split())
l, r = map(int, input().split())

sys.setrecursionlimit(100000)


def check(i, l, r):
    if i == m:
        return max(r - l + 1, 0)
    l_, r_ = map(int, input().split())
    nl = max(l, l_)
    nr = min(r, r_)
    return check(i + 1, nl, nr)


print(check(1, l, r))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 5)

n, m = map(int, input().split())

l, r = map(int, input().split())


def check(i, l, r):
    if i == m:
        return max(r - l + 1, 0)
    l_, r_ = map(int, input().split())
    nl = max(l, l_)
    nr = min(r, r_)
    i += 1
    return check(i, nl, nr)


print(check(1, l, r))

Submission status: Accepted

Solution code:

"""
imos
"""
N, M = map(int,input().split())
from itertools import accumulate
imos = [0]*(N+2)
for i in range(M):
    L,R = map(int,input().split())
    imos[L] += 1
    imos[R+1] -= 1
acc = list(accumulate(imos))
print(sum([1 for a in acc if a == M]))

Submission status: Accepted

Solution code:
import numpy as np
n,m=map(int,input().split())
post_b = 0
post_c = n
for i in range(m):
    b,c=map(int,input().split())
    if post_b < b:
        post_b = b
    if post_c > c:
        post_c = c

if (post_c - post_b + 1)<0:
    print("0")
else:
    print(post_c - post_b + 1)

Submission status: Accepted

Solution code:
# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *
readl= lambda: list(map(int, sys.stdin.readline().split()))
readt= lambda: tuple(map(int, sys.stdin.readline().split()))
read = lambda: sys.stdin.readline().rstrip()
readi = lambda: int(read())
readmi = lambda: map(int, sys.stdin.readline().split())
readms = lambda: map(str, sys.stdin.readline().split())

n, m = readmi()
a = [0] * (n + 2)
r = defaultdict(int)
for i in range(m):
    x,y = readmi()
    a[x - 1] += 1
    a[y] += -1

for i in range(n + 1):
    a[i + 1] += a[i]
count = 0
flg = True
for i in range(n):
    if a[i] >= m:
        count += 1
print(count)

Submission status: Accepted

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

Ls, Rs = [0 for _ in range(M)],  [0 for _ in range(M)]

for i in range(M):
    L, R = map(int,input().split())
    Ls[i] = L
    Rs[i] = R
    
L_prime = max(Ls)
R_peime = min(Rs)

if L_prime > R_peime:
    print(0)
else:
    print(R_peime - L_prime + 1)

Submission status: Accepted

Solution code:
import collections
# s = [[]]
n, m = map(int,input().split())
s = [list(map(int,input().split())) for i in range(m)]

# n, m = 4, 2
# s = [[1,3], [2,4]]

if m == 1:
    print(s[0][-1] - s[0][0] + 1)
else:
    l = s[0][0]
    r = s[0][1]
    for i in range(1,m):
        l = max(l,s[i][0])
        r = min(r,s[i][1])
    print(max(r-l+1,0))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
l = []
for i in range(m):
  l.append([int(i) for i in input().split()])
maxL = l[0][0]
minR = l[0][1]
for j in range(1,m):
  if maxL <= l[j][0]:
    maxL = l[j][0]
  if minR >= l[j][1]:
    minR = l[j][1]
if maxL <= minR:
  print(minR - maxL + 1)
else:
  print(0)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
l, r = map(int, input().split())
li = []


for _ in range(m - 1):
    l_, r_ = map(int, input().split())
    l = max(l, l_)
    r = min(r, r_)


print(max(r - l + 1, 0))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
id = [list(map(int, input().split())) for _ in range(M)]
L = []
R = []
for i in range(M):
    L.append(id[i][0])
    R.append(id[i][1])
if max(L) <= min(R):
    print(min(R) - max(L) + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
import sys

n,m = input().split()
n,m = int(n), int(m)


list = []

count = 0
lMin, rMax = -1, -1

for i in range(0,m) :
    l, r = input().split()

    list.append((int(l),int(r)))

    if lMin == -1 and rMax == -1:
        lMin, rMax = list[i]
    else:
        if lMin < list[i][0] :
            lMin = list[i][0]
            
        if rMax > list[i][1] :
            rMax = list[i][1]

count = rMax - lMin +1

if count < 0 : 
    count = 0

print(count)

Submission status: Accepted

Solution code:
n,m=map(int, input().split())
maxl=0
minr=n
for _ in range(m):
    l,r=map(int, input().split())
    maxl = max(maxl, l)
    minr = min(minr, r)
print(minr-maxl+1 if maxl<=minr else 0)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
L = []
R = []
for i in range(m):
    l,r = map(int,input().split())
    L.append(l)
    R.append(r)
ans = 0
L = max(L)
R = min(R)
for i in range(1,n+1):
    if L <= i and R >= i:
        ans += 1
print(ans)