Line Friends (Small)

Given N line segments, build a graph where segments are adjacent when they overlap, then answer shortest-path queries between pairs of segments.

Medium5GraphBFSGeometryArrayInterviewNo attempts yetTime limit2sMemory limit256 MB

Problem

NN segments lie on a number line. Two segments can talk to each other only when they overlap, and two segments that can talk become friends. Touching at a single endpoint counts as an overlap.

The figure labels the segments in Korean. Brown (브라운) and Cony (코니) are friends, and Moon (문) and James (제임스) are friends, but Brown and Sally (샐리) are not.

The segments want to know how close they are to each other. Moon and Leonard (레너드) are not friends, but James is a friend of both of them, 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 direct friends counts as a closeness of 1, then Moon and Leonard are 2 close and Brown and Sally are 4 close. Moon is a friend of a friend of Cony and is also a friend of Cony, so Moon and Cony are 1 close. The closeness of two segments is the smallest number of friendships that connects them.

You are the mayor of the segment village, so you have to answer at once whenever two segments ask "how close are we?". Write a program that does this work for you.

Input

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

Each of the next NN lines contains the left endpoint LiL_i and the right endpoint RiR_i of segment ii, for ii from 1 to NN. (1000000LiRi1000000-1000000 \le L_i \le R_i \le 1000000)

The next line contains the number of questions QQ. (1Q3001 \le Q \le 300)

Each of the next QQ lines contains the numbers AA and BB of the two segments that are asking. (1A,BN1 \le A, B \le N, ABA \ne B)

Output

For each question, print the closeness of the two segments on its own line. If the two segments are not connected by friendships, print -1.