#P8989. [北大集训 2021] 随机游走

[北大集训 2021] 随机游走

Background

CTT2021 D2T3.

Problem Description

Given a directed graph with nn vertices labeled 1,2,,n1,2,\dots,n. Initially, for all i{1,2,,n1}\forall i\in\{1,2,\dots,n-1\}, there is a directed edge from ii to i+1i+1.

You may add mm more directed edges (any start and end vertices are allowed). Multiple edges and self-loops are allowed.

Player A starts from vertex 11 and moves as a random walk until reaching vertex nn. You want to maximize the expected number of steps for Player A to move from 11 to nn.

A random walk is defined as follows: suppose Player A is currently at vertex xx, and xx has dd outgoing edges. Then Player A chooses one of these dd outgoing edges uniformly at random and moves along it.

Input Format

The first line contains a positive integer TT, the number of test cases. It is guaranteed that T105T \le 10^5.

The next TT lines each contain three integers n,m,pn,m,p, representing the number of vertices in the directed graph, the number of edges you add, and the modulus for the answer. It is guaranteed that 1n1091 \leq n \leq 10^9, 0m10180 \leq m \leq 10^{18}, 2p109+72\leq p\leq 10^9+7, and pp is a prime.

Output Format

Output TT lines. The ii-th line contains an integer ansans, meaning the maximum expected number of steps in the ii-th test case modulo pp.

(It can be proven that the answer is a rational number. Suppose its simplest form is ab\frac{a}{b}. Then you need to output an ansans such that ansbmodp=aans \cdot b \bmod p = a. It is guaranteed that such an ansans exists.)

4
3 2 97
10 25 233
6 12345 2333
1000000000 1000000000000000000 1000000007 

6
131
1206
161905971

Hint

Test Package ID nn\le mm\le TT\le Special Property Score
11 55 55 1010 None 1010
22 10210^2
33 10810^8 10210^2 2020
44 5050 3,0003,000 33
55 10910^9 10910^9 10510^5 m<n1m<n-1 1010
66 101810^{18} None 3030

Translated by ChatGPT 5