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

Uva10689 Yet another Number Sequence ( 矩阵快速幂 )

时间:2014-10-22 06:16:30      阅读:151      评论:0      收藏:0      [点我收藏+]

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

 

 

Uva 10689 Yet another Number Sequence (  矩阵快速幂  )

 

 

题意:

就是矩阵快速幂,没什么好说的。

 

分析:

其实还是斐波那契数列。只是最后对应的矩阵不是(1,1)是(a,b)了
MOD = 1;
for( int i = 0; i < m; ++i )
    MOD *= 10;    

 

代码
bubuko.com,布布扣
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
#define MAX_SIZE 2
#define CLR( a, b ) memset( a, b, sizeof(a) )

LL a, b, n, m, t, MOD;

LL M[MAX_SIZE];
inline void scan( LL & x )
{
    char c;
    while( c = getchar(), c < 0 || c > 9 );
    x = c - 0;
    while( c = getchar(), c >= 0 && c <= 9 )    x = x*10 + c - 0;
}

struct Mat
{
    LL mat[MAX_SIZE][MAX_SIZE];

    void init()
    {
        for( int i = 0; i < 2; ++i )
            for( int j = 0; j < 2; ++j )
                mat[i][j] = ( i == j );
    }
    void zero()
    {
        for( int i = 0; i < 2; ++i )
            for( int j = 0; j < 2; ++j )
                mat[i][j] = 0;
    }
    void setv( int v )
    {
        for( int i = 0; i < 2; ++i )
            for( int j = 0; j < 2; ++j )
                mat[i][j] = v;
    }
    Mat operator*( const Mat &b )const
    {
        Mat c;
        c.zero();
        for( int k = 0; k < 2; ++k )
            for( int i = 0; i < 2; ++i )    if( mat[i][k] )
                for( int j = 0; j < 2; ++j )
                    c.mat[i][j] = ( c.mat[i][j] + mat[i][k] * b.mat[k][j] ) % MOD;
        return c;
    }    
    void debug()
    {
        for( int i = 0; i < 2; ++i )
        {
            for( int j = 0; j < 2; ++j )
            {
                if( j != 0 )    putchar(   );
                printf( "%lld", mat[i][j] );
            }
            putchar( \n );
        }
    }
};

Mat fast_mod( Mat a, LL b )
{
    Mat res;
    res.init();
    while( b )
    {
        if( b & 1 )    res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}

void Orz()
{
    Mat c;
    c.setv( 1 );
    c.mat[0][0] = 0;
    //c.debug();        
    scan( t );
    while( t-- )
    {
        scan( a ), scan( b ), scan( n ), scan( m );
        MOD = 1;
        for( int i = 0; i < m; ++i )
            MOD *= 10;    
        //M[0] = a, M[1] = b;
        if( n == 1)
            printf( "%lld\n", a % MOD );
        else if( n == 2 )
            printf( "%lld\n", b % MOD );
        else
        {    
            Mat res = fast_mod( c, n - 2 + 1 );
            LL ans = ( res.mat[1][0] * a + res.mat[1][1] * b ) % MOD;
            printf( "%lld\n", ans );
        }
    }
}

int main()
{
    Orz();    
    return 0;
}
代码君

 

Uva10689 Yet another Number Sequence ( 矩阵快速幂 )

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

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

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