Editorial for DMPG '16 G5 - Continuation Passing
Submitting an official solution before solving the problem yourself is a bannable offence.
If we examine the adjacency matrix of the graph given, along with how the state of the graph changes after this matrix is applied some number of times, we notice that the adjacency matrix can first be multiplied by itself some number of times before it is applied to the state of the graph for the same result. After multiplying the matrix by itself some number of times for each query, apply it to the initial state of the graph where node has a source of in the first row, and there is way to travel there. To apply a matrix, relax all existing edges.
Fast matrix exponentiation on the adjacency matrix, where coordinate of the matrix represents the number of ways to move to , starting from , yields an solution. This is still inadequate for the time limit, so notice that it only takes time to apply a matrix. By precomputing all matrices which are the adjacency matrix raised to some power of 2 (up to ), several matrices can be applied per query in time each, and each query can be answered using matrix applications.
The final time complexity is .
It should also be noted that, very occasionally, a matrix result will be non-zero and be divisible by . This could cause an incorrect answer when applying the matrix to the state of the graph, which can be prevented by maintaining a boolean matrix in parallel with the adjacency matrix to represent which nodes can reach which other nodes. Since this collision usually requires the matrix to be raised to a relatively high exponent, there is another small chance that this will affect the answer. However, with such a large modulo value, such cases are rare and absent in the test data.
Comments