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 MBN 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.
The first line contains the number of segments N. (2≤N≤300)
Each of the next N lines contains the left endpoint Li and the right endpoint Ri of segment i, for i from 1 to N. (−1000000≤Li≤Ri≤1000000)
The next line contains the number of questions Q. (1≤Q≤300)
Each of the next Q lines contains the numbers A and B of the two segments that are asking. (1≤A,B≤N, A=B)
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.