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 c_0c\_0 and c_fc\_f can be indirectly friendly if there exist cities c_1,,c_f1c\_1, \ldots, c\_{f-1} such that c_kc\_k is friendly with c_k+1c\_{k+1} for 0k<f0\leq k < f. If c_0c\_0 and c_fc\_f are different and indirectly friendly, then we say that the friendship degree of these cities is the smallest possible ff 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 11 and 22 are directly friendly, as well as cities 22 and 33. Cities 11 and 33 have a friendship degree of 22, because they are indirectly friendly via city 22. City 44 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 nn and ss (2n90,0002\leq n\leq 90\\,000, 2s3002\leq s\leq 300), the number of cities and the number of symbols that may appear on the coat of arms of some city.
  • nn lines, the iith of which consists of two integers t_it\_i and b_ib\_i (1t_i,b_is1\leq t\_i, b\_i\leq s). t_it\_i is the symbol on the top side of the coat of arms of the iith city, and b_ib\_i is the symbol on the bottom side of the coat of arms of the iith city. If iji\neq j, then t_it_jt\_i\neq t\_j or b_ib_jb\_i\neq b\_j.
  • One line with an integer qq (1q1051\leq q\leq 10^5), the number of queries.
  • qq lines, the iith of which contains two integers cc and dd (1c,dn1\leq c, d\leq n, cdc\neq d), 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 1-1 if the two cities are not (indirectly) friendly.