Algorithm summary madman (v) matrix multiplication (matrix fast power)

The first learned know from linear algebra matrix multiplication, matrix multiplication condition for the number of rows and columns of the second matrix like a matrix, the first matrix multiplication is multiplied by the second row of the first matrix corresponding elements of the first row and column elements of the first column of the matrix as a result. (See Detailed linear algebra)
so we can write the code matrix multiplication correctional

struct JZ{  int m[maxn][maxn];   };
JZ muti(JZ a,JZ b)
{
    JZ temp;
    memset(temp.m,0,sizeof(temp.m));
    for(int i=0;i<maxn;i++)
        for(int j=0;j<maxn;j++){
            for(int k=0;k<maxn;k++)
            {
                temp.m[i][j]+=a.m[i][k]*b.m[k][j];
            }
            temp.m[i][j];
        }
    return temp;
}

For the square we can own ride their own, it is the exponentiation operation.
We refer to the Quick power, will replace digital multiplication matrix multiplication can be drawn quickly power matrix code;

#include<bits/stdc++.h>
using namespace std;
const int MOD=1e8+5;
const int maxn=2; //定义方阵的阶数
struct JZ{  int m[maxn][maxn];   };//定义maxn阶方阵
JZ muti(JZ a,JZ b,int mod);
JZ quick_mod(JZ a,int k,int mod);
int main()
{
    JZ demo;
    JZ ans;
    int n;
    for(int i=0;i<maxn;i++)
    for(int j=0;j<maxn;j++) cin>>demo.m[i][j];
    while(cin>>n){
    ans=quick_mod(demo,n,MOD);
    for(int i=0;i<maxn;i++){
        for(int j=0;j<maxn;j++)
        cout<<ans.m[i][j]<<' ';
        cout<<endl;}
    }
}
JZ muti(JZ a,JZ b,int mod)
{
    JZ temp;
    memset(temp.m,0,sizeof(temp.m));
    for(int i=0;i<maxn;i++)
        for(int j=0;j<maxn;j++){
            for(int k=0;k<maxn;k++)
            {
                temp.m[i][j]+=(long long) a.m[i][k]*b.m[k][j]%mod;
            }
            temp.m[i][j]%=mod;
        }
    return temp;
}
JZ quick_mod(JZ a,int k,int mod)
{
    JZ ans;
    for(int i=0;i<maxn;i++)
        for(int j=0;j<maxn;j++)
            ans.m[i][j]=(i==j);
    while(k)  {
    if(k &1)  ans =muti(ans,a,mod);
    a = muti(a,a,mod);
    k >>=1;
    }
    return ans;
}

Applications: Matrix rapid power demand Fibonacci number.
We define a matrix A
| 0 1 |
| 1 1 |
define F (0) = 0, F (1) = 1.
A matrix configuration matrix F | 0. 1 |
N-th power of the A matrix, F is multiplied by the first matrix is the N-th Fibonacci Fibonacci series.
Demonstrate:
F. A matrix by the right matrix element to be representative of left, right, left plus right element is equal. Matrix multiplication is associative, so F X- X- ...... ...... N X-= F (X- X- X-...... X-)
so that different definitions can be different matrix F Fibonacci number.

Guess you like

Origin www.cnblogs.com/lunatic-talent/p/11306478.html