#P9361. Contestant Strength Comparison
Contestant Strength Comparison
Contestant Strength Comparison
There are \(n\) contestants and they participate in \(m\) contests. For each contest, you are given a ranklist which is a permutation \(a_k\) where \(a_{k,i}\) is the contestant whose rank is \(i\) in the \(k\)-th contest.
SolarPea and PolarSea are two of the \(n\) contestants. SolarPea wants to prove that he is stronger than PolarSea.
We say contestant \(x\) is \(l\)-stronger than contestant \(y\) if and only if there exists a sequence \(b_1, b_2, \dots, b_{l+1}\) such that \(b_1=x\), \(b_{l+1}=y\), and for every \(1 \le i \le l\) there exists at least one contest \(k\) where the rank of \(b_i\) is less than the rank of \(b_{i+1}\) (i.e. \(b_i\) performs better than \(b_{i+1}\) in that contest).
There are \(q\) queries. In the \(i\)-th query, SolarPea is contestant \(x\) and PolarSea is contestant \(y\). Your task is to determine the minimum positive integer \(l\) so that SolarPea is \(l\)-stronger than PolarSea. If no such sequence exists, output \(-1\).
Note: A contestant having a smaller rank means he performed better in that contest.
inputFormat
The first line contains two integers \(n\) and \(m\) \((1 \le n, m \le \text{constraints})\) representing the number of contestants and contests respectively.
Then \(m\) lines follow, each line containing \(n\) distinct integers, a permutation of \(1, 2, \dots, n\), representing the ranklist for that contest. In the \(k\)-th line, the \(i\)-th number denotes that the contestant with that number got rank \(i\) in the \(k\)-th contest.
The next line contains a single integer \(q\) \((1 \le q \le \text{constraints})\) representing the number of queries.
Each of the following \(q\) lines contains two integers \(x\) and \(y\), indicating that in the query SolarPea is contestant \(x\) and PolarSea is contestant \(y\).
outputFormat
For each query, output a single line containing the minimum positive integer \(l\) such that SolarPea is \(l\)-stronger than PolarSea. If no such sequence exists, output \(-1\).
sample
5 2
1 2 3 4 5
5 4 3 2 1
3
1 5
2 4
3 1
1
1
1
</p>