Brothers in Arms
InterviewTime limit10sMemory limit1024 MB
Each city is an edge between its top and bottom symbols. For each query, find the shortest friendship chain length between two cities, or -1 if none exists.
- Level
Medium5 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
In medieval times, keeping track of relationships between cities was extremely difficult, since most cities did not have access to the internet[citation needed]. However, it was possible to determine whether two cities were friendly by examining their coats of arms. Every coat of arms showed two symbols: one at the top and one at the bottom. If two cities have an equal symbol at the top, or an equal symbol at the bottom, they are friendly.
Following the saying "the friends of my friends are my friends", two cities and are indirectly friendly if there exist cities such that is friendly with for . If and are different and indirectly friendly, then the friendship degree of these cities is the smallest possible following this definition. See Figure B.1 for an example.

Parts of these coats of arms are CC BY-SA 4.0 on Wikimedia Commons.
Figure B.1: Illustration of Sample Input 1. Cities 1 and 2 are directly friendly, as are cities 2 and 3. Cities 1 and 3 have a friendship degree of 2, because they are indirectly friendly via city 2. City 4 is not (indirectly) friendly with any other city.
You are given a list of coats of arms and a list of queries. For every query, determine the friendship degree of the two given cities.
Input
The input consists of:
One line with two integers and (, ), the number of cities and the number of symbols that may appear on the coat of arms of some city.
lines, the th of which consists of two integers and (). is the symbol on the top side of the coat of arms of the th city, and is the symbol on the bottom side. If , then or .
One line with an integer (), the number of queries.
lines, the th of which contains two integers and (, ), two cities for which you should calculate the friendship degree.
Output
For every query, output an integer stating the friendship degree of the two cities, or if the two cities are not (indirectly) friendly.