Brothers in Arms
시간 제한10초메모리 제한1024 MB
도시들이 문장의 위쪽이나 아래쪽 심볼을 공유하면 연결된다고 할 때, 각 질의에서 두 도시 사이 최단 거리를 구한다.
문제
In medieval times, keeping track of the 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 with each other by examining their coats of arms. In those days, 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 they have an equal symbol at the bottom, they are friendly.
Following the saying "the friends of my friends are my friends", two cities and can be indirectly friendly if there exist cities such that is friendly with for . If and are different and indirectly friendly, then we say that 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 and are directly friendly, as well as cities and . Cities and have a friendship degree of , because they are indirectly friendly via city . City 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.
입력
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 of the coat of arms of the th city. 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.
출력
For every query, output an integer stating the friendship degree of the two cities, or if the two cities are not (indirectly) friendly.