码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-31 15:31:42      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   for   sp   

 

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

 

bubuko.com,布布扣

 

 

 

bubuko.com,布布扣
#include <cstdio>
#include <cstring>
#define CLR( a, b ) memset( a, b, sizeof(a) )
#define MOD 10
#define MAX_SIZE 40
struct 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 ( 矩阵快速幂 )

标签:style   blog   http   io   color   os   ar   for   sp   

原文地址:http://www.cnblogs.com/BigBallon/p/4064983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!