luogu#P3762. [TJOI2017] 龙舟

[TJOI2017] 龙舟

Background

Description

Jialidun University has a dragon boat club with nn teams, each consisting of mm paddlers. Dragon boat racing is a team sport, and while it depends on each individual’s ability, coordination is crucial. Therefore, the ability of a team is evaluated by the value $C=\frac{b_1 \times b_2 \times \cdots \times b_m}{a_1 \times a_2 \times \cdots \times a_m}$, where bib_i is the standard ability value for position ii, and aia_i is the ability value of the paddler in position ii in the team. After cancellation, we obtain C=BAC=\frac{B}{A} with gcd(B,A)=1\gcd(B,A)=1, i.e., AA and BB are coprime.

However, due to varying conditions at the venue, we consider that under pressure MM, the team’s final performance is C1modMC^{-1} \bmod M. We define that under modulo MM, 1x=y\frac{1}{x}=y, where yy satisfies xy1(modM)xy \equiv 1\pmod M and 0y<M0 \le y < M. If no such yy exists, we say the team will underperform under pressure MM (that is, yy is the modular inverse of xx modulo MM; if the inverse does not exist, the team underperforms). Given this season’s schedule, the coaching staff wants to know each team’s performance in the matches.

Output Format

Output kk lines. For the ii-th scheduled match, output the team’s on-site performance value C1modMC^{-1} \bmod M. If the team underperforms (i.e., the inverse does not exist), output -1.

2 3 3
5 2 3
3 2 3
2 3 2
1 4
2 4
1 7
3
-1
4

Hint

For 20%20\% of the testdata, 1<M,ai,bi<1081<M,a_i,b_i<10^8, m100m \le 100.

For 100%100\% of the testdata, 1<M,ai,bi<2×10181<M,a_i,b_i<2 \times 10^{18}, m10000m \le 10000, n20n \le 20, k50k \le 50.

Translated by ChatGPT 5