Segment Friends (Large)
Time limit2sMemory limit256 MB
Given N segments on a line, build the intersection graph and answer Q shortest-path queries between segment pairs, or report -1.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Sorting, Prefix sum
- Solved
- No attempts yet
Problem
There are 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 and given in a query, compute the smallest number of friendships you have to follow to get from to .
Input
The first line contains the number of segments . ()
Each of the next lines contains the left endpoint and the right endpoint of segment , for segments 1 through , separated by a space. ()
The next line contains the number of queries . ()
Each of the last lines contains two segment numbers and . (, )
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.