Problem:


Score : 700 points

Problem Statement

N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.

Tak the traveler has the following two personal principles:

He never travels a distance of more than L in a single day.

He never sleeps in the open. That is, he must stay at a hotel at the end of a day.

You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.

Constraints

2 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq Q \leq 10^5

1 \leq x_i < x_2 < ... < x_N \leq 10^9

x_{i+1} - x_i \leq L

1 \leq a_j,b_j \leq N

a_j \neq b_j

N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.

Partial Score

200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.

Input

The input is given from Standard Input in the following format:

N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q

Output

Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.

Sample Input 1

9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5

Sample Output 1

4
2
1
2

For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:

Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.

Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.

Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.

Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 10.



Sample input:
9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5


Sample output:
4
2
1
2

Submission status: Runtime Error

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    _LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    x = LI()
    L = NI()
    m = N.bit_length()
    f = [[N-1] * N for _ in range(m)]
    j = 1
    for i in range(N-1):
        while x[i] + L >= x[j+1]:
            j += 1
            if j >= N-1: break
        f[0][i] = j
    for k in range(1,m):
        for i in range(N):
            f[k][i] = f[k-1][f[k-1][i]]

    for _ in range(NI()):
        ans = 0
        a,b = _LI()
        if a > b: a,b = b,a

        for k in range(m-1,-1,-1):
            if f[k][a] < b:
                ans += 2**k
        print(ans+1)



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    x = LI()
    f = [[] for i in range(n)]
    l = I()
    for i in range(n):
        xi = x[i]
        j = bisect.bisect_right(x,l+xi)-1
        f[i].append(j)
    h = int(math.log(n,2))+1
    for j in range(h-1):
        for i in range(n):
            f[i].append(f[f[i][j]][j])
    q = I()
    for _ in range(q):
        a,b = LI()
        a -= 1
        b -= 1
        if b < a:
            a,b = b,a
        ans = 0
        while a != b:
            i = bisect.bisect_left(f[a],b)
            ans += 1<<i
            a = f[a][i]
        print(ans)
    return

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

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * k for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
#print(e)

def doubling(u, v):
  if u == v: return 0
  ok = -1
  ng = len(e[u])
  while ng - ok > 1:
    m = (ok + ng) // 2
    if e[u][m] < v: ok = m
    else: ng = m
  if ok < 0: return 1
  return doubling(e[u][ok], v) + pow(2, ok)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * k for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
#print(e)

def doubling(u, v):
  if u == v: return 0
  x = min(len(e[u]) - 1, bl(e[u], v))
  if x == 0: return 1
  x -= e[u][x] > v
  x = max(0, x)
  return doubling(e[u][x], v) + pow(2, x)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * k for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
#print(e)

def doubling(u, v):
  if u == v: return 0
  x = min(len(e[u]) - 1, bl(e[u], v))
  #print(u, v, x)
  return doubling(e[u][x], v) + pow(2, x)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * (k + 1) for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
print(e)

def doubling(u, v):
  if u == v: return 0
  x = bl(e[u], v)
  x = max(0, x - (e[u][x] == N - 1))
  #print(u, v, x)
  return doubling(e[u][x], v) + pow(2, x)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * (k + 1) for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
#print(e)

def doubling(u, v):
  if u == v: return 0
  x = bl(e[u], v)
  #print(u, v, x)
  return doubling(e[u][x], v) + pow(2, x)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
L = int(input())
k = 0
while a[-1] // (L * pow(2, k)): k += 1
e = [[0] * (k + 1) for _ in range(N)]
for i in range(N):
  t = L + a[i]
  ok = i
  ng = N
  while ng - ok > 1:
    m = (ok + ng) // 2
    if a[m] <= t: ok = m
    else: ng = m
  e[i][0] = ok
for j in range(len(e[i]) - 1):
  for i in range(N):
    x = e[i][j]
    e[i][j + 1] = e[x][j]
#print(e)

def doubling(u, v):
  if u == v: return 0
  x = bl(e[u], v)
  #print(u, v, x)
  return doubling(e[u][x], v) + pow(2, x)

