首页 > 代码库 > Uva 11149 - Power of Matrix ( 矩阵快速幂 )

Uva 11149 - Power of Matrix ( 矩阵快速幂 )

 

Uva 11149 - Power of Matrix  ( 矩阵快速幂 )

 

 

 

 

#include <cstdio>#include <cstring>#define CLR( a, b ) memset( a, b, sizeof(a) )#define MOD 10#define MAX_SIZE 40struct Mat{    int r, c;    int mat[MAX_SIZE][MAX_SIZE];        Mat( int _r = 0 , int _c = 0 )    {        CLR( mat, 0 );        r = _r, c = _c;    }    void init()    {        for( int i = 0; i < r; ++i )            for( int j = 0; j < c; ++j )                mat[i][j] = ( i == j );    }    Mat operator + ( const Mat &b ) const    {        Mat t( r, c );        for( int i = 0; i < r; ++i )            for( int j = 0; j < c; ++j )                t.mat[i][j] = ( mat[i][j] + b.mat[i][j] ) % MOD;        return t;    }    Mat operator * ( const Mat &b ) const    {        Mat t( r, b.c );        for( int k = 0; k < c; ++k )            for( int i = 0; i < r; ++i ) if( mat[i][k] )                for( int j = 0; j < b.c; ++j )                    t.mat[i][j] = ( t.mat[i][j] + mat[i][k] * b.mat[k][j] ) % MOD;        return t;                    }    void debug()    {        for( int i = 0; i < r; ++i )        {            for( int j = 0; j < c; ++j )            {                if( j !=0 )    putchar(   );                printf( "%d", mat[i][j] );            }            putchar( \n );        }    }};Mat fast_mod( Mat a, int b ){    Mat c( a.r, a.c );    c.init();    while( b )    {        if( b & 1 ) c = c * a;        a = a * a;        b >>= 1;    }    return c;}Mat solve( Mat a, int b ){    if( b == 1 )        return a;    Mat in( a.r, a.c );    in.init();    if( b == 0 )        return in;    if( b & 1 )        return solve( a, b/2 ) * ( in + fast_mod( a, b/2 ) ) + fast_mod( a, b );    else        return solve( a, b/2 ) * ( in + fast_mod( a, b/2 ) );}void Orz(){    int n, k, x;    int cas = 0;    while( ~scanf( "%d %d", &n, &k ) && n )    {        Mat t( n, n );        for( int i = 0; i < n; ++i )        {            for( int j = 0; j < n; ++j )            {                scanf( "%d", &x );                t.mat[i][j] = x % MOD;            }        }        t = solve( t, k );        t.debug();        putchar( \n );    }}int main(){    Orz();    return 0;}
代码君

 

Uva 11149 - Power of Matrix ( 矩阵快速幂 )