Solution of P10502 Matrix Power Series

· · 题解

你可以浏览这个题解的中文版本。

Consider the partition.

According to the matrix multiplication distributive law, if we have already computed A+A^2+\cdots+A^p, we can multiply it by A^{q}, thus obtaining A^{q+1}+A^{q+2}+\cdots+A^{q+p} within the complexity of \mathcal{O}(n^3\log k).

This enlightens us to refer to the chunking idea, where the sum sought is divided into a number of intervals of equal length, and a number of loose chunks. The whole block recursively computes the next level of the answer and multiplies by the coefficients just fine, and the loose blocks are computed violently.

Let there be x chunks, and the partition computes \mathcal{O}(\log_x k) layers, with a complexity of \mathcal{O}(x\cdot n^3\log k) for computing each layer, and \mathcal{O}(x\log_x k\cdot n^3\log k) for total complexity.

Take k=10^{18} and examine the function f(x)=x\log_x k, which is minimized when x is about 2.7, so x=3 is optimal. Complexity \mathcal{O}(\log_3 k\cdot n^3\log k) with three times as many constants. Should be the theoretical optimal solution.

Martix solve(int r) {
    if(r == 1) return a;
    if(r == 2) return a + a * a;
    auto p = solve(r / 3);
    if(r % 3 == 1) return p + pow(a, r / 3) * p + pow(a, r / 3 * 2) * p + pow(a, r);
    else if(r % 3 == 2) return p + pow(a, r / 3) * p + pow(a, r / 3 * 2) * p + pow(a, r) + pow(a, r - 1);
    else return p + pow(a, r / 3) * p + pow(a, r / 3 * 2) * p;
}