Q = int(input())
for _ in range(Q):
  x, y = map(int, input().split())
  x -= 1
  y -= 1
  if x > y: x, y = y, x
  print(doubling(x, y))

Submission status: Runtime Error

Solution code:
import bisect

def wantp(p,day,db):

    for i in range(len(db)):
        i = len(db)-1-i

        if day & (2 ** i) > 0:
            p = db[i][p]

    return p

N = int(input())

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

L = int(input())

able = []

for i in range(N):

    able.append(bisect.bisect_right(x,x[i] + L) - 1)

#print (able)

db = [able]

while min(db[-1]) != N-1:

    new = []

    for i in range(N):

        new.append(db[-1][db[-1][i]])

    db.append(new)

db1 = db.copy()

for i in range(N):
    x[i] = x[-1] - x[i]
x.reverse()
#print (x)

able = []
for i in range(N):
    able.append(bisect.bisect_right(x,x[i] + L) - 1)
db = [able]
while min(db[-1]) != N-1:
    new = []
    for i in range(N):
        new.append(db[-1][db[-1][i]])
    db.append(new)
db2 = db
#print (db2)


Q = int(input())

for loop in range(Q):

    a,b = map(int,input().split())
    a -= 1
    b -= 1

    if a < b:

        l = 0
        r = N+1

        while r-l != 1:

            m = (l+r) // 2

            np = wantp(a,m,db1)
            #print (a,m,np)

            if np < b:
                l = m
            else:
                r = m

        print (r)

    else:
        a = N-1-a
        b = N-1-b

        l = 0
        r = N+1

        while r-l != 1:

            m = (l+r) // 2

            np = wantp(a,m,db2)
            #print (a,m,np)

            if np < b:
                l = m
            else:
                r = m

        print (r)

Submission status: Runtime Error

Solution code:
from bisect import bisect_right

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

depth = [-1]*n
depth[-1] = 0

m = 18
par = [[-1]*n for i in range(m)]

def dfs(i):
    if depth[i] >= 0:
        return depth[i]
    j = bisect_right(x, x[i]+l)-1
    if j >= n:
        j = n-1
    par[0][i] = j
    depth[i] = dfs(j) + 1
    return depth[i]

for i in range(n):
    dfs(i)

for i in range(17):
    for j in range(n):
        par[i+1][j]=par[i][par[i][j]]

def hoge(x, y):
# xからk個上の頂点がy以上になる最小のkを求める
    k = 0
    for i in range(18)[::-1]:
        if 0 <= par[i][x] <= y:
            k += 1<<i
            x = par[i][x]
    return k

q = int(input())
ans = []
for i in range(q):
    a,b = map(int, input().split())
    a,b = a-1,b-1
    if a > b:
        a,b = b,a
    ans.append(hoge(a, b))

print(*ans, sep="\n")

Submission status: Runtime Error

Solution code:
import bisect
import math
n = int(input())
x = list(map(int, input().split()))
l = int(input())

