Theorem. Let be the adjacency matrix of the graph. Then the element A^t[i][j] equals the number of paths of length (that is, consisting of edges; vertices and edges may repeat) leading from vertex to vertex .
A cycle of length in the sense of the problem statement is a sequence of vertices v_1, v_2, \ldots, v_t with edges v_1 \to v_2 \to \ldots \to v_t \to v_1. In other words, it is a closed path of edges starting at vertex v_1. Sequences are compared as a whole, so cyclic shifts of the same cycle (for example, and ) are considered different cycles. The number of closed paths of length starting at vertex equals A^t[i][i], and the number of all cycles of length equals the trace of the matrix (the sum of its diagonal elements):
Therefore, the required number of cycles of length less than equals
Iterating over the lengths one by one is not feasible: for k = 10^6 and n = 35 this takes about k \cdot n^3 \approx 4 \cdot 10^{10} operations. The sum of matrix powers must be computed with O(\log k) multiplications.
Block matrix. Construct a matrix of size 2n \times 2n composed of four blocks of size n \times n: the upper left block is , the upper right and lower right blocks are the identity matrix , and the lower left block is zero.
Block matrix multiplication. Block matrices are multiplied by the same "row by column" rule as ordinary matrices, except that blocks (submatrices) stand in place of numbers. The block of the result located in the -th block row and the -th block column equals the sum of the products of the blocks of the -th row of the left matrix and the corresponding blocks of the -th column of the right matrix:
For a 2 \times 2 block partition it looks as follows (the blocks that produce C_{11} are highlighted):
The rule applies if the partition of the columns of the left matrix coincides with the partition of the rows of the right one: then every product A_{is} \cdot B_{sj} is defined. In our case all blocks have the same size n \times n, so this condition holds. The order of the factors in each product must not be changed, since matrix multiplication is not commutative.
Let us prove by induction that the upper right block of the matrix B^p equals S_p = I + A + \ldots + A^{p-1}, the upper left block equals A^p, and the lower block row does not change. For p = 1 this holds: S_1 = I. Multiply B^p by using the block multiplication rule. For example, the upper right block of B^{p+1} is obtained by multiplying the upper block row of B^p (A^p, S_p) by the right block column of (I, I):
Multiplication by a zero block gives a zero block, and multiplication by does not change a matrix. Therefore B^{p+1} has the same form: the upper left block equals A^{p+1}, the upper right one equals A^p + S_p = S_{p+1}, and the lower block row is .
Thus, the upper right block of the matrix B^k equals I + A + A^2 + \ldots + A^{k-1}. Its trace differs from the answer only by the term \mathit{tr}(I) = n: by the problem statement a cycle is non-empty, while A^0 = I corresponds to paths of length . Therefore
The matrix B^k is computed by fast exponentiation; all operations are performed modulo .
Complexity. The size of the matrix is 2n \le 70, and one multiplication takes (2n)^3 \approx 3.4 \cdot 10^5 operations. Exponentiation requires at most 2 \cdot \log_2 k \approx 40 multiplications, giving O(n^3 \log k) in total.
Overflow. All matrix elements are stored modulo m < 2^{30}, so the product of two elements is less than 10^{18}, and together with the added remainder it is less than 1.8 \cdot 10^{19}. This fits into the unsigned long long type if the remainder is taken after each term.
Example
The graph contains the edges 1 \to 2, 1 \to 4, 2 \to 3, 3 \to 1, 4 \to 1, that is, two simple cycles passing through vertex .
We need to find the number of cycles of length less than k = 6, that is, of lengths from to . Let us list all such cycles. A cycle of length is obtained by traversing the cycle 1 \to 4 \to 1 twice, and a cycle of length is a combination of cycles of lengths and . Each cycle of length is written from all starting vertices, so the number of cycles coincides with the trace of the matrix A^t.
The program obtains the same sum differently. The upper right block of the matrix B^6 equals I + A + A^2 + \ldots + A^5, its diagonal is (6, 3, 3, 4), and its trace is . Subtracting \mathit{tr}(I) = 4, we get the answer 16 - 4 = 12.
Algorithm Implementation
Declare the types: ull is an unsigned -bit integer, Mat is a square matrix. The modulus is stored in the global variable , and the size of the matrices in .
typedef unsigned long long ull;
typedef vector<vector<ull>> Mat;
ull MOD;
int SZ;The function mul multiplies matrices and of size \mathit{SZ} \times \mathit{SZ} modulo . The loop order — — makes it possible to skip zero elements : the matrix is sparse, especially at the first steps. The value x \cdot b[t][j] is less than 10^{18}, so its sum with does not overflow ull.
Mat mul(const Mat &a, const Mat &b)
{
Mat c(SZ, vector<ull>(SZ, 0));
for (int i = 0; i < SZ; i++)
for (int t = 0; t < SZ; t++)
{
ull x = a[i][t];
if (!x) continue;
for (int j = 0; j < SZ; j++)
c[i][j] = (c[i][j] + x * b[t][j]) % MOD;
}
return c;
}The main part of the program. Read the input data. The size of the block matrix is \mathit{SZ} = 2n.
cin >> n >> k >> MOD;
SZ = 2 * n;Construct the matrix B = [[A, I], [0, I]]. Fill the upper left block from the adjacency matrix, and put ones on the diagonals of the upper right and lower right blocks.
// B = [[A, I], [0, I]]
Mat B(SZ, vector<ull>(SZ, 0));
for (int i = 0; i < n; i++)
{
string s;
cin >> s;
for (int j = 0; j < n; j++)
if (s[j] == 'Y') B[i][j] = 1;
B[i][n + i] = 1;
B[n + i][n + i] = 1;
}Compute R = B^k by fast exponentiation. The initial value of is the identity matrix.
Mat R(SZ, vector<ull>(SZ, 0));
for (int i = 0; i < SZ; i++) R[i][i] = 1;
long long p = k;
while (p > 0)
{
if (p & 1) R = mul(R, B);
B = mul(B, B);
p >>= 1;
}The upper right block of the matrix equals I + A + \ldots + A^{k-1}. Compute its trace: the elements R[i][n + i] for 0 \le i < n.
// upper right block R = I + A + ... + A^(k-1)
ull tr = 0;
for (int i = 0; i < n; i++)
tr = (tr + R[i][n + i]) % MOD;Subtract \mathit{tr}(A^0) = n: cycles of length are not counted. The term is added so that the difference does not become negative. Print the answer.
ull ans = (tr + MOD - (ull)n % MOD) % MOD; // subtract tr(A^0) = n
cout << ans << endl;