Segment Friends (Large)

Given N segments on a line, build the intersection graph and answer Q shortest-path queries between segment pairs, or report -1.

Hard8GraphBFSSortingPrefix sumNo attempts yetTime limit2sMemory limit256 MB

Problem

There are NN segments living on a number line. Two segments can talk only when they share at least one point, so exactly those pairs became friends. Touching at a single endpoint counts as sharing a point.

In the figure above, Brown and Cony became friends and Moon and James became friends, but Brown and Sally did not.

The segments now want to know how close they are to each other. Moon and Leonard are not friends, but James is a friend of both Moon and Leonard, so Moon is a friend of a friend of Leonard. In the same way, Brown is a friend of a friend of a friend of a friend of Sally. If being friends means a closeness of 1, then Moon and Leonard are 2 close and Brown and Sally are 4 close. Moon is also a friend of a friend of Cony, but Moon is a friend of Cony as well, so Moon and Cony are 1 close.

You are the mayor of the segment town, and whenever two segments ask "how close are we?" you have to answer right away. For the two segments AA and BB given in a query, compute the smallest number of friendships you have to follow to get from AA to BB.

Input

The first line contains the number of segments NN. (2N1500002 \le N \le 150000)

Each of the next NN lines contains the left endpoint LiL_i and the right endpoint RiR_i of segment ii, for segments 1 through NN, separated by a space. (1000000LiRi1000000-1000000 \le L_i \le R_i \le 1000000)

The next line contains the number of queries QQ. (1Q1500001 \le Q \le 150000)

Each of the last QQ lines contains two segment numbers AA and BB. (1A,BN1 \le A, B \le N, ABA \ne B)

Output

For each query, print on its own line how close the two segments are. If the two segments are not connected by any chain of friendships, print -1.