max_pow = math.ceil(math.log2(x[-1]//l))+1
next_hotel = [[i for j in range(max_pow+1)] for i in range(n)]

head = 1
tail = 0
while head < n:
    if x[tail]+l < x[head]:
        next_hotel[tail][1] = head-1
        tail += 1
    else:
        head += 1
else:
    for i in range(tail, n):
        next_hotel[i][1] = n-1

for i in range(1, max_pow):
    b = 2**i
    for j in range(n-1):
        next_hotel[j][i+1] = next_hotel[next_hotel[j][i]][i]

q = int(input())
for _ in range(q):
    a, b = map(int, input().split())
    a -= 1
    b -= 1

    if a > b:
        a, b = b, a
    total = 0
    while a < b:
        t = bisect.bisect_left(next_hotel[a], b)
        if t == 0:
            break
        else:
            total += 2**(t-1)
            a = next_hotel[a][t]
    print(total)

Submission status: Runtime Error

Solution code:
import os
import sys

import numpy as np

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

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

N = int(sys.stdin.readline())
X = list(map(int, sys.stdin.readline().split()))
L = int(sys.stdin.readline())
Q = int(sys.stdin.readline())
AB = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

N += 2
X = [X[0]] + X + [X[-1]]
X = np.array(X, dtype=int)
# rdp[d][i]: i番のホテルから(2^d)日で何個右までいけるか
rdp = np.zeros((N.bit_length(), N), dtype=int)
rdp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    rdp[d] = rdp[d - 1] + rdp[d - 1][np.arange(N) + rdp[d - 1]]

X = -X[::-1]
# ldp[d][i]: i番のホテルから(2^d)日で何個左までいけるか
ldp = np.zeros((N.bit_length(), N), dtype=int)
ldp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    ldp[d] = ldp[d - 1] + ldp[d - 1][np.arange(N) + ldp[d - 1]]


# print(rdp)
# print(ldp)


def solver(l, r):
    ret = 0
    while l < r:
        d = np.searchsorted(rdp[:, l], r - l)
        if rdp[d, l] == r - l:
            ret += 2 ** d
            break
        if d > 0:
            d -= 1
        ret += 2 ** d
        l += rdp[d, l]
    return ret


def solvel(l, r):
    r = N - r - 1
    l = N - l - 1
    ret = 0
    while l < r:
        d = np.searchsorted(ldp[:, l], r - l)
        if ldp[d, l] == r - l:
            ret += 2 ** d
            break
        if d > 0:
            d -= 1
        ret += 2 ** d
        l += ldp[d, l]
    return ret


# print(np.searchsorted([1, 2, 5, 8, 9], 3))
# print(np.searchsorted([1, 2, 5, 8, 9], 4))
# print(np.searchsorted([1, 2, 5, 8, 9], 5))
# print(np.searchsorted([1, 2, 5, 8, 9], 6))
# print(np.searchsorted([1, 2, 5, 8, 9], 7))
# print()

for a, b in AB:
    if a < b:
        r = solver(a, b)
    else:
        r = solvel(a, b)
    print(r)

Submission status: Runtime Error

Solution code:
import os
import sys

import numpy as np

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

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

N = int(sys.stdin.readline())
X = list(map(int, sys.stdin.readline().split()))
L = int(sys.stdin.readline())
Q = int(sys.stdin.readline())
AB = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

N += 1
X.append(X[-1])
X = np.array(X, dtype=int)
# rdp[d][i]: i番のホテルから(2^d)日で何個右までいけるか
rdp = np.zeros((N.bit_length(), N), dtype=int)
rdp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    rdp[d] = rdp[d - 1] + rdp[d - 1][np.arange(N) + rdp[d - 1]]

X = -X[::-1]
# ldp[d][i]: i番のホテルから(2^d)日で何個左までいけるか
ldp = np.zeros((N.bit_length(), N), dtype=int)
ldp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    ldp[d] = ldp[d - 1] + ldp[d - 1][np.arange(N) + ldp[d - 1]]


# print(rdp)
# print(ldp)


def solver(l, r):
    ret = 0
    while l < r:
        d = np.searchsorted(rdp[:, l], r - l)
        if rdp[d, l] == r - l:
            ret += 2 ** d
            break
        if d > 0:
            d -= 1
        ret += 2 ** d
        l += rdp[d, l]
    return ret


def solvel(l, r):
    r = N - r - 1
    l = N - l - 1
    ret = 0
    while l < r:
        d = np.searchsorted(ldp[:, l], r - l)
        if ldp[d, l] == r - l:
            ret += 2 ** d
            break
        if d > 0:
            d -= 1
        ret += 2 ** d
        l += ldp[d, l]
    return ret


# print(np.searchsorted([1, 2, 5, 8, 9], 3))
# print(np.searchsorted([1, 2, 5, 8, 9], 4))
# print(np.searchsorted([1, 2, 5, 8, 9], 5))
# print(np.searchsorted([1, 2, 5, 8, 9], 6))
# print(np.searchsorted([1, 2, 5, 8, 9], 7))
# print()

for a, b in AB:
    if a < b:
        r = solver(a - 1, b - 1)
    else:
        r = solvel(a - 1, b - 1)
    print(r)

Submission status: Runtime Error

Solution code:
import os
import sys

import numpy as np

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

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

N = int(sys.stdin.readline())
X = list(map(int, sys.stdin.readline().split()))
L = int(sys.stdin.readline())
Q = int(sys.stdin.readline())
AB = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

X = np.array(X, dtype=int)
# rdp[d][i]: i番のホテルから(2^d)日で何個右までいけるか
rdp = np.zeros((N.bit_length(), N), dtype=int)
rdp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    rdp[d] = rdp[d - 1] + rdp[d - 1][np.arange(N) + rdp[d - 1]]

X = -X[::-1]
# ldp[d][i]: i番のホテルから(2^d)日で何個左までいけるか
ldp = np.zeros((N.bit_length(), N), dtype=int)
ldp[0] = np.searchsorted(X, X + L, side='right') - np.arange(N) - 1
for d in range(1, N.bit_length()):
    ldp[d] = ldp[d - 1] + ldp[d - 1][np.arange(N) + ldp[d - 1]]

# print(rdp)
# print(ldp)


def solver(l, r):
    ret = 0
    while l < r:
        d = np.searchsorted(rdp[:, l], r - l)
        if d > 0 and rdp[d, l] > r - l:
            d -= 1
        ret += 2 ** d
        l += rdp[d, l]
    return ret


def solvel(l, r):
    r = N - r - 1
    l = N - l - 1
    ret = 0
    while l < r:
        d = np.searchsorted(ldp[:, l], r - l)
        if d > 0 and ldp[d, l] > r - l:
            d -= 1
        ret += 2 ** d
        l += ldp[d, l]
    return ret


# print(np.searchsorted([1, 2, 5, 8, 9], 3))
# print(np.searchsorted([1, 2, 5, 8, 9], 4))
# print(np.searchsorted([1, 2, 5, 8, 9], 5))
# print(np.searchsorted([1, 2, 5, 8, 9], 6))
# print(np.searchsorted([1, 2, 5, 8, 9], 7))
# print()

for a, b in AB:
    if a < b:
        r = solver(a - 1, b - 1)
    else:
        r = solvel(a - 1, b - 1)
    print(r)

Submission status: Runtime Error

Solution code:
from bisect import*
r=range
n,*t=map(int,open(0).read().split())
m=2**16
x=t[:n]
d=[[bisect(x,y+t[n])-1for y in x]]+[[0]*n for _ in r(m)]
for i in r(m):
  for j in r(n):
    d[i+1][j]=d[i][d[i][j]]
for a,b in zip(t[n+2::2],t[n+3::2]):
  a-=1
  b-=1
  if b<a:a,b=b,a
  c=1
  for i in r(m,-1,-1):
    if d[i][a]<b:
      a=d[i][a]
      c+=2**i
  print(c)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

#define FOR(i,a,b) for (int i=(a);i<(b);++i)
#define REP(i,n) for (int i=0;i<(n);++i)
#define RREP(i,n) for (int i=(n)-1;i>=0;--i)
#define all(a) (a).begin(),(a).end()

using namespace std;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    int N, L, Q;
    cin >> N;
    vector<int> x(N);
    REP(i, N) cin >> x[i];
    cin >> L >> Q;

    int K = 31 - __builtin_clz(N - 1); // floor(log(max(b - a)))
    vector<vector<int>> dp(N, vector<int>(K + 1));
    REP(i, N) {
        dp[i][0] = distance(x.begin(), upper_bound(all(x), x[i] + L)) - 1;
        //printf("dp[%d][0] = %d\n", i, dp[i][0]);
    }
    FOR(j, 1, K + 1) REP(i, N) {
        dp[i][j] = dp[dp[i][j - 1]][j - 1];
    }

    REP(_, Q) {
        int a, b;
        cin >> a >> b;
        --a; --b;
        if (a > b) {
            swap(a, b);
        }
        int result = 0;
        RREP(i, K + 1) {
            if (dp[a][i] < b) {
                //printf("from x[%d] to x[%d] in %d days\n", a, dp[a][i], 1 << i);
                a = dp[a][i];
                result += 1 << i;
            }
        }
        ++result;
        cout << result << '\n';
    }
    cout << flush;

    return 0;
}

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left, bisect_right
from functools import lru_cache

sys.setrecursionlimit(10 ** 5 + 1)


@lru_cache(maxsize=None)
def solve(l, r):
    if l >= r:
        return 0
    return solve(rightmost[l], r) + 1


n = int(input())
xxx = list(map(int, input().split()))
l = int(input())

rightmost = []
for x in xxx:
    rightmost.append(bisect_right(xxx, x + l) - 1)

buf = []
q = int(input())
for line in sys.stdin:
    a, b = map(int, line.split())
    a -= 1
    b -= 1
    if a > b:
        a, b = b, a
    buf.append(solve(a, b))
print('\n'.join(map(str, buf)))

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left, bisect_right
from functools import lru_cache


@lru_cache(maxsize=None)
def solve(l, r):
    if l >= r:
        return 0
    return solve(rightmost[l], r) + 1


n = int(input())
xxx = list(map(int, input().split()))
l = int(input())

rightmost = []
for x in xxx:
    rightmost.append(bisect_right(xxx, x + l) - 1)

buf = []
q = int(input())
for line in sys.stdin:
    a, b = map(int, line.split())
    a -= 1
    b -= 1
    if a > b:
        a, b = b, a
    buf.append(solve(a, b))
print('\n'.join(map(str, buf)))

Submission status: Runtime Error

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] = SR()
    return l
