POJ 3233 Matrix Power Series(矩阵快速幂)

Description

Given a n × n matrix A and a positive integer k, find the sum

S=A+A2+A3++Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

Output

Output the elements of S modulo m in the same way as A is given.

Sample Input

2 2 4
0 1
1 1

Sample Output

1 2
2 3
思路:当k=6时可以将S化解成如下等式进行二分求解

S=A+A2+A3+A3A+A2+A3

#include 
#include 
using namespace std;
const int MAX_N=35;
int inf=99999999;
typedef int Matrix[MAX_N][MAX_N];
int n,m;
Matrix A;
void MATRIX_MUL(const Matrix p,const Matrix q,Matrix aim)//矩阵乘法
{
    for(int i=0;ifor (int j=0;j0;
            for (int k=0;kvoid MATRIX_PLU(const Matrix p,const Matrix q,Matrix aim)//矩阵加法
{
    for(int i=0;ifor (int j=0;jvoid MATRIX_POW(int k,Matrix aim)//求解矩阵快速幂,将结果保存在aim里
{
    if(k==1)
    {
        for (int i=0;ifor (int j=0;jelse
    {
        if(k%2==1)
        {
            Matrix l,r;
            MATRIX_POW(k/2,l);
            MATRIX_MUL(l,l,r);
            MATRIX_MUL(r,A,aim);
        }
        else
        {
            Matrix a;
            MATRIX_POW(k/2,a);
            MATRIX_MUL(a,a,aim);
        }
    }
}
void solve(int k,Matrix aim)//求解一个值为k的矩阵和式,将结果保存在aim里
{
    if(k==1)
    {
        for (int i=0;ifor (int j=0;jelse
    {
        if(k%2==1)
        {
            Matrix a1,a2,a3,ak;
            solve(k/2,a1);
            MATRIX_POW(k/2,a3);
            MATRIX_MUL(a3,A,ak);
            MATRIX_PLU(a1,ak,a2);
            MATRIX_MUL(a2,a3,ak);
            MATRIX_PLU(a1,ak,aim);
        }
        else
        {
            Matrix a1,a2,ap;
            solve(k/2,a1);
            MATRIX_POW(k/2,ap);
            MATRIX_MUL(a1,ap,a2);
            MATRIX_PLU(a1,a2,aim);
        }
    }
}
int main()
{
    freopen("test.txt","r",stdin);
    int k;
    scanf("%d%d%d",&n,&k,&m);
    for (int i=0;ifor (int j=0;jscanf("%d",&A[i][j]);
            A[i][j]%=m;
        }
    }
    Matrix ans;
    solve(k,ans);
    for (int i=0;ifor (int j=0;jprintf("%d ",ans[i][j]);
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(矩阵)