mod = 1000000007

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = I()
    x = LI()
    l = I()
    k = int(math.log(n,2))
    f = [[i for j in range(k+1)] for i in range(n)]
    for i in range(n-1):
        j = bisect.bisect_left(x,x[i]+l)
        if j < n:
            if x[j] > x[i]+l:
                f[i][0] = j-1
            else:
                f[i][0] = j
        else:
            f[i][0] = j-1
    po2 = [1]*(k+1)
    for i in range(k):
        po2[i+1] = po2[i]*2
    for j in range(k):
        for i in range(n):
            f[i][j+1] = f[f[i][j]][j]
    q = I()
    for i in range(q):
        a,b = LI()
        a,b = [min(a,b)-1, max(a,b)-1]
        ans = 0
        while a < b:
            i = bisect.bisect_left(f[a],b)
            ans += po2[i]
            if f[a][i] == b:
                break
            a = f[a][i-1]
        print(ans)

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

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

Submission status: Runtime Error

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] = SR()
    return l
mod = 1000000007

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = I()
    x = LI()
    l = I()
    k = int(math.log(n,2))
    f = [[i for j in range(k+1)] for i in range(n)]
    for i in range(n-1):
        j = bisect.bisect_left(x,x[i]+l)
        if j < n:
            if x[j] > x[i]+l:
                f[i][0] = j-1
            else:
                f[i][0] = j
        else:
            f[i][0] = j-1
    po2 = [1]*(k+1)
    for i in range(k):
        po2[i+1] = po2[i]*2
    for j in range(k):
        for i in range(n):
            f[i][j+1] = f[f[i][j]][j]
    q = I()
    for i in range(q):
        a,b = LI()
        a,b = [min(a,b)-1, max(a,b)-1]
        ans = 0
        while 1:
            i = bisect.bisect_left(f[a],b)
            if f[f[a][i-1]][0] < b < f[a][i] or f[a][i] == b:
                ans += po2[i]
                break
            ans += po2[i-1]
            a = f[a][i-1]
        print(ans)

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

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

Submission status: Runtime Error

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] = SR()
    return l
mod = 1000000007

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = I()
    x = LI()
    l = I()
    k = int(math.log(n,2))
    f = [[i for j in range(k+1)] for i in range(n)]
    for i in range(n-1):
        j = bisect.bisect_left(x,x[i]+l)
        if j < n:
            if x[j] > x[i]+l:
                f[i][0] = j-1
            else:
                f[i][0] = j
        else:
            f[i][0] = j-1
    po2 = [1]*(k+1)
    for i in range(k):
        po2[i+1] = po2[i]*2
    for j in range(k):
        for i in range(n):
            f[i][j+1] = f[f[i][j]][j]
    q = I()
    for i in range(q):
        a,b = LI()
        a,b = [min(a,b)-1, max(a,b)-1]
        ans = 0
        while 1:
            i = bisect.bisect_left(f[a],b)
            if f[a][i] == b:
                ans += po2[i]
                break
            ans += po2[i-1]
            a = f[a][i-1]
        print(ans)

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

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

Submission status: Runtime Error

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] = SR()
    return l
mod = 1000000007

#A
def A():
    return

#B
def B():
    return

#C
def C():
    n = I()
    x = LI()
    l = I()
    k = int(math.log(n,2))
    f = [[i for j in range(k+1)] for i in range(n)]
    for i in range(n-1):
        j = bisect.bisect_left(x,x[i]+l)
        if j < n:
            if x[j] > x[i]+l:
                f[i][0] = j-1
            else:
                f[i][0] = j
        else:
            f[i][0] = j-1
    po2 = [1]*(k+1)
    for i in range(k):
        po2[i+1] = po2[i]*2
    for j in range(1,k+1):
        for i in range(n):
            f[i][j] = f[f[i][j-1]][j-1]
    q = I()
    for i in range(q):
        a,b = LI()
        a,b = [min(a,b)-1, max(a,b)-1]
        i = 0
        while x[f[a][i]] < x[b]:
            i += 1
        if x[f[a][i]] == x[b]:
            print(po2[i])
        else:
            ans = po2[i]
            s = f[f[a][i-1]][0]
            g = f[b][0]
            while s < g:
                s = f[s][0]
                ans += 1
            print(ans)

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

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

Submission status: Runtime Error

Solution code:
from bisect import bisect, bisect_left
import sys

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

def search_1(start):
	return bisect(x, x[start] + l) - 1

route = [[] for _ in range(n)]

i = 0 # 親の位置
for i in range(n - 1):
	if route[i] == []:
		j = search_1(i) # カーソルの位置
		num = 1 # 何日目の場所か
		route[i].append(j)
		if route[j] == []:
			route[j] = (i, num)
		else: # 既に他の親が通っている
			route[i] += route[route[j][0]][route[j][1]:]
			continue
		while j < n - 1:
			j = search_1(j)
			num += 1
			route[i].append(j)
			if route[j] == []:
				route[j] = (i, num)
			else: # 既に他の親が通っている
				route[i] += route[route[j][0]][route[j][1]:]
				break
	else:
		continue

# print(route)

def search_2(start, goal):
	if type(route[start]) == type([]):
		return bisect_left(route[start], goal) + 1
	else:
		return bisect_left(route[route[start][0]][route[start][1]:], goal) + 1



q = int(input())
for _ in range(q):
	a, b = map(int, sys.stdin.redline().strip().split())
	if a > b:
		a, b = b, a
	print(search_2(a - 1, b - 1))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect
N=int(input())
X=[int(i) for i in input().split()]
L=int(input())
Q=int(input())
#T=[[int(i) for i in input().split()] for i in range(Q)]
T=[]
for i in range(Q):
    a,b=map(int,input().split())
    if a>b:
        a,b=b,a
    T.append((a-1,b-1))
F=[0]*N
for i in range(N):
    F[i]= bisect(X, X[i] + L) -1
#print(F)
dp=[ [N-1] * (N) for i in range(17)]

for i in range(N):
    #dp[0][i]=i
    dp[0][i]=F[i]
for c in range(1,17):
    for i in range(N):
        dp[c][i] = dp[c-1][ dp[c-1][i] ]
#print(dp)

def f(a,b):
    num=0
    t = a
    while True:
        for i in range(17):
            if dp[i][t]>=b:
                s=i
                break
        if s==0:
            num+=1
            break
        num += pow(2, s - 1)
        t = dp[s-1][t]
    print(num)
for a,b in T:
    f(a